auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testFailoverDuringNomadCommitForPassiveAddition() throws Exception { startNode(1, 1); waitUntil(out.getLog(1, 1), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 1)).getNodeCount(), is(equalTo(1))); startNode(1, 2); waitUntil(out.getLog(1, 2), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 2)).getNodeCount(), is(equalTo(1))); assertThat(configToolInvocation("attach", "-d", "localhost:" + getNodePort(1, 1), "-s", "localhost:" + getNodePort(1, 2)), is(successful())); activateCluster(); int activeNodeId = findActive(1).getAsInt(); String propertySettingString = "stripe.1.node." + activeNodeId + ".tc-properties.failoverAddition=killAddition-commit"; startNode(1, 3); waitUntil(out.getLog(1, 3), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 3)).getNodeCount(), is(equalTo(1))); assertThat(configToolInvocation("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString), is(successful())); assertThat( configToolInvocation("attach", "-f", "-d", "localhost:" + getNodePort(1, findActive(1).getAsInt()), "-s", "localhost:" + getNodePort(1, 3)), is(successful())); assertThat(getUpcomingCluster("localhost", getNodePort(1, 3)).getNodeCount(), is(equalTo(3))); }

Target:
public void testFailoverDuringNomadCommitForPassiveAddition() throws Exception { startNode(1, 1); waitUntil(out.getLog(1, 1), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 1)).getNodeCount(), is(equalTo(1))); startNode(1, 2); waitUntil(out.getLog(1, 2), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 2)).getNodeCount(), is(equalTo(1))); assertThat(configToolInvocation("attach", "-d", "localhost:" + getNodePort(1, 1), "-s", "localhost:" + getNodePort(1, 2)), is(successful())); activateCluster(); int activeId = findActive(1).getAsInt(); int passiveId = findPassives(1)[0]; String propertySettingString = "stripe.1.node." + activeId + ".tc-properties.failoverAddition=killAddition-commit"; startNode(1, 3); waitUntil(out.getLog(1, 3), containsLog("Started the server in diagnostic mode")); assertThat(getUpcomingCluster("localhost", getNodePort(1, 3)).getNodeCount(), is(equalTo(1))); assertThat(configToolInvocation("set", "-s", "localhost:" + getNodePort(1, 1), "-c", propertySettingString), is(successful())); assertThat( configToolInvocation("attach", "-f", "-d", "localhost:" + getNodePort(1, activeId), "-s", "localhost:" + getNodePort(1, 3)), is(successful())); waitUntil(out.getLog(1, 3), containsLog("Moved to State[ PASSIVE-STANDBY ]")); assertThat(getUpcomingCluster("localhost", getNodePort(1, passiveId)).getNodeCount(), is(equalTo(3))); assertThat(getUpcomingCluster("localhost", getNodePort(1, 3)).getNodeCount(), is(equalTo(3))); withTopologyService(1, passiveId, topologyService -> assertTrue(topologyService.isActivated())); withTopologyService(1, 3, topologyService -> assertTrue(topologyService.isActivated())); }
Source:
public static List<IVariable> getLambdaFrameVariables(IStackFrame frame) throws DebugException { List<IVariable> variables = new ArrayList<>(); IThread thread = frame.getThread(); if (LambdaUtils.isLambdaFrame(frame)) { IStackFrame[] stackFrames = thread.getStackFrames(); for (int i = 0; i < Math.min(3, stackFrames.length); ++i) { IStackFrame stackFrame = stackFrames[i]; IVariable[] stackFrameVariables = stackFrame.getVariables(); variables.addAll(Arrays.asList(stackFrameVariables)); } } return Collections.unmodifiableList(variables); }

Target:
public static List<IVariable> getLambdaFrameVariables(IStackFrame frame) throws DebugException { List<IVariable> variables = new ArrayList<>(); if (LambdaUtils.isLambdaFrame(frame)) { IThread thread = frame.getThread(); IStackFrame[] stackFrames = thread.getStackFrames(); for (int i = 0; i < Math.min(3, stackFrames.length); ++i) { IStackFrame stackFrame = stackFrames[i]; IVariable[] stackFrameVariables = stackFrame.getVariables(); variables.addAll(Arrays.asList(stackFrameVariables)); } } return Collections.unmodifiableList(variables); }
Source:
public static Slice toQuadKey(@SqlType(BingTileType.NAME) long input) { return Slices.utf8Slice(BingTile.decode(input).toQuadKey()); }

Target:
public static Slice toQuadKey(@SqlType(BingTileType.NAME) long input) { return utf8Slice(BingTile.decode(input).toQuadKey()); }
Source:
public void shouldCreateProfileAndPreferencesOnUserCreation() throws Exception { final User user = new User().withEmail("test@email.com").withName("testName"); new UserManager(userDao, profileDao, preferenceDao, new String[0]).create(user, false); verify(profileDao).create(any(Profile.class)); verify(preferenceDao).setPreferences(anyString(), anyMapOf(String.class, String.class)); }

Target:
public void shouldCreateProfileAndPreferencesOnUserCreation() throws Exception { final User user = new User().withEmail("test@email.com").withName("testName"); manager.create(user, false); verify(profileDao).create(any(Profile.class)); verify(preferenceDao).setPreferences(anyString(), anyMapOf(String.class, String.class)); }
Source:
public List<RassXmlAgencyEntry> sortRassXmlAgencyEntriesForUpdate(List<RassXmlAgencyEntry> agencies) { AgenciesSortHelper agencySortHelper = new AgenciesSortHelper(); sortAgenciesWithNoReportsToAgency(agencies, agencySortHelper); sortAgenciesWithReportsToAgencyThatHasBeenSorted(agencySortHelper); sortLeftOverAgencies(agencySortHelper); return agencySortHelper.sortedAgencies; }

Target:
public List<RassXmlAgencyEntry> sortRassXmlAgencyEntriesForUpdate(List<RassXmlAgencyEntry> agencies) { AgenciesSortHelper agencySortHelper = new AgenciesSortHelper(); sortAgenciesWithNoReportsToAgency(agencies, agencySortHelper); sortAgenciesWithReportsToAgencyThatHasBeenSorted(agencySortHelper); sortAnyUnsortedAgencies(agencySortHelper); return agencySortHelper.sortedAgencies; }
Source:
public Iterable<Object> executeQuery(Query query) { EntityManager entityManager = emf.createEntityManager(); SQLSchema schema = schemas.get(query.getSchema().getEntityClass()); Preconditions.checkNotNull(schema); SQLQuery sql = toSQL(query, schema); log.debug("SQL Query: " + sql); javax.persistence.Query jpaQuery = entityManager.createNativeQuery(sql.toString()); Pagination pagination = query.getPagination(); if (pagination != null) { jpaQuery.setFirstResult(pagination.getOffset()); jpaQuery.setMaxResults(pagination.getLimit()); if (pagination.isGenerateTotals()) { SQLQuery paginationSQL = toPageTotalSQL(sql); javax.persistence.Query pageTotalQuery = entityManager.createNativeQuery(paginationSQL.toString()); supplyFilterQueryParameters(query, pageTotalQuery); long total = new TimedFunction<>( () -> CoerceUtil.coerce(pageTotalQuery.getSingleResult(), Long.class), "Running Query: " + paginationSQL ).get(); pagination.setPageTotals(total); } } supplyFilterQueryParameters(query, jpaQuery); List<Object> results = new TimedFunction<>(() -> jpaQuery.getResultList(), "Running Query: " + sql).get(); return new SQLEntityHydrator(results, query, dictionary, entityManager).hydrate(); }

Target:
public Iterable<Object> executeQuery(Query query) { EntityManager entityManager = null; try { entityManager = emf.createEntityManager(); SQLSchema schema = schemas.get(query.getSchema().getEntityClass()); Preconditions.checkNotNull(schema); SQLQuery sql = toSQL(query, schema); log.debug("SQL Query: " + sql); javax.persistence.Query jpaQuery = entityManager.createNativeQuery(sql.toString()); Pagination pagination = query.getPagination(); if (pagination != null) { jpaQuery.setFirstResult(pagination.getOffset()); jpaQuery.setMaxResults(pagination.getLimit()); if (pagination.isGenerateTotals()) { SQLQuery paginationSQL = toPageTotalSQL(sql); javax.persistence.Query pageTotalQuery = entityManager.createNativeQuery(paginationSQL.toString()); supplyFilterQueryParameters(query, pageTotalQuery); long total = new TimedFunction<>( () -> CoerceUtil.coerce(pageTotalQuery.getSingleResult(), Long.class), "Running Query: " + paginationSQL ).get(); pagination.setPageTotals(total); } } supplyFilterQueryParameters(query, jpaQuery); List<Object> results = new TimedFunction<>(() -> jpaQuery.getResultList(), "Running Query: " + sql).get(); return new SQLEntityHydrator(results, query, dictionary, entityManager).hydrate(); } finally { if (entityManager != null) { entityManager.close(); } } }
Source:
private void updateOrienteerUserRoleDoc(ODatabaseDocument db, ODocument perspective) { OSecurity security = db.getMetadata().getSecurity(); ORole role = security.getRole(ORIENTEER_USER_ROLE); if (role == null) { ORole reader = security.getRole("reader"); role = security.createRole(ORIENTEER_USER_ROLE, reader, OSecurityRole.ALLOW_MODES.DENY_ALL_BUT); } role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_WIDGET, OrientPermission.READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_DASHBOARD, OrientPermission.READ.getPermissionFlag()); role.grant(OSecurityHelper.FEATURE_RESOURCE, SearchPage.SEARCH_FEATURE, OrientPermission.READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OrienteerUser.CLASS_NAME, 6); role.grant(ResourceGeneric.DATABASE, "cluster", 6); role.getDocument().field(PerspectivesModule.PROP_PERSPECTIVE, perspective); role.save(); }

Target:
private void updateOrienteerUserRoleDoc(ODatabaseDocument db, ODocument perspective) { OSecurity security = db.getMetadata().getSecurity(); ORole role = security.getRole(ORIENTEER_USER_ROLE); if (role == null) { ORole reader = security.getRole("reader"); role = security.createRole(ORIENTEER_USER_ROLE, reader, OSecurityRole.ALLOW_MODES.DENY_ALL_BUT); } role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_WIDGET, READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OWidgetsModule.OCLASS_DASHBOARD, READ.getPermissionFlag()); role.grant(OSecurityHelper.FEATURE_RESOURCE, SearchPage.SEARCH_FEATURE, READ.getPermissionFlag()); role.grant(ResourceGeneric.CLASS, OrienteerUser.CLASS_NAME, OrientPermission.combinedPermission(READ, UPDATE)); role.grant(ResourceGeneric.DATABASE, "cluster", OrientPermission.combinedPermission(READ, UPDATE)); role.getDocument().field(PerspectivesModule.PROP_PERSPECTIVE, perspective); role.save(); }
Source:
public void testApplyStatefulOperatorGetState() throws InterruptedException, IOException, ClassNotFoundException { final ApplyStatefulFunction applyStatefulFunction = new FindMaxIntFunction(); final ApplyStatefulOperator<Integer, Integer> applyStatefulOperator = new ApplyStatefulOperator<>(applyStatefulFunction); final MistDataEvent data10 = new MistDataEvent(10, 0L); final MistDataEvent data20 = new MistDataEvent(20, 1L); final List<MistEvent> result = new LinkedList<>(); applyStatefulOperator.setOutputEmitter(new OutputBufferEmitter(result)); applyStatefulOperator.processLeftData(data10); applyStatefulOperator.processLeftData(data20); final int expectedApplyStatefulOperatorState = 20; final Map<String, Object> operatorState = applyStatefulOperator.getOperatorState(); final int applyStatefulOperatorState = (int)operatorState.get("applyStatefulFunctionState"); Assert.assertEquals(expectedApplyStatefulOperatorState, applyStatefulOperatorState); }

Target:
public void testApplyStatefulOperatorGetState() throws InterruptedException { final ApplyStatefulFunction applyStatefulFunction = new FindMaxIntFunction(); final ApplyStatefulOperator<Integer, Integer> applyStatefulOperator = new ApplyStatefulOperator<>(applyStatefulFunction); final MistDataEvent data10 = new MistDataEvent(10, 0L); final MistDataEvent data20 = new MistDataEvent(20, 1L); final List<MistEvent> result = new LinkedList<>(); applyStatefulOperator.setOutputEmitter(new OutputBufferEmitter(result)); applyStatefulOperator.processLeftData(data10); applyStatefulOperator.processLeftData(data20); final int expectedApplyStatefulOperatorState = 20; final Map<String, Object> operatorState = applyStatefulOperator.getOperatorState(); final int applyStatefulOperatorState = (int)operatorState.get("applyStatefulFunctionState"); Assert.assertEquals(expectedApplyStatefulOperatorState, applyStatefulOperatorState); }
Source:
public Cookie getCookie(String cookieName) { throw new IllegalStateException("Not supported yet"); }

Target:
public Cookie getCookie(String cookieName) { throw new UnsupportedOperationException("Not supported yet"); }
Source:
private static void buildHashTableStrict( Block keyBlock, int keyOffset, int keyCount, MethodHandle keyBlockEquals, MethodHandle keyBlockHashCode, int[] outputHashTable, int hashTableOffset, int hashTableSize) throws DuplicateMapKeyException { for (int i = 0; i < keyCount; i++) { int hash = getHashPosition(keyBlock, keyOffset + i, keyBlockHashCode, hashTableSize); while (true) { if (outputHashTable[hashTableOffset + hash] == -1) { outputHashTable[hashTableOffset + hash] = i; break; } Boolean isDuplicateKey; try { isDuplicateKey = (Boolean) keyBlockEquals.invokeExact(keyBlock, keyOffset + i, keyBlock, keyOffset + outputHashTable[hashTableOffset + hash]); } catch (RuntimeException e) { throw e; } catch (Throwable throwable) { throw new RuntimeException(throwable); } if (isDuplicateKey == null) { throw new PrestoException(NOT_SUPPORTED, "map key cannot be indeterminate"); } if (isDuplicateKey) { throw new DuplicateMapKeyException(keyBlock, keyOffset + i); } hash++; if (hash == hashTableSize) { hash = 0; } } } }

Target:
private static void buildHashTableStrict( Block keyBlock, int keyOffset, int keyCount, MethodHandle keyBlockEquals, MethodHandle keyBlockHashCode, int[] outputHashTable, int hashTableOffset, int hashTableSize) throws DuplicateMapKeyException { for (int i = 0; i < keyCount; i++) { int hash = getHashPosition(keyBlock, keyOffset + i, keyBlockHashCode, hashTableSize); while (true) { if (outputHashTable[hashTableOffset + hash] == -1) { outputHashTable[hashTableOffset + hash] = i; break; } Boolean isDuplicateKey; try { isDuplicateKey = (Boolean) keyBlockEquals.invokeExact(keyBlock, keyOffset + i, keyBlock, keyOffset + outputHashTable[hashTableOffset + hash]); } catch (RuntimeException e) { throw e; } catch (Throwable throwable) { throw new RuntimeException(throwable); } if (isDuplicateKey == null) { throw new PrestoException(NOT_SUPPORTED, "map key cannot be null or contain nulls"); } if (isDuplicateKey) { throw new DuplicateMapKeyException(keyBlock, keyOffset + i); } hash++; if (hash == hashTableSize) { hash = 0; } } } }
Source:
public NodeMetadata apply(Container container) { String group = "jclouds"; String name = "container"; NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); nodeMetadataBuilder.id(container.getId()) .name(name) .group(group); LocationBuilder locationBuilder = new LocationBuilder(); locationBuilder.description(""); locationBuilder.id(""); locationBuilder.scope(LocationScope.HOST); nodeMetadataBuilder.location(locationBuilder.build()); if (container.getStatus() != null) { nodeMetadataBuilder.status(container.getStatus().contains("Up") ? NodeMetadata.Status.RUNNING : NodeMetadata.Status.SUSPENDED); } else { nodeMetadataBuilder.status(container.getState().isRunning() ? NodeMetadata.Status.RUNNING : NodeMetadata.Status.SUSPENDED); } nodeMetadataBuilder.imageId(container.getImage()); nodeMetadataBuilder.loginPort(getLoginPort(container)); nodeMetadataBuilder.publicAddresses(getPublicIpAddresses()); nodeMetadataBuilder.privateAddresses(getPrivateIpAddresses(container)); nodeMetadataBuilder.operatingSystem(OperatingSystem.builder().description("my description") .family(OsFamily.UNRECOGNIZED) .build()); return nodeMetadataBuilder.build(); }

Target:
public NodeMetadata apply(Container container) { String name = cleanUpName(container.getName()); String group = nodeNamingConvention.extractGroup(name); NodeMetadataBuilder builder = new NodeMetadataBuilder(); builder.ids(container.getId()) .name(name) .group(group) .hostname(container.getContainerConfig().getHostname()) .hardware(new HardwareBuilder() .id("") .ram(container.getContainerConfig().getMemory()) .processor(new Processor(container.getContainerConfig().getCpuShares(), container.getContainerConfig().getCpuShares())) .build()); builder.status(toPortableStatus.apply(container.getState())); builder.imageId(container.getImage()); builder.loginPort(getLoginPort(container)); builder.publicAddresses(getPublicIpAddresses()); builder.privateAddresses(getPrivateIpAddresses(container)); builder.location(Iterables.getOnlyElement(locations.get())); Image image = images.get().get(container.getImage()); builder.imageId(image.getId()); builder.operatingSystem(image.getOperatingSystem()); return builder.build(); }
Source:
public Object invoke(Object proxy, Method method, Object[] args) { setCalled = method.getName().startsWith("set"); boolean argNull = args.length > 1 && args[1] == null; setNull = "setNull".equals(method.getName()) || argNull; return null; }

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws SQLException { if (method.getName().equals("unwrap") && args.length == 1 && method.getParameterTypes()[0].equals(Class.class)) { throw new SQLException("The current implementation of DefineNamedBindings is incompatible with " + "arguments that rely on java.sql.Wrapper.unwrap(Class<?>)"); } if (method.getName().startsWith("set")) { setCalled = true; boolean argNull = args.length > 1 && args[1] == null; setNull = argNull || "setNull".equals(method.getName()); } return defaultValue(method.getReturnType()); }
Source:
private void minimizeWorkload(SubscriptionAssignmentView state, SubscriptionAssignmentView.Transformer transformer) { Set<SubscriptionAssignment> redundant = new HashSet<>(); for (SubscriptionName subscriptionName : state.getSubscriptions()) { int diff = state.getAssignmentsCountForSubscription(subscriptionName) - consumersPerSubscription; if (diff > 0) { Iterator<SubscriptionAssignment> iterator = state.getAssignmentsForSubscription(subscriptionName).iterator(); while (diff > 0 && iterator.hasNext()) { SubscriptionAssignment assignment = iterator.next(); if (assignment.isAutoAssigned()) { redundant.add(assignment); diff--; } } } } redundant.forEach(transformer::removeAssignment); }

Target:
private void minimizeWorkload(SubscriptionAssignmentView state, SubscriptionAssignmentView.Transformer transformer) { state.getSubscriptions() .stream() .flatMap(subscriptionName -> findRedundantAssignments(state, subscriptionName)) .forEach(transformer::removeAssignment); }
Source:
public void removePartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { assignedPartitionIds.remove(partitionIdMap.get(partitionIdStr)); for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionRemoved(partitionId); } logger.info("Removed partition to current VCR: ", partitionIdStr); } else { logger.trace("Partition not in clusterMap on remove.", partitionIdStr); metrics.partitionIdNotInClusterMapOnRemove.inc(); } }

Target:
public void removePartition(String partitionIdStr) { PartitionId partitionId = partitionIdMap.get(partitionIdStr); if (partitionId != null) { if (assignedPartitionIds.remove(partitionId)) { for (VirtualReplicatorClusterListener listener : listeners) { listener.onPartitionRemoved(partitionId); } logger.info("Partition is removed from current VCR: {}.", partitionIdStr, vcrInstanceName); } else { logger.info("Partition not exists on current VCR: {}", partitionIdStr, vcrInstanceName); } } else { logger.error("Partition not in clusterMap on remove.", partitionIdStr); metrics.partitionIdNotInClusterMapOnRemove.inc(); } }
Source:
private Element getDownloadElement() throws IOException { Element releaseContainer = getLatestReleaseElement().select("div.release-body ul.release-downloads").first(); Iterator<Element> iter = releaseContainer.select("li a").iterator(); LinkedHashSet<Element> assets = new LinkedHashSet<Element>(); while (iter.hasNext()) { Element button = iter.next(); if (button.hasClass("button") && button.hasClass("primary") && button.hasAttr("href")) assets.add(button); } switch (assets.size()) { case 0: throw new IOException("No releases found for this mod"); case 1: Iterator<Element> i = assets.iterator(); return i.next(); default: Iterator<Element> j = assets.iterator(); HashMap<String, Element> releases = new HashMap<String, Element>(); while (j.hasNext()) { Element dl = j.next(); releases.put(dl.attr("href").substring(dl.attr("href").lastIndexOf('/') + 1), dl); } if (downloadAsset != null && releases.containsKey(downloadAsset)) return releases.get(downloadAsset); downloadAsset = (String) JOptionPane.showInputDialog(null, "Which variant of the mod should be used?", "Multiple Downloads Available", JOptionPane.QUESTION_MESSAGE, null, releases.keySet().toArray(), releases.keySet().toArray()[0]); if (downloadAsset == null) throw new IOException("You must select a download to use the mod!"); return releases.get(downloadAsset); } }

Target:
private Element getDownloadElement() throws IOException { LinkedHashSet<Element> assets = new LinkedHashSet<>(getLatestReleaseElement().select("div.release-body ul.release-downloads").first().select("li a.primary")); switch (assets.size()) { case 0: { throw new IOException("No releases found for this mod"); } case 1: { return assets.iterator().next(); } default: { HashMap<String, Element> releases = new HashMap<>(); for (Element dl : assets){ releases.put(dl.attr("href").substring(dl.attr("href").lastIndexOf('/') + 1), dl); } if (downloadAsset != null && releases.containsKey(downloadAsset)) return releases.get(downloadAsset); downloadAsset = (String) JOptionPane.showInputDialog(null, "Which variant of the mod should be used?", "Multiple Downloads Available", JOptionPane.QUESTION_MESSAGE, null, releases.keySet().toArray(), releases.keySet().toArray()[0]); if (downloadAsset == null) throw new IOException("You must select a download to use the mod!"); return releases.get(downloadAsset); } } }
Source:
public void addElement(int x, int y, int z) { elementList.add(new GhostGroupElement(x, y, z, Eln.ghostBlock, GhostBlock.tCube)); }

Target:
public void addElement(int x, int y, int z) { elementList.add(new GhostGroupElement(x, y, z, ModBlock.ghostBlock, GhostBlock.tCube)); }
Source:
public void onClose() { superOnClose(); dataTypesPage.disableShortcuts(); super.onClose(); }

Target:
public void onClose() { superDoClose(); dataTypesPage.disableShortcuts(); super.onClose(); }
Source:
private void updateState(AuthState state) { if (this.state != null && this.state == state) { return; } this.state = state; switch (state) { case AUTH_START: if (authType != null && authType.equals("auth_type_email")) { showFragment(new SignEmailFragment(), false, false); } else if (authType != null && authType.equals("auth_type_phone")){ showFragment(new SignPhoneFragment(), false, false); } break; case CODE_VALIDATION_PHONE: case CODE_VALIDATION_EMAIL: if((state==AuthState.CODE_VALIDATION_EMAIL && authType.equals("auth_type_phone")) || (state==AuthState.CODE_VALIDATION_PHONE && authType.equals("auth_type_email"))){ updateState(AuthState.AUTH_START); break; } Fragment signInFragment = new SignInFragment(); Bundle args = new Bundle(); args.putString("authType", state==AuthState.CODE_VALIDATION_EMAIL?SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE); signInFragment.setArguments(args); showFragment(signInFragment, false, false); break; case GET_OAUTH_PARAMS: executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params"); break; case COMPLETE_OAUTH: if(authType.equals("auth_type_phone")){ updateState(AuthState.AUTH_START); break; } showFragment(new SignEmailFragment(), false, false); startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG); break; case SIGN_UP: showFragment(new SignUpFragment(), false, false); break; case LOGGED_IN: messenger().trackAuthSuccess(); finish(); startActivity(new Intent(this, MainActivity.class)); break; } }

Target:
private void updateState(AuthState state) { if (this.state != null && this.state == state) { return; } this.state = state; switch (state) { case AUTH_START: if (authType == AUTH_TYPE_EMAIL) { showFragment(new SignEmailFragment(), false, false); } else if (authType == AUTH_TYPE_PHONE) { showFragment(new SignPhoneFragment(), false, false); } break; case CODE_VALIDATION_PHONE: case CODE_VALIDATION_EMAIL: if ((state == AuthState.CODE_VALIDATION_EMAIL && authType == AUTH_TYPE_PHONE) || (state == AuthState.CODE_VALIDATION_PHONE && authType == AUTH_TYPE_EMAIL)) { updateState(AuthState.AUTH_START); break; } Fragment signInFragment = new SignInFragment(); Bundle args = new Bundle(); args.putString("authType", state == AuthState.CODE_VALIDATION_EMAIL ? SignInFragment.AUTH_TYPE_EMAIL : SignInFragment.AUTH_TYPE_PHONE); signInFragment.setArguments(args); showFragment(signInFragment, false, false); break; case GET_OAUTH_PARAMS: executeAuth(messenger().requestGetOAuthParams(), "get_oauth_params"); break; case COMPLETE_OAUTH: if (authType == AUTH_TYPE_PHONE) { updateState(AuthState.AUTH_START); break; } showFragment(new SignEmailFragment(), false, false); startActivityForResult(new Intent(this, OAuthDialogActivity.class), OAUTH_DIALOG); break; case SIGN_UP: showFragment(new SignUpFragment(), false, false); break; case LOGGED_IN: messenger().trackAuthSuccess(); finish(); startActivity(new Intent(this, MainActivity.class)); break; } }
Source:
public AnalyzedRelation visitQueriedSelectRelation(QueriedSelectRelation<?> relation, CoordinatorTxnCtx context) { AnalyzedRelation subRelation = relation.subRelation(); AnalyzedRelation normalizedSubRelation = process(subRelation, context); QueriedSelectRelation<?> newRelation; if (normalizedSubRelation instanceof FieldResolver) { EvaluatingNormalizer evalNormalizer = new EvaluatingNormalizer( functions, RowGranularity.CLUSTER, null, ((FieldResolver) normalizedSubRelation)); if (subRelation == normalizedSubRelation) { newRelation = relation.map(s -> evalNormalizer.normalize(s, context)); } else { newRelation = relation .replaceSubRelation(normalizedSubRelation) .map(s -> evalNormalizer.normalize(s, context)); } } else if (subRelation == normalizedSubRelation) { newRelation = relation; } else { newRelation = relation.replaceSubRelation(normalizedSubRelation); } WhereClauseValidator.validate(newRelation.where().queryOrFallback()); return newRelation; }

Target:
public AnalyzedRelation visitQueriedSelectRelation(QueriedSelectRelation<?> relation, CoordinatorTxnCtx context) { AnalyzedRelation normalizedSubRelation = process(relation.subRelation(), context); final QueriedSelectRelation<?> newRelation; if (normalizedSubRelation instanceof FieldResolver) { EvaluatingNormalizer evalNormalizer = new EvaluatingNormalizer( functions, RowGranularity.CLUSTER, null, ((FieldResolver) normalizedSubRelation)); newRelation = relation .replaceSubRelation(normalizedSubRelation) .map(s -> evalNormalizer.normalize(s, context)); } else { newRelation = relation.replaceSubRelation(normalizedSubRelation); } WhereClauseValidator.validate(newRelation.where().queryOrFallback()); return newRelation; }
Source:
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( trainingOperationResponse -> trainingOperationResponse.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(extractedForm -> { extractedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); }); extractedForm.getPages().forEach(formPage -> { System.out.printf("Page Angle: %s%n", formPage.getTextAngle()); System.out.printf("Page Dimension unit: %s%n", formPage.getUnit()); System.out.println(); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string }

Target:
public void beginRecognizeCustomFormsFromUrl() { String analyzeFilePath = "{file_source_url}"; String modelId = "{model_id}"; formRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl(analyzeFilePath, modelId).subscribe( recognizePollingOperation -> recognizePollingOperation.getFinalResult().subscribe(recognizedForms -> recognizedForms.forEach(recognizedForm -> { recognizedForm.getFields().forEach((fieldText, fieldValue) -> { System.out.printf("Page number: %s%n", fieldValue.getPageNumber()); System.out.printf("Field text: %s%n", fieldText); System.out.printf("Field value: %s%n", fieldValue.getFieldValue()); System.out.printf("Confidence score: %.2f%n", fieldValue.getConfidence()); }); }) ) ); END: com.azure.ai.formrecognizer.FormRecognizerAsyncClient.beginRecognizeCustomFormsFromUrl#string-string }
Source:
private void checkDeltaByteArrayProblem(FileMetaData meta, Configuration conf, BlockMetaData block) { if (conf.getBoolean(ParquetInputFormat.SPLIT_FILES, true)) { Set<Encoding> encodings = new HashSet<Encoding>(); for (ColumnChunkMetaData column : block.getColumns()) { try { encodings.addAll(column.getEncodings()); } catch (KeyAccessDeniedException e) { LOG.warn("checkDeltaByteArrayProblem: Bypass encrypted column because key unavailable", column); } } for (Encoding encoding : encodings) { if (CorruptDeltaByteArrays.requiresSequentialReads(meta.getCreatedBy(), encoding)) { throw new ParquetDecodingException("Cannot read data due to " + "PARQUET-246: to read safely, set " + SPLIT_FILES + " to false"); } } } }

Target:
private void checkDeltaByteArrayProblem(FileMetaData meta, Configuration conf, BlockMetaData block) { if (conf.getBoolean(ParquetInputFormat.SPLIT_FILES, true)) { Set<Encoding> encodings = new HashSet<Encoding>(); for (ColumnChunkMetaData column : block.getColumns()) { encodings.addAll(column.getEncodings()); } for (Encoding encoding : encodings) { if (CorruptDeltaByteArrays.requiresSequentialReads(meta.getCreatedBy(), encoding)) { throw new ParquetDecodingException("Cannot read data due to " + "PARQUET-246: to read safely, set " + SPLIT_FILES + " to false"); } } } }
Source:
public HiveMetaStore(Configuration conf, HdfsSinkConnectorConfig connectorConfig) throws HiveMetaStoreException { HiveConf hiveConf = new HiveConf(conf, HiveConf.class); String hiveConfDir = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_CONF_DIR_CONFIG); String hiveMetaStoreURIs = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_METASTORE_URIS_CONFIG); if (!hiveConfDir.equals("")) { hiveConf.addResource(new Path(hiveConfDir, "/hive-site.xml")); } hiveConf.set("hive.metastore.uris", hiveMetaStoreURIs); try { client = HCatUtil.getHiveMetastoreClient(hiveConf); } catch (IOException | MetaException e) { throw new HiveMetaStoreException(e); } }

Target:
public HiveMetaStore(Configuration conf, HdfsSinkConnectorConfig connectorConfig) throws HiveMetaStoreException { HiveConf hiveConf = new HiveConf(conf, HiveConf.class); String hiveConfDir = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_CONF_DIR_CONFIG); String hiveMetaStoreURIs = connectorConfig.getString(HdfsSinkConnectorConfig.HIVE_METASTORE_URIS_CONFIG); if (!hiveConfDir.equals("")) { String hiveSitePath = hiveConfDir + "/hive-site.xml"; File hiveSite = new File(hiveSitePath); if (!hiveSite.exists()) { log.warn("hive-site.xml does not exist in provided Hive configuration directory {}.", hiveConf); } hiveConf.addResource(new Path(hiveSitePath)); } hiveConf.set("hive.metastore.uris", hiveMetaStoreURIs); try { client = HCatUtil.getHiveMetastoreClient(hiveConf); } catch (IOException | MetaException e) { throw new HiveMetaStoreException(e); } }
Source:
private int determineMaxExtractedTextLength( DatabaseMetaData metaData ) { ResultSet resultSet = null; try { resultSet = metaData.getColumns(null, null, null, EXTRACTED_TEXT_COLUMN_NAME); return resultSet.next() ? resultSet.getInt("COLUMN_SIZE") : DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } catch (SQLException e) { LOGGER.debug(e, "Cannot determine the maximum size of the column which holds the extracted text. Defaulting to {0}", DEFAULT_MAX_EXTRACTED_TEXT_LENGTH); return DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } finally { tryToClose(resultSet); } }

Target:
private int determineMaxExtractedTextLength( DatabaseMetaData metaData ) { ResultSet resultSet = null; try { String tableName = this.tableName; if (metaData.storesLowerCaseIdentifiers()) { tableName = tableName.toLowerCase(); } else if (metaData.storesUpperCaseIdentifiers()) { tableName = tableName.toUpperCase(); } resultSet = metaData.getColumns(null, null, tableName, EXTRACTED_TEXT_COLUMN_NAME); return resultSet.next() ? resultSet.getInt("COLUMN_SIZE") : DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } catch (SQLException e) { LOGGER.debug(e, "Cannot determine the maximum size of the column which holds the extracted text. Defaulting to {0}", DEFAULT_MAX_EXTRACTED_TEXT_LENGTH); return DEFAULT_MAX_EXTRACTED_TEXT_LENGTH; } finally { tryToClose(resultSet); } }
Source:
void updateLabel() { String msg; ICluster cluster = AccountService.getDefault().getModel().getClusters().get(0); if (removed || cluster.getAccounts().isEmpty()) { msg = "No configured accounts"; } else { IAccount account = cluster.getAccounts().get(0); msg = account.getId() + " account configured valid until " + Date.from(Instant.ofEpochMilli(account.getAccessTokenExpiryTime())); } label.setText(msg); }

Target:
void updateLabel() { String msg; if (removed || osioCluster.getAccounts().isEmpty()) { msg = "No configured accounts"; } else { IAccount account = osioCluster.getAccounts().get(0); msg = account.getId() + " account configured valid until " + Date.from(Instant.ofEpochMilli(account.getAccessTokenExpiryTime())); } label.setText(msg); }
Source:
public static boolean deepEquals(final @Nullable Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> class1 = o1.getClass(); Class<?> class2 = o2.getClass(); if (!class1.equals(class2)) { return false; } if (class1.isArray()) { int length = Array.getLength(o1); if (Array.getLength(o2) != length) { return false; } for (int i = 0; i < length; i++) { if (!deepEquals(Array.get(o1, i), Array.get(o2, i))) { return false; } } return true; } else if (o1 instanceof Collection) { Collection<?> c1 = (Collection<?>) o1; Collection<?> c2 = (Collection<?>) o2; int size = c1.size(); if (c2.size() != size) { return false; } if (o1 instanceof Set) { for (Object e1 : c1) { boolean contains = false; for (Object e2 : c2) { if (deepEquals(e1, e2)) { contains = true; break; } } if (!contains) { return false; } } return true; } Iterator<?> i1 = c1.iterator(); Iterator<?> i2 = c2.iterator(); while (i1.hasNext()) { if (!deepEquals(i1.next(), i2.next())) { return false; } } return true; } return o1.equals(o2); }

Target:
public static boolean deepEquals(final @Nullable Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> class1 = o1.getClass(); Class<?> class2 = o2.getClass(); if (!class1.equals(class2)) { return false; } if (class1.isArray()) { int length = Array.getLength(o1); if (Array.getLength(o2) != length) { return false; } for (int i = 0; i < length; i++) { if (!deepEquals(Array.get(o1, i), Array.get(o2, i))) { return false; } } return true; } else if (o1 instanceof Collection) { Collection<?> c1 = (Collection<?>) o1; Collection<?> c2 = (Collection<?>) o2; int size = c1.size(); if (c2.size() != size) { return false; } if (o1 instanceof Set && !(o1 instanceof SortedSet<?>)) { for (Object e1 : c1) { boolean contains = false; for (Object e2 : c2) { if (deepEquals(e1, e2)) { contains = true; break; } } if (!contains) { return false; } } return true; } Iterator<?> i1 = c1.iterator(); Iterator<?> i2 = c2.iterator(); while (i1.hasNext()) { if (!deepEquals(i1.next(), i2.next())) { return false; } } return true; } return o1.equals(o2); }
Source:
public Collection<Object> convertDimensionValue(String name, String value) { List<Object> result = new ArrayList<Object>(); try { String typeName = getDomainDatatype(name); if (typeName != null) { Class<?> type = Class.forName(typeName); if (type == java.util.Date.class) { result.addAll(new TimeParser().parse(value)); } else if ((type == java.lang.Double.class || type == java.lang.Float.class) && !value.contains(",")) { result.add(parseNumberOrRange(value)); } else { for (String element : value.split(",")) { result.add(Converters.convert(element, type)); } } } else { result.add(value); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to convert dimension value: ", e); result.add(value); } return result; }

Target:
public Collection<Object> convertDimensionValue(String name, String value) { List<Object> result = new ArrayList<Object>(); try { String typeName = getDomainDatatype(name); if (typeName != null) { Class<?> type = Class.forName(typeName); if (type == java.util.Date.class) { result.addAll(new TimeParser().parse(value)); } else if (Number.class.isAssignableFrom(type) && !value.contains(",")) { result.add(parseNumberOrRange(value)); } else { for (String element : value.split(",")) { result.add(Converters.convert(element, type)); } } } else { result.add(value); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to convert dimension value: ", e); result.add(value); } return result; }
Source:
public void testConsistentIdNotConfigured() throws Exception { Ignite ignite = startGrid(0); assertNull(ignite.configuration().getConsistentId()); assertTrue(ADDR_WITH_PORT_PATTERN.matcher(ignite.cluster().localNode().consistentId().toString()).find()); info("Consistent id in that case: " + ignite.cluster().localNode().consistentId()); }

Target:
public void testConsistentIdNotConfigured() throws Exception { Ignite ignite = startGrid(0); assertNull(ignite.configuration().getConsistentId()); assertTrue(ADDR_WITH_PORT_PATTERN.matcher(ignite.cluster().localNode().consistentId().toString()).find()); info("Consistent ID: " + ignite.cluster().localNode().consistentId()); }
Source:
protected Collection<Asset> getNewestAssets() throws IOException { JsonObject assetsElement = getLatestReleaseElement(); Collection<Asset> assets = new LinkedList<>(); JsonArray jsonArray = assetsElement.get("assets").getAsJsonArray(); for(int index = 0; index < jsonArray.size(); index++) { JsonObject jsonObject = jsonArray.get(index).getAsJsonObject(); assets.add(new Asset( jsonObject.get("name").getAsString(), new URL( jsonObject.get("browser_download_url").getAsString()) )); } return assets; }

Target:
protected Collection<Asset> getNewestAssets() throws IOException { JsonObject assetsElement = getLatestReleaseElement(); Collection<Asset> assets = new LinkedList<>(); JsonArray jsonArray = assetsElement.get("assets").getAsJsonArray(); for(JsonElement element: jsonArray) { JsonObject jsonObject = element.getAsJsonObject(); assets.add(new Asset( jsonObject.get("name").getAsString(), new URL( jsonObject.get("browser_download_url").getAsString()) )); } return assets; }
Source:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}" + ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool = resolverUtil.resolvePool(pool); pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }

Target:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}" + ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }
Source:
private JSONArray buildWarnings() { try { String warningsText = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("warnings.json")); JSONArray warnings = JSONArray.fromObject(warningsText); return warnings; } catch (IOException e) { return new JSONArray(); } }

Target:
private JSONArray buildWarnings() throws IOException { String warningsText = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("warnings.json")); JSONArray warnings = JSONArray.fromObject(warningsText); return warnings; }
Source:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest.setNotes("some notes"); LoanTransaction loanTransaction = loanService.executeJSONTransactionRequest(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction); } else { System.out.println( "The loan amount does not meet the prerequisites, therefore its interest rate will not be updated."); } }

Target:
public static void testChangeInterestRateForActiveRevolvingCreditLoans() throws MambuApiException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println("\nIn " + methodName); LoansService loanService = MambuAPIFactory.getLoanService(); AccountState accountState = loanService.getLoanAccount(NEW_LOAN_ACCOUNT_ID).getAccountState(); LoanProductType loanProductType = demoProduct.getLoanProductType(); if (loanProductType.equals(LoanProductType.REVOLVING_CREDIT) && accountState.equals(AccountState.ACTIVE)) { JSONTransactionRequest jsonTransactionRequest = new JSONTransactionRequest(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 1); jsonTransactionRequest.setDate(calendar.getTime()); jsonTransactionRequest.setRate(new BigDecimal(10)); jsonTransactionRequest.setNotes("some notes"); LoanTransaction loanTransaction = loanService.executeJSONTransactionRequest(NEW_LOAN_ACCOUNT_ID, LoanTransactionType.INTEREST_RATE_CHANGED, jsonTransactionRequest); System.out.println("The interest rate was edited for the loan account " + NEW_LOAN_ACCOUNT_ID + ". Transaction ID = " + loanTransaction); } else { System.out.println( "The loan account does not meet the prerequisites, therefore its interest rate will not be updated."); } }
Source:
private BufferAggregator getBuffer() { System.out.println("In getBuffer"); BufferAggregator result; if (this.buffers.isEmpty() && this.numBuffs < this.maxBuffs) { System.out.println("Allocating buffer aggregator"); result = new BufferAggregator(this.buffSize); this.numBuffs++; } else { try { System.out.println("Attempting to take buffer aggregator from queue"); result = this.buffers.take(); } catch (InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException("BufferedUpload thread interrupted. Thread:" + Thread.currentThread().getId())); } } return result; }

Target:
private BufferAggregator getBuffer() { System.out.println("In getBuffer"); BufferAggregator result; if (this.buffers.isEmpty() && this.numBuffs < this.maxBuffs) { System.out.println("Allocating buffer aggregator"); result = new BufferAggregator(this.buffSize); this.numBuffs++; } else { try { System.out.println("Attempting to take buffer aggregator from queue"); System.out.println("Size of buffer: " + this.buffers.remainingCapacity()); System.out.println("Num buffs: " + this.numBuffs); System.out.println("Max buffs: " + this.maxBuffs); result = this.buffers.take(); } catch (InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException("BufferedUpload thread interrupted. Thread:" + Thread.currentThread().getId())); } } return result; }
Source:
public void ensureOldMapsRemoved() { for (Cache<Object, Object> cache : caches(CACHE_NAME)) { DataContainer dc = TestingUtil.extractComponent(cache, DataContainer.class); if (!(dc instanceof DefaultSegmentedDataContainer)) { throw new AssertionError("Test requires DefaultSegmentedDataContainer impl"); } DefaultSegmentedDataContainer segmentedDataContainer = (DefaultSegmentedDataContainer) dc; DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); Address address = cache.getCacheManager().getAddress(); Set<Integer> segments = dm.getReadConsistentHash().getSegmentsForOwner(address); int mapCount = 0; for (int i = 0; i < segmentedDataContainer.maps.length(); ++i) { if (segmentedDataContainer.maps.get(i) != null) { assertTrue("Segment " + i + " has non null map, but wasn't owned by node: " + address + "!", segments.contains(i)); mapCount++; } } assertEquals(mapCount, segments.size()); } }

Target:
public void ensureOldMapsRemoved() { for (Cache<Object, Object> cache : caches(CACHE_NAME)) { DataContainer dc = TestingUtil.extractComponent(cache, DataContainer.class); assertTrue(dc instanceof DefaultSegmentedDataContainer); DefaultSegmentedDataContainer segmentedDataContainer = (DefaultSegmentedDataContainer) dc; DistributionManager dm = TestingUtil.extractComponent(cache, DistributionManager.class); Address address = cache.getCacheManager().getAddress(); Set<Integer> segments = dm.getReadConsistentHash().getSegmentsForOwner(address); int mapCount = 0; for (int i = 0; i < segmentedDataContainer.maps.length(); ++i) { if (segmentedDataContainer.maps.get(i) != null) { assertTrue("Segment " + i + " has non null map, but wasn't owned by node: " + address + "!", segments.contains(i)); mapCount++; } } assertEquals(mapCount, segments.size()); } }
Source:
public void run(final double[] values, final int limit, final boolean infectious_nans, final MutableNumericType dp) { if (limit < 1) { throw new IllegalDataException("Limit must be greater than 0"); } double sum = 0; int nans = 0; for (int i = 0; i < limit; i++) { if (Double.isNaN(values[i]) && !infectious_nans) { nans++; continue; } sum += values[i]; } if (nans == limit) { dp.resetValue(Double.NaN); } else { dp.resetValue(sum); } }

Target:
public void run(final double[] values, final int limit, final boolean infectious_nans, final MutableNumericType dp) { if (limit < 1) { throw new IllegalDataException("Limit must be greater than 0"); } double sum = 0; int nans = 0; for (int i = 0; i < limit; i++) { if (Double.isNaN(values[i]) && !infectious_nans) { nans++; continue; } sum += values[i]; } if (nans == limit || (nans > 0 && infectious_nans)) { dp.resetValue(Double.NaN); } else { dp.resetValue(sum); } }
Source:
public void testPublish() { byte[] testBytes = {}; String testString = "Test"; when(urlService.inputStreamToByteArray(inputStream)).thenReturn(testBytes); when(facebookService.publishToFacebook(any(byte[].class), any(String.class), any(String.class), any(String.class), any(String.class))).thenReturn(testString); Response response = resource.publish(key, "Test", inputStream, contentDisposition, "photo", "Test", "Test"); String result = (String) response.getEntity(); assertEquals(response.getStatusInfo(), Response.Status.OK); assertEquals(result, "Test"); }

Target:
public void testPublish() { byte[] testBytes = {}; when(urlService.inputStreamToByteArray(inputStream)).thenReturn(testBytes); when(facebookService.publishToFacebook(any(byte[].class), any(String.class), any(String.class), any(String.class), any(String.class))).thenReturn("Test"); Response response = resource.publish(key, "Test", inputStream, contentDisposition, "photo", "Test", "Test"); String result = (String) response.getEntity(); assertEquals(response.getStatusInfo(), Response.Status.OK); assertEquals(result, "Test"); }