repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
HardikDR/kubernetes | test/images/porter/Makefile | 920 | # Use:
#
# `make porter` will build porter.
# `make tag` will suggest a tag.
# `make container` will build a container-- you must supply a tag.
# `make push` will push the container-- you must supply a tag.
REPO ?= gcr.io/google_containers
SUGGESTED_TAG = $(shell git rev-parse --verify HEAD)
porter: porter.go
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-w' ./porter.go
tag:
@echo "If all relevant changes are committed, suggest using TAG=$(SUGGESTED_TAG)"
@echo "$$ make container TAG=$(SUGGESTED_TAG)"
@echo "or"
@echo "$$ make push TAG=$(SUGGESTED_TAG)"
container:
$(if $(TAG),,$(error TAG is not defined. Use 'make tag' after committing changes to see a suggestion))
docker build -t $(REPO)/porter:$(TAG) .
push:
$(if $(TAG),,$(error TAG is not defined. Use 'make tag' after committing changes to see a suggestion))
gcloud docker push $(REPO)/porter:$(TAG)
clean:
rm -f porter
| apache-2.0 |
belliottsmith/cassandra | test/unit/org/apache/cassandra/auth/CassandraRoleManagerTest.java | 7254 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.auth;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Iterables;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.SchemaConstants;
import org.apache.cassandra.schema.TableMetadata;
import org.apache.cassandra.service.StorageService;
import static org.apache.cassandra.auth.AuthTestUtils.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CassandraRoleManagerTest
{
@BeforeClass
public static void setupClass()
{
SchemaLoader.prepareServer();
// create the system_auth keyspace so the IRoleManager can function as normal
SchemaLoader.createKeyspace(SchemaConstants.AUTH_KEYSPACE_NAME,
KeyspaceParams.simple(1),
Iterables.toArray(AuthKeyspace.metadata().tables, TableMetadata.class));
// We start StorageService because confirmFastRoleSetup confirms that CassandraRoleManager will
// take a faster path once the cluster is already setup, which includes checking MessagingService
// and issuing queries with QueryProcessor.process, which uses TokenMetadata
DatabaseDescriptor.daemonInitialization();
StorageService.instance.initServer(0);
AuthCacheService.initializeAndRegisterCaches();
}
@Before
public void setup() throws Exception
{
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES).truncateBlocking();
ColumnFamilyStore.getIfExists(SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS).truncateBlocking();
}
@Test
public void getGrantedRolesImplMinimizesReads()
{
// IRoleManager::getRoleDetails was not in the initial API, so a default impl
// was added which uses the existing methods on IRoleManager as primitive to
// construct the Role objects. While this will work for any IRoleManager impl
// it is inefficient, so CassandraRoleManager has its own implementation which
// collects all of the necessary info with a single query for each granted role.
// This just tests that that is the case, i.e. we perform 1 read per role in the
// transitive set of granted roles
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// simple role with no grants
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// single level of grants
grantRolesTo(roleManager, ROLE_A, ROLE_B, ROLE_C);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
// Check that when granted roles appear multiple times in parallel levels of the hierarchy, we don't
// do redundant reads. E.g. here role_b_1, role_b_2 and role_b3 are granted to both role_b and role_c
// but we only want to actually read them once
grantRolesTo(roleManager, ROLE_C, ROLE_B_1, ROLE_B_2, ROLE_B_3);
fetchRolesAndCheckReadCount(roleManager, ROLE_A);
}
private void fetchRolesAndCheckReadCount(IRoleManager roleManager, RoleResource primaryRole)
{
long before = getRolesReadCount();
Set<Role> granted = roleManager.getRoleDetails(primaryRole);
long after = getRolesReadCount();
assertEquals(granted.size(), after - before);
}
@Test
public void confirmFastRoleSetup()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
CassandraRoleManager crm = new CassandraRoleManager();
assertTrue("Expected the role manager to have existing roles before CassandraRoleManager setup", CassandraRoleManager.hasExistingRoles());
}
@Test
public void warmCacheLoadsAllEntries()
{
IRoleManager roleManager = new AuthTestUtils.LocalCassandraRoleManager();
roleManager.setup();
for (RoleResource r : ALL_ROLES)
roleManager.createRole(AuthenticatedUser.ANONYMOUS_USER, r, new RoleOptions());
// Multi level role hierarchy
grantRolesTo(roleManager, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
grantRolesTo(roleManager, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
// Use CassandraRoleManager to get entries for pre-warming a cache, then verify those entries
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
Set<Role> roleBRoles = cacheEntries.get(ROLE_B);
assertRoleSet(roleBRoles, ROLE_B, ROLE_B_1, ROLE_B_2, ROLE_B_3);
Set<Role> roleCRoles = cacheEntries.get(ROLE_C);
assertRoleSet(roleCRoles, ROLE_C, ROLE_C_1, ROLE_C_2, ROLE_C_3);
for (RoleResource r : ALL_ROLES)
{
// We already verified ROLE_B and ROLE_C
if (r.equals(ROLE_B) || r.equals(ROLE_C))
continue;
// Check the cache entries for the roles without any further grants
assertRoleSet(cacheEntries.get(r), r);
}
}
@Test
public void warmCacheWithEmptyTable()
{
CassandraRoleManager crm = new CassandraRoleManager();
crm.setup();
Map<RoleResource, Set<Role>> cacheEntries = crm.bulkLoader().get();
assertTrue(cacheEntries.isEmpty());
}
private void assertRoleSet(Set<Role> actual, RoleResource...expected)
{
assertEquals(expected.length, actual.size());
for (RoleResource expectedRole : expected)
assertTrue(actual.stream().anyMatch(role -> role.resource.equals(expectedRole)));
}
}
| apache-2.0 |
vishnuzimbra/zimbra | test/fixtures/cookbooks/aws_test/recipes/iam_user.rb | 313 | aws_iam_user 'test-kitchen-user' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :create
end
aws_iam_user 'test-kitchen-user' do
aws_access_key node['aws_test']['key_id']
aws_secret_access_key node['aws_test']['access_key']
action :delete
end
| apache-2.0 |
hankduan/angular | modules/playground/e2e_test/web_workers/kitchen_sink/kitchen_sink_spec.ts | 1788 | import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util';
import {Promise} from 'angular2/src/core/facade/async';
describe('WebWorkers Kitchen Sink', function() {
afterEach(() => {
verifyNoBrowserErrors();
browser.ignoreSynchronization = false;
});
var selector = "hello-app .greeting";
var URL = "playground/src/web_workers/kitchen_sink/index.html";
it('should greet', () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(selector)), 15000);
expect(element.all(by.css(selector)).first().getText()).toEqual("hello world!");
});
it('should change greeting', () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(selector)), 15000);
element(by.css("hello-app .changeButton")).click();
var elem = element(by.css(selector));
browser.wait(protractor.until.elementTextIs(elem, "howdy world!"), 5000);
expect(elem.getText()).toEqual("howdy world!");
});
it("should display correct key names", () => {
// This test can't wait for Angular 2 as Testability is not available when using WebWorker
browser.ignoreSynchronization = true;
browser.get(URL);
browser.wait(protractor.until.elementLocated(by.css(".sample-area")), 15000);
var area = element.all(by.css(".sample-area")).first();
expect(area.getText()).toEqual('(none)');
area.sendKeys('u');
browser.wait(protractor.until.elementTextIs(area, "U"), 5000);
expect(area.getText()).toEqual("U");
});
});
| apache-2.0 |
tsugiproject/tsugi | vendor/google/apiclient-services/src/Google/Service/CloudKMS/KeyOperationAttestation.php | 1447 | <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudKMS_KeyOperationAttestation extends Google_Model
{
protected $certChainsType = 'Google_Service_CloudKMS_CertificateChains';
protected $certChainsDataType = '';
public $content;
public $format;
/**
* @param Google_Service_CloudKMS_CertificateChains
*/
public function setCertChains(Google_Service_CloudKMS_CertificateChains $certChains)
{
$this->certChains = $certChains;
}
/**
* @return Google_Service_CloudKMS_CertificateChains
*/
public function getCertChains()
{
return $this->certChains;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setFormat($format)
{
$this->format = $format;
}
public function getFormat()
{
return $this->format;
}
}
| apache-2.0 |
swarmsandbox/wildfly-swarm | fractions/javaee/datasources/src/main/java/org/wildfly/swarm/datasources/runtime/drivers/Hive2DriverInfo.java | 1490 | /**
* Copyright 2015-2017 Red Hat, Inc, and individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.swarm.datasources.runtime.drivers;
import org.wildfly.swarm.config.datasources.DataSource;
import org.wildfly.swarm.datasources.runtime.DriverInfo;
/**
* Auto-detection for Apache Hive
*
* @author Kylin Soong
*/
public class Hive2DriverInfo extends DriverInfo {
public static final String DEFAULT_CONNETION_URL = "jdbc:hive2://localhost:10000/default";
public static final String DEFAULT_USER_NAME = "sa";
public static final String DEFAULT_PASSWORD = "sa";
protected Hive2DriverInfo() {
super("hive2", "org.apache.hive.jdbc", "org.apache.hive.jdbc.HiveDriver");
}
@Override
protected void configureDefaultDS(DataSource datasource) {
datasource.connectionUrl(DEFAULT_CONNETION_URL);
datasource.userName(DEFAULT_USER_NAME);
datasource.password(DEFAULT_PASSWORD);
}
}
| apache-2.0 |
uaraven/nano | sample/webservice/eBayDemoApp/src/com/ebay/trading/api/EBayMotorsProBestOfferEnabledDefinitionType.java | 509 | // Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;
import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
/**
*
* Indicates whether Contact Seller is enabled for Classified Ads.
* Added for EbayMotors Pro users.
*
*/
public class EBayMotorsProBestOfferEnabledDefinitionType implements Serializable {
private static final long serialVersionUID = -1L;
@AnyElement
@Order(value=0)
public List<Object> any;
} | apache-2.0 |
vongalpha/origin | pkg/user/registry/useridentitymapping/rest.go | 10722 | package useridentitymapping
import (
"fmt"
kapi "k8s.io/kubernetes/pkg/api"
kerrs "k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/rest"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/fielderrors"
"k8s.io/kubernetes/pkg/util/sets"
"github.com/openshift/origin/pkg/user/api"
"github.com/openshift/origin/pkg/user/registry/identity"
"github.com/openshift/origin/pkg/user/registry/user"
)
// REST implements the RESTStorage interface in terms of an image registry and
// image repository registry. It only supports the Create method and is used
// to simplify adding a new Image and tag to an ImageRepository.
type REST struct {
userRegistry user.Registry
identityRegistry identity.Registry
}
// NewREST returns a new REST.
func NewREST(userRegistry user.Registry, identityRegistry identity.Registry) *REST {
return &REST{userRegistry: userRegistry, identityRegistry: identityRegistry}
}
// New returns a new UserIdentityMapping for use with Create.
func (r *REST) New() runtime.Object {
return &api.UserIdentityMapping{}
}
// Get returns the mapping for the named identity
func (s *REST) Get(ctx kapi.Context, name string) (runtime.Object, error) {
_, _, _, _, mapping, err := s.getRelatedObjects(ctx, name)
return mapping, err
}
// Create associates a user and identity if they both exist, and the identity is not already mapped to a user
func (s *REST) Create(ctx kapi.Context, obj runtime.Object) (runtime.Object, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForCreate(mapping)
createdMapping, _, err := s.createOrUpdate(ctx, obj, true)
return createdMapping, err
}
// Update associates an identity with a user.
// Both the identity and user must already exist.
// If the identity is associated with another user already, it is disassociated.
func (s *REST) Update(ctx kapi.Context, obj runtime.Object) (runtime.Object, bool, error) {
mapping, ok := obj.(*api.UserIdentityMapping)
if !ok {
return nil, false, kerrs.NewBadRequest("invalid type")
}
Strategy.PrepareForUpdate(mapping, nil)
return s.createOrUpdate(ctx, mapping, false)
}
func (s *REST) createOrUpdate(ctx kapi.Context, obj runtime.Object, forceCreate bool) (runtime.Object, bool, error) {
mapping := obj.(*api.UserIdentityMapping)
identity, identityErr, oldUser, oldUserErr, oldMapping, oldMappingErr := s.getRelatedObjects(ctx, mapping.Name)
// Ensure we didn't get any errors other than NotFound errors
if !(oldMappingErr == nil || kerrs.IsNotFound(oldMappingErr)) {
return nil, false, oldMappingErr
}
if !(identityErr == nil || kerrs.IsNotFound(identityErr)) {
return nil, false, identityErr
}
if !(oldUserErr == nil || kerrs.IsNotFound(oldUserErr)) {
return nil, false, oldUserErr
}
// If we expect to be creating, fail if the mapping already existed
if forceCreate && oldMappingErr == nil {
return nil, false, kerrs.NewAlreadyExists("UserIdentityMapping", oldMapping.Name)
}
// Allow update to create if missing
creating := forceCreate || kerrs.IsNotFound(oldMappingErr)
if creating {
// Pre-create checks with no access to oldMapping
if err := rest.BeforeCreate(Strategy, ctx, mapping); err != nil {
return nil, false, err
}
// Ensure resource version is not specified
if len(mapping.ResourceVersion) > 0 {
return nil, false, kerrs.NewNotFound("UserIdentityMapping", mapping.Name)
}
} else {
// Pre-update checks with access to oldMapping
if err := rest.BeforeUpdate(Strategy, ctx, mapping, oldMapping); err != nil {
return nil, false, err
}
// Ensure resource versions match
if len(mapping.ResourceVersion) > 0 && mapping.ResourceVersion != oldMapping.ResourceVersion {
return nil, false, kerrs.NewConflict("UserIdentityMapping", mapping.Name, fmt.Errorf("the resource was updated to %s", oldMapping.ResourceVersion))
}
// If we're "updating" to the user we're already pointing to, we're already done
if mapping.User.Name == oldMapping.User.Name {
return oldMapping, false, nil
}
}
// Validate identity
if kerrs.IsNotFound(identityErr) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("identity.name", mapping.Identity.Name, "referenced identity does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
// Get new user
newUser, err := s.userRegistry.GetUser(ctx, mapping.User.Name)
if kerrs.IsNotFound(err) {
errs := fielderrors.ValidationErrorList([]error{
fielderrors.NewFieldInvalid("user.name", mapping.User.Name, "referenced user does not exist"),
})
return nil, false, kerrs.NewInvalid("UserIdentityMapping", mapping.Name, errs)
}
if err != nil {
return nil, false, err
}
// Update the new user to point at the identity. If this fails, Update is re-entrant
if addIdentityToUser(identity, newUser) {
if _, err := s.userRegistry.UpdateUser(ctx, newUser); err != nil {
return nil, false, err
}
}
// Update the identity to point at the new user. If this fails. Update is re-entrant
if setIdentityUser(identity, newUser) {
if updatedIdentity, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
return nil, false, err
} else {
identity = updatedIdentity
}
}
// At this point, the mapping for the identity has been updated to the new user
// Everything past this point is cleanup
// Update the old user to no longer point at the identity.
// If this fails, log the error, but continue, because Update is no longer re-entrant
if oldUser != nil && removeIdentityFromUser(identity, oldUser) {
if _, err := s.userRegistry.UpdateUser(ctx, oldUser); err != nil {
util.HandleError(fmt.Errorf("error removing identity reference %s from user %s: %v", identity.Name, oldUser.Name, err))
}
}
updatedMapping, err := mappingFor(newUser, identity)
return updatedMapping, creating, err
}
// Delete deletes the user association for the named identity
func (s *REST) Delete(ctx kapi.Context, name string) (runtime.Object, error) {
identity, _, user, _, _, mappingErr := s.getRelatedObjects(ctx, name)
if mappingErr != nil {
return nil, mappingErr
}
// Disassociate the identity with the user first
// If this fails, Delete is re-entrant
if removeIdentityFromUser(identity, user) {
if _, err := s.userRegistry.UpdateUser(ctx, user); err != nil {
return nil, err
}
}
// Remove the user association from the identity last.
// If this fails, log the error, but continue, because Delete is no longer re-entrant
// At this point, the mapping for the identity no longer exists
if unsetIdentityUser(identity) {
if _, err := s.identityRegistry.UpdateIdentity(ctx, identity); err != nil {
util.HandleError(fmt.Errorf("error removing user reference %s from identity %s: %v", user.Name, identity.Name, err))
}
}
return &kapi.Status{Status: kapi.StatusSuccess}, nil
}
// getRelatedObjects returns the identity, user, and mapping for the named identity
// a nil mappingErr means all objects were retrieved without errors, and correctly reference each other
func (s *REST) getRelatedObjects(ctx kapi.Context, name string) (
identity *api.Identity, identityErr error,
user *api.User, userErr error,
mapping *api.UserIdentityMapping, mappingErr error,
) {
// Initialize errors to NotFound
identityErr = kerrs.NewNotFound("Identity", name)
userErr = kerrs.NewNotFound("User", "")
mappingErr = kerrs.NewNotFound("UserIdentityMapping", name)
// Get identity
identity, identityErr = s.identityRegistry.GetIdentity(ctx, name)
if identityErr != nil {
return
}
if !hasUserMapping(identity) {
return
}
// Get user
user, userErr = s.userRegistry.GetUser(ctx, identity.User.Name)
if userErr != nil {
return
}
// Ensure relational integrity
if !identityReferencesUser(identity, user) {
return
}
if !userReferencesIdentity(user, identity) {
return
}
mapping, mappingErr = mappingFor(user, identity)
return
}
// hasUserMapping returns true if the given identity references a user
func hasUserMapping(identity *api.Identity) bool {
return len(identity.User.Name) > 0
}
// identityReferencesUser returns true if the identity's user name and uid match the given user
func identityReferencesUser(identity *api.Identity, user *api.User) bool {
return identity.User.Name == user.Name && identity.User.UID == user.UID
}
// userReferencesIdentity returns true if the user's identity list contains the given identity
func userReferencesIdentity(user *api.User, identity *api.Identity) bool {
return sets.NewString(user.Identities...).Has(identity.Name)
}
// addIdentityToUser adds the given identity to the user's list of identities
// returns true if the user's identity list was modified
func addIdentityToUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if identities.Has(identity.Name) {
return false
}
identities.Insert(identity.Name)
user.Identities = identities.List()
return true
}
// removeIdentityFromUser removes the given identity from the user's list of identities
// returns true if the user's identity list was modified
func removeIdentityFromUser(identity *api.Identity, user *api.User) bool {
identities := sets.NewString(user.Identities...)
if !identities.Has(identity.Name) {
return false
}
identities.Delete(identity.Name)
user.Identities = identities.List()
return true
}
// setIdentityUser sets the identity to reference the given user
// returns true if the identity's user reference was modified
func setIdentityUser(identity *api.Identity, user *api.User) bool {
if identityReferencesUser(identity, user) {
return false
}
identity.User = kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
}
return true
}
// unsetIdentityUser clears the identity's user reference
// returns true if the identity's user reference was modified
func unsetIdentityUser(identity *api.Identity) bool {
if !hasUserMapping(identity) {
return false
}
identity.User = kapi.ObjectReference{}
return true
}
// mappingFor returns a UserIdentityMapping for the given user and identity
// The name and resource version of the identity mapping match the identity
func mappingFor(user *api.User, identity *api.Identity) (*api.UserIdentityMapping, error) {
return &api.UserIdentityMapping{
ObjectMeta: kapi.ObjectMeta{
Name: identity.Name,
ResourceVersion: identity.ResourceVersion,
UID: identity.UID,
},
Identity: kapi.ObjectReference{
Name: identity.Name,
UID: identity.UID,
},
User: kapi.ObjectReference{
Name: user.Name,
UID: user.UID,
},
}, nil
}
| apache-2.0 |
dulems/azure-powershell | src/ResourceManager/TrafficManager/Commands.TrafficManager2/Endpoint/RemoveAzureTrafficManagerEndpointConfig.cs | 2353 | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System.Management.Automation;
using Microsoft.Azure.Commands.TrafficManager.Models;
using Microsoft.Azure.Commands.TrafficManager.Utilities;
using ProjectResources = Microsoft.Azure.Commands.TrafficManager.Properties.Resources;
namespace Microsoft.Azure.Commands.TrafficManager
{
[Cmdlet(VerbsCommon.Remove, "AzureRmTrafficManagerEndpointConfig"), OutputType(typeof(TrafficManagerProfile))]
public class RemoveAzureTrafficManagerEndpointConfig : TrafficManagerBaseCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "The name of the endpoint.")]
[ValidateNotNullOrEmpty]
public string EndpointName { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The profile.")]
[ValidateNotNullOrEmpty]
public TrafficManagerProfile TrafficManagerProfile { get; set; }
public override void ExecuteCmdlet()
{
if (this.TrafficManagerProfile.Endpoints == null)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
int endpointsRemoved = this.TrafficManagerProfile.Endpoints.RemoveAll(endpoint => string.Equals(this.EndpointName, endpoint.Name));
if (endpointsRemoved == 0)
{
throw new PSArgumentException(string.Format(ProjectResources.Error_EndpointNotFound, this.EndpointName));
}
this.WriteVerbose(ProjectResources.Success);
this.WriteObject(this.TrafficManagerProfile);
}
}
}
| apache-2.0 |
jppelteret/homebrew-cask | Casks/hunt-x.rb | 307 | cask 'hunt-x' do
version :latest
sha256 :no_check
url 'http://huntx.mobilefirst.in/Apps/Hunt%20X.zip'
name 'Hunt X'
homepage 'http://huntx.mobilefirst.in/'
license :unknown # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder
app 'Hunt X.app'
end
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-func-dstr-var-obj-ptrn-prop-ary.js | 1967 | // This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/obj-ptrn-prop-ary.case
// - src/dstr-binding-for-await/default/for-await-of-async-func-var.template
/*---
description: Object binding pattern with "nested" array binding pattern not using initializer (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( var ForBinding of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult,
varBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
1. Assert: lhs is a ForBinding.
2. Let status be the result of performing BindingInitialization
for lhs passing nextValue and undefined as the arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
[...]
3. If Initializer is present and v is undefined, then
[...]
4. Return the result of performing BindingInitialization for BindingPattern
passing v and environment as arguments.
---*/
var iterCount = 0;
async function fn() {
for await (var { w: [x, y, z] = [4, 5, 6] } of [{ w: [7, undefined, ] }]) {
assert.sameValue(x, 7);
assert.sameValue(y, undefined);
assert.sameValue(z, undefined);
assert.throws(ReferenceError, function() {
w;
});
iterCount += 1;
}
}
fn()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| bsd-2-clause |
tonyseek/homebrew-cask | Casks/evernote.rb | 268 | class Evernote < Cask
url 'https://www.evernote.com/about/download/get.php?file=EvernoteMac'
appcast 'http://update.evernote.com/public/ENMac/EvernoteMacUpdate.xml'
homepage 'https://evernote.com/'
version 'latest'
sha256 :no_check
link 'Evernote.app'
end
| bsd-2-clause |
mmicko/bx | tests/handle_test.cpp | 2557 | /*
* Copyright 2010-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
#include "test.h"
#include <bx/handlealloc.h>
#include <bx/hash.h>
TEST_CASE("HandleListT", "")
{
bx::HandleListT<32> list;
list.pushBack(16);
REQUIRE(list.getFront() == 16);
REQUIRE(list.getBack() == 16);
list.pushFront(7);
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 16);
uint16_t expected0[] = { 15, 31, 7, 16, 17, 11, 13 };
list.pushBack(17);
list.pushBack(11);
list.pushBack(13);
list.pushFront(31);
list.pushFront(15);
uint16_t count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
REQUIRE(count == BX_COUNTOF(expected0) );
list.remove(17);
list.remove(31);
list.remove(16);
list.pushBack(16);
uint16_t expected1[] = { 15, 7, 11, 13, 16 };
count = 0;
for (uint16_t it = list.getFront(); it != UINT16_MAX; it = list.getNext(it), ++count)
{
REQUIRE(it == expected1[count]);
}
REQUIRE(count == BX_COUNTOF(expected1) );
list.popBack();
list.popFront();
list.popBack();
list.popBack();
REQUIRE(list.getFront() == 7);
REQUIRE(list.getBack() == 7);
list.popBack();
REQUIRE(list.getFront() == UINT16_MAX);
REQUIRE(list.getBack() == UINT16_MAX);
}
TEST_CASE("HandleAllocLruT", "")
{
bx::HandleAllocLruT<16> lru;
uint16_t handle[4] =
{
lru.alloc(),
lru.alloc(),
lru.alloc(),
lru.alloc(),
};
lru.touch(handle[1]);
uint16_t expected0[] = { handle[1], handle[3], handle[2], handle[0] };
uint16_t count = 0;
for (uint16_t it = lru.getFront(); it != UINT16_MAX; it = lru.getNext(it), ++count)
{
REQUIRE(it == expected0[count]);
}
}
TEST_CASE("HandleHashTable", "")
{
typedef bx::HandleHashMapT<512> HashMap;
HashMap hm;
REQUIRE(512 == hm.getMaxCapacity() );
bx::StringView sv0("test0");
bool ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(!ok);
REQUIRE(1 == hm.getNumElements() );
bx::StringView sv1("test1");
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv1), 0);
REQUIRE(ok);
REQUIRE(2 == hm.getNumElements() );
hm.removeByHandle(0);
REQUIRE(0 == hm.getNumElements() );
ok = hm.insert(bx::hash<bx::HashMurmur2A>(sv0), 0);
REQUIRE(ok);
hm.removeByKey(bx::hash<bx::HashMurmur2A>(sv0) );
REQUIRE(0 == hm.getNumElements() );
for (uint32_t ii = 0, num = hm.getMaxCapacity(); ii < num; ++ii)
{
ok = hm.insert(ii, uint16_t(ii) );
REQUIRE(ok);
}
}
| bsd-2-clause |
adamliter/homebrew-core | Formula/libwebsockets.rb | 1637 | class Libwebsockets < Formula
desc "C websockets server library"
homepage "https://libwebsockets.org"
url "https://github.com/warmcat/libwebsockets/archive/v3.1.0.tar.gz"
sha256 "db948be74c78fc13f1f1a55e76707d7baae3a1c8f62b625f639e8f2736298324"
head "https://github.com/warmcat/libwebsockets.git"
bottle do
sha256 "c3dee13c27c98c87853ec9d1cbd3db27473c3fee1b0870260dc6c47294dd95e4" => :mojave
sha256 "fce83552c866222ad1386145cdd9745b82efc0c0a97b89b9069b98928241e893" => :high_sierra
sha256 "a57218f16bde1f484648fd7893d99d3dafc5c0ade4902c7ce442019b9782dc66" => :sierra
end
depends_on "cmake" => :build
depends_on "libevent"
depends_on "libuv"
depends_on "openssl"
def install
system "cmake", ".", *std_cmake_args,
"-DLWS_IPV6=ON",
"-DLWS_WITH_HTTP2=ON",
"-DLWS_WITH_LIBEVENT=ON",
"-DLWS_WITH_LIBUV=ON",
"-DLWS_WITH_PLUGINS=ON",
"-DLWS_WITHOUT_TESTAPPS=ON",
"-DLWS_UNIX_SOCK=ON"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <openssl/ssl.h>
#include <libwebsockets.h>
int main()
{
struct lws_context_creation_info info;
memset(&info, 0, sizeof(info));
struct lws_context *context;
context = lws_create_context(&info);
lws_context_destroy(context);
return 0;
}
EOS
system ENV.cc, "test.c", "-I#{Formula["openssl"].opt_prefix}/include", "-L#{lib}", "-lwebsockets", "-o", "test"
system "./test"
end
end
| bsd-2-clause |
endlessm/chromium-browser | third_party/grpc/src/src/compiler/python_generator.h | 1853 | /*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
#define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
#include <utility>
#include <vector>
#include "src/compiler/config.h"
#include "src/compiler/schema_interface.h"
namespace grpc_python_generator {
// Data pertaining to configuration of the generator with respect to anything
// that may be used internally at Google.
struct GeneratorConfiguration {
GeneratorConfiguration();
grpc::string grpc_package_root;
// TODO(https://github.com/grpc/grpc/issues/8622): Drop this.
grpc::string beta_package_root;
// TODO(https://github.com/google/protobuf/issues/888): Drop this.
grpc::string import_prefix;
std::vector<grpc::string> prefixes_to_filter;
};
class PythonGrpcGenerator : public grpc::protobuf::compiler::CodeGenerator {
public:
PythonGrpcGenerator(const GeneratorConfiguration& config);
~PythonGrpcGenerator();
bool Generate(const grpc::protobuf::FileDescriptor* file,
const grpc::string& parameter,
grpc::protobuf::compiler::GeneratorContext* context,
grpc::string* error) const;
private:
GeneratorConfiguration config_;
};
} // namespace grpc_python_generator
#endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H
| bsd-3-clause |
ethz-asl/Schweizer-Messer | sm_python/include/sm/python/Id.hpp | 2754 | #ifndef SM_PYTHON_ID_HPP
#define SM_PYTHON_ID_HPP
#include <numpy_eigen/boost_python_headers.hpp>
#include <boost/python/to_python_converter.hpp>
#include <Python.h>
#include <boost/cstdint.hpp>
namespace sm { namespace python {
// to use: sm::python::Id_python_converter<FrameId>::register_converter();
// adapted from http://misspent.wordpress.com/2009/09/27/how-to-write-boost-python-converters/
template<typename ID_T>
struct Id_python_converter
{
typedef ID_T id_t;
// The "Convert from C to Python" API
static PyObject * convert(id_t const & id){
PyObject * i = PyInt_FromLong(id.getId());
// It seems that the call to "incref(.)" caused a memory leak!
// I will check this in hoping it doesn't cause any instability.
return i;//boost::python::incref(i);
}
// The "Convert from Python to C" API
// Two functions: convertible() and construct()
static void * convertible(PyObject* obj_ptr)
{
if (!(PyInt_Check(obj_ptr) || PyLong_Check(obj_ptr)))
return 0;
return obj_ptr;
}
static void construct(
PyObject* obj_ptr,
boost::python::converter::rvalue_from_python_stage1_data* data)
{
// Get the value.
boost::uint64_t value;
if ( PyInt_Check(obj_ptr) ) {
value = PyInt_AsUnsignedLongLongMask(obj_ptr);
} else {
value = PyLong_AsUnsignedLongLong(obj_ptr);
}
void* storage = ((boost::python::converter::rvalue_from_python_storage<id_t>*)
data)->storage.bytes;
new (storage) id_t(value);
// Stash the memory chunk pointer for later use by boost.python
data->convertible = storage;
}
// The registration function.
static void register_converter()
{
// This code checks if the type has already been registered.
// http://stackoverflow.com/questions/9888289/checking-whether-a-converter-has-already-been-registered
boost::python::type_info info = boost::python::type_id<id_t>();
const boost::python::converter::registration* reg = boost::python::converter::registry::query(info);
if (reg == NULL || reg->m_to_python == NULL) {
// This is the code to register the type.
boost::python::to_python_converter<id_t,Id_python_converter>();
boost::python::converter::registry::push_back(
&convertible,
&construct,
boost::python::type_id<id_t>());
}
}
};
}}
#endif /* SM_PYTHON_ID_HPP */
| bsd-3-clause |
chromium/chromium | ui/message_center/views/message_popup_collection_unittest.cc | 38889 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/message_center/views/message_popup_collection.h"
#include "base/containers/cxx20_erase.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "ui/display/display.h"
#include "ui/events/base_event_utils.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/message_center_constants.h"
#include "ui/message_center/views/desktop_message_popup_collection.h"
#include "ui/message_center/views/message_popup_view.h"
#include "ui/views/test/views_test_base.h"
using message_center::MessageCenter;
using message_center::Notification;
namespace message_center {
namespace {
class MockMessagePopupView;
class MockMessagePopupCollection : public DesktopMessagePopupCollection {
public:
explicit MockMessagePopupCollection(gfx::NativeWindow context)
: DesktopMessagePopupCollection(), context_(context) {}
MockMessagePopupCollection(const MockMessagePopupCollection&) = delete;
MockMessagePopupCollection& operator=(const MockMessagePopupCollection&) =
delete;
~MockMessagePopupCollection() override = default;
void SetAnimationValue(double current) {
animation()->SetCurrentValue(current);
if (current == 1.0)
animation()->End();
else
AnimationProgressed(animation());
}
void RemovePopup(MockMessagePopupView* popup) {
base::Erase(popups_, popup);
}
bool IsAnimating() { return animation()->is_animating(); }
void set_is_primary_display(bool is_primary_display) {
is_primary_display_ = is_primary_display;
}
void set_is_fullscreen(bool is_fullscreen) { is_fullscreen_ = is_fullscreen; }
void set_new_popup_height(int new_popup_height) {
new_popup_height_ = new_popup_height;
}
std::vector<MockMessagePopupView*>& popups() { return popups_; }
bool popup_timer_started() const { return popup_timer_started_; }
protected:
MessagePopupView* CreatePopup(const Notification& notification) override;
void ConfigureWidgetInitParamsForContainer(
views::Widget* widget,
views::Widget::InitParams* init_params) override {
// Provides an aura window context for widget creation.
init_params->context = context_;
}
void RestartPopupTimers() override {
MessagePopupCollection::RestartPopupTimers();
popup_timer_started_ = true;
}
void PausePopupTimers() override {
MessagePopupCollection::PausePopupTimers();
popup_timer_started_ = false;
}
bool IsPrimaryDisplayForNotification() const override {
return is_primary_display_;
}
bool BlockForMixedFullscreen(
const Notification& notification) const override {
return is_fullscreen_;
}
private:
gfx::NativeWindow context_;
std::vector<MockMessagePopupView*> popups_;
bool popup_timer_started_ = false;
bool is_primary_display_ = true;
bool is_fullscreen_ = false;
int new_popup_height_ = 84;
};
class MockMessagePopupView : public MessagePopupView {
public:
MockMessagePopupView(const std::string& id,
int init_height,
MockMessagePopupCollection* popup_collection)
: MessagePopupView(popup_collection),
popup_collection_(popup_collection),
id_(id),
title_(base::UTF16ToUTF8(
MessageCenter::Get()->FindVisibleNotificationById(id)->title())) {
auto* view = new views::View;
view->SetPreferredSize(gfx::Size(kNotificationWidth, init_height));
AddChildView(view);
}
~MockMessagePopupView() override = default;
void Close() override {
popup_collection_->RemovePopup(this);
MessagePopupView::Close();
}
void UpdateContents(const Notification& notification) override {
if (height_after_update_.has_value())
SetPreferredHeight(height_after_update_.value());
popup_collection_->NotifyPopupResized();
updated_ = true;
title_ = base::UTF16ToUTF8(notification.title());
}
void AutoCollapse() override {
if (expandable_)
children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, 42));
}
void SetPreferredHeight(int height) {
children().front()->SetPreferredSize(gfx::Size(kNotificationWidth, height));
}
void SetHovered(bool is_hovered) {
if (is_hovered) {
ui::MouseEvent enter_event(ui::ET_MOUSE_ENTERED, gfx::Point(),
gfx::Point(), ui::EventTimeForNow(), 0, 0);
OnMouseEntered(enter_event);
} else {
ui::MouseEvent exit_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
OnMouseExited(exit_event);
}
}
void SimulateFocused() { OnDidChangeFocus(nullptr, children().front()); }
void Activate() {
SetCanActivate(true);
GetWidget()->Activate();
}
const std::string& id() const { return id_; }
bool updated() const { return updated_; }
const std::string& title() const { return title_; }
void set_expandable(bool expandable) { expandable_ = expandable; }
void set_height_after_update(absl::optional<int> height_after_update) {
height_after_update_ = height_after_update;
}
private:
const raw_ptr<MockMessagePopupCollection> popup_collection_;
std::string id_;
bool updated_ = false;
bool expandable_ = false;
std::string title_;
absl::optional<int> height_after_update_;
};
MessagePopupView* MockMessagePopupCollection::CreatePopup(
const Notification& notification) {
auto* popup =
new MockMessagePopupView(notification.id(), new_popup_height_, this);
popups_.push_back(popup);
return popup;
}
} // namespace
class MessagePopupCollectionTest : public views::ViewsTestBase,
public MessageCenterObserver {
public:
MessagePopupCollectionTest() = default;
MessagePopupCollectionTest(const MessagePopupCollectionTest&) = delete;
MessagePopupCollectionTest& operator=(const MessagePopupCollectionTest&) =
delete;
~MessagePopupCollectionTest() override = default;
// views::ViewTestBase:
void SetUp() override {
views::ViewsTestBase::SetUp();
MessageCenter::Initialize();
MessageCenter::Get()->DisableTimersForTest();
MessageCenter::Get()->AddObserver(this);
popup_collection_ =
std::make_unique<MockMessagePopupCollection>(GetContext());
// This size fits test machines resolution and also can keep a few popups
// w/o ill effects of hitting the screen overflow. This allows us to assume
// and verify normal layout of the toast stack.
SetDisplayInfo(gfx::Rect(0, 0, 1920, 1070), // taskbar at the bottom.
gfx::Rect(0, 0, 1920, 1080));
}
void TearDown() override {
MessageCenter::Get()->RemoveAllNotifications(
false /* by_user */, MessageCenter::RemoveType::ALL);
AnimateUntilIdle();
popup_collection_.reset();
MessageCenter::Get()->RemoveObserver(this);
MessageCenter::Shutdown();
views::ViewsTestBase::TearDown();
}
// MessageCenterObserver:
void OnNotificationDisplayed(const std::string& notification_id,
const DisplaySource source) override {
last_displayed_id_ = notification_id;
}
protected:
std::unique_ptr<Notification> CreateNotification(const std::string& id) {
return CreateNotification(id, "test title");
}
std::unique_ptr<Notification> CreateNotification(const std::string& id,
const std::string& title) {
return std::make_unique<Notification>(
NOTIFICATION_TYPE_BASE_FORMAT, id, base::UTF8ToUTF16(title),
u"test message", gfx::Image(), std::u16string() /* display_source */,
GURL(), NotifierId(), RichNotificationData(),
new NotificationDelegate());
}
std::string AddNotification() {
std::string id = base::NumberToString(id_++);
MessageCenter::Get()->AddNotification(CreateNotification(id));
return id;
}
void Update() { popup_collection_->Update(); }
void SetAnimationValue(double current) {
popup_collection_->SetAnimationValue(current);
}
bool IsAnimating() const { return popup_collection_->IsAnimating(); }
void AnimateUntilIdle() {
while (popup_collection_->IsAnimating()) {
popup_collection_->SetAnimationValue(1.0);
}
}
void AnimateToMiddle() {
EXPECT_TRUE(popup_collection_->IsAnimating());
popup_collection_->SetAnimationValue(0.5);
}
void AnimateToEnd() {
EXPECT_TRUE(popup_collection_->IsAnimating());
popup_collection_->SetAnimationValue(1.0);
}
MockMessagePopupView* GetPopup(const std::string& id) {
for (auto* popup : popup_collection_->popups()) {
if (popup->id() == id)
return popup;
}
return nullptr;
}
MockMessagePopupView* GetPopupAt(size_t index) {
return popup_collection_->popups()[index];
}
size_t GetPopupCounts() const { return popup_collection_->popups().size(); }
void SetDisplayInfo(const gfx::Rect& work_area,
const gfx::Rect& display_bounds) {
display::Display dummy_display;
dummy_display.set_bounds(display_bounds);
dummy_display.set_work_area(work_area);
work_area_ = work_area;
popup_collection_->RecomputeAlignment(dummy_display);
}
bool IsPopupTimerStarted() const {
return popup_collection_->popup_timer_started();
}
MockMessagePopupCollection* popup_collection() const {
return popup_collection_.get();
}
const gfx::Rect& work_area() const { return work_area_; }
const std::string& last_displayed_id() const { return last_displayed_id_; }
private:
int id_ = 0;
std::unique_ptr<MockMessagePopupCollection> popup_collection_;
gfx::Rect work_area_;
std::string last_displayed_id_;
};
TEST_F(MessagePopupCollectionTest, Nothing) {
EXPECT_FALSE(IsAnimating());
Update();
// If no popups are available, nothing changes.
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, FadeInFadeOutNotification) {
// Add a notification.
std::string id = AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
// The popup will fade in from right.
const int before_x = GetPopup(id)->GetBoundsInScreen().x();
EXPECT_EQ(0.0f, GetPopup(id)->GetOpacity());
AnimateToMiddle();
EXPECT_GT(before_x, GetPopup(id)->GetBoundsInScreen().x());
EXPECT_LT(0.0f, GetPopup(id)->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(id)->GetOpacity());
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(work_area().Contains(GetPopup(id)->GetBoundsInScreen()));
EXPECT_EQ(id, last_displayed_id());
// The popup will fade out because of timeout.
MessageCenter::Get()->MarkSinglePopupAsShown(id, false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(id)->GetOpacity());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_FALSE(GetPopup(id));
}
TEST_F(MessagePopupCollectionTest, FadeInMultipleNotifications) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
for (size_t i = 0; i < ids.size(); ++i) {
EXPECT_EQ(ids[i], last_displayed_id());
EXPECT_EQ(i + 1, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopupAt(i)->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopupAt(i)->GetOpacity());
EXPECT_TRUE(work_area().Contains(GetPopupAt(i)->GetBoundsInScreen()));
}
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
for (size_t i = 0; i < ids.size(); ++i)
EXPECT_EQ(ids[i], GetPopupAt(i)->id());
for (size_t i = 0; i < ids.size() - 1; ++i) {
EXPECT_GT(GetPopupAt(i)->GetBoundsInScreen().x(),
GetPopupAt(i + 1)->GetBoundsInScreen().bottom());
}
}
TEST_F(MessagePopupCollectionTest, FadeInMultipleNotificationsInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
for (size_t i = 0; i < ids.size(); ++i) {
EXPECT_EQ(ids[i], last_displayed_id());
EXPECT_EQ(i + 1, GetPopupCounts());
const int before_x = GetPopupAt(i)->GetBoundsInScreen().x();
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopupAt(i)->GetOpacity());
EXPECT_GT(before_x, GetPopupAt(i)->GetBoundsInScreen().x());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopupAt(i)->GetOpacity());
EXPECT_TRUE(work_area().Contains(GetPopupAt(i)->GetBoundsInScreen()));
if (i + 1 < ids.size()) {
const int before_y = GetPopupAt(i)->GetBoundsInScreen().y();
AnimateToMiddle();
EXPECT_GT(before_y, GetPopupAt(i)->GetBoundsInScreen().y());
AnimateToEnd();
}
}
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
for (size_t i = 0; i < ids.size(); ++i)
EXPECT_EQ(ids[i], GetPopupAt(i)->id());
for (size_t i = 0; i < ids.size() - 1; ++i) {
EXPECT_GT(GetPopupAt(i + 1)->GetBoundsInScreen().x(),
GetPopupAt(i)->GetBoundsInScreen().bottom());
}
}
TEST_F(MessagePopupCollectionTest, UpdateContents) {
std::string id = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id)->updated());
auto updated_notification = CreateNotification(id);
updated_notification->set_message(u"updated");
MessageCenter::Get()->UpdateNotification(id, std::move(updated_notification));
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id)->updated());
}
TEST_F(MessagePopupCollectionTest, UpdateContentsCausesPopupClose) {
std::string id = AddNotification();
AnimateToEnd();
RunPendingMessages();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id)->updated());
GetPopup(id)->set_height_after_update(2048);
auto updated_notification = CreateNotification(id);
updated_notification->set_message(u"updated");
MessageCenter::Get()->UpdateNotification(id, std::move(updated_notification));
RunPendingMessages();
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MessageCenterVisibility) {
// It only applies to a platform with MessageCenterView i.e. Chrome OS.
MessageCenter::Get()->SetHasMessageCenterView(true);
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
AddNotification();
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_EQ(3u, GetPopupCounts());
EXPECT_EQ(3u, MessageCenter::Get()->GetPopupNotifications().size());
// The notification should be hidden when MessageCenterView is visible.
MessageCenter::Get()->SetVisibility(Visibility::VISIBILITY_MESSAGE_CENTER);
// It should not animate in order to show ARC++ notifications properly.
EXPECT_FALSE(IsAnimating());
MessageCenter::Get()->SetVisibility(Visibility::VISIBILITY_TRANSIENT);
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
EXPECT_EQ(0u, MessageCenter::Get()->GetPopupNotifications().size());
}
TEST_F(MessagePopupCollectionTest, ShowCustomOnPrimaryDisplay) {
// TODO(yoshiki): Support custom popup notification on multiple display
// (crbug.com/715370).
popup_collection()->set_is_primary_display(true);
auto custom = CreateNotification("id");
custom->set_type(NOTIFICATION_TYPE_CUSTOM);
MessageCenter::Get()->AddNotification(std::move(custom));
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, NotShowCustomOnSubDisplay) {
// Disables popup of custom notification on non-primary displays, since
// currently custom notification supports only on one display at the same
// time.
// TODO(yoshiki): Support custom popup notification on multiple display
// (crbug.com/715370).
popup_collection()->set_is_primary_display(false);
auto custom = CreateNotification("id");
custom->set_type(NOTIFICATION_TYPE_CUSTOM);
MessageCenter::Get()->AddNotification(std::move(custom));
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MixedFullscreenShow) {
popup_collection()->set_is_fullscreen(false);
AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, MixedFullscreenBlock) {
popup_collection()->set_is_fullscreen(true);
AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(0u, GetPopupCounts());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveDown) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(ids.front())->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(ids[0])->GetOpacity());
EXPECT_EQ(ids[0], GetPopup(ids[0])->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(ids[1])->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(ids[1])->GetBoundsInScreen();
AnimateToMiddle();
gfx::Rect moving = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_GT(moving.bottom(), before.bottom());
EXPECT_GT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(0.f, GetPopup(ids.back())->GetOpacity());
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopup(ids.back())->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(ids.back())->GetOpacity());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveDownInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
std::string dismissed_id = ids[kMaxVisiblePopupNotifications - 1];
std::string new_bottom_id = ids[kMaxVisiblePopupNotifications - 2];
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(dismissed_id)->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(dismissed_id, false);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(dismissed_id)->GetOpacity());
EXPECT_EQ(dismissed_id, GetPopup(dismissed_id)->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(new_bottom_id)->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(new_bottom_id)->GetBoundsInScreen();
AnimateToMiddle();
gfx::Rect moving = GetPopup(new_bottom_id)->GetBoundsInScreen();
EXPECT_GT(moving.bottom(), before.bottom());
EXPECT_GT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(new_bottom_id)->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications - 1, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, NotificationsMoveUpForInverse) {
popup_collection()->set_inverse();
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_FALSE(IsAnimating());
gfx::Rect dismissed = GetPopup(ids.front())->GetBoundsInScreen();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
EXPECT_TRUE(IsAnimating());
// FADE_OUT
AnimateToMiddle();
EXPECT_GT(1.0f, GetPopup(ids[0])->GetOpacity());
EXPECT_EQ(ids[0], GetPopup(ids[0])->id());
AnimateToEnd();
EXPECT_EQ(ids[1], GetPopup(ids[1])->id());
EXPECT_TRUE(IsAnimating());
gfx::Rect before = GetPopup(ids[1])->GetBoundsInScreen();
// MOVE_UP_FOR_INVERSE
AnimateToMiddle();
gfx::Rect moving = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_LT(moving.bottom(), before.bottom());
EXPECT_LT(dismissed.bottom(), moving.bottom());
AnimateToEnd();
gfx::Rect after = GetPopup(ids[1])->GetBoundsInScreen();
EXPECT_EQ(dismissed, after);
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(0.f, GetPopup(ids.back())->GetOpacity());
// FADE_IN
AnimateToMiddle();
EXPECT_LT(0.0f, GetPopup(ids.back())->GetOpacity());
AnimateToEnd();
EXPECT_EQ(1.0f, GetPopup(ids.back())->GetOpacity());
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, PopupResized) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
std::vector<gfx::Rect> previous_bounds;
for (const auto& id : ids)
previous_bounds.push_back(GetPopup(id)->GetBoundsInScreen());
const int changed_height = 256;
GetPopup(ids[1])->SetPreferredHeight(changed_height);
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
EXPECT_EQ(previous_bounds[0], GetPopup(ids[0])->GetBoundsInScreen());
EXPECT_EQ(previous_bounds[1].bottom(),
GetPopup(ids[1])->GetBoundsInScreen().bottom());
EXPECT_GT(previous_bounds[1].y(), GetPopup(ids[1])->GetBoundsInScreen().y());
EXPECT_GT(previous_bounds[2].bottom(),
GetPopup(ids[2])->GetBoundsInScreen().bottom());
EXPECT_GT(previous_bounds[2].y(), GetPopup(ids[2])->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(previous_bounds[0], GetPopup(ids[0])->GetBoundsInScreen());
EXPECT_EQ(changed_height, GetPopup(ids[1])->GetBoundsInScreen().height());
}
TEST_F(MessagePopupCollectionTest, ExpandLatest) {
std::string id = AddNotification();
AnimateToEnd();
GetPopup(id)->set_expandable(true);
const int top_y = GetPopup(id)->GetBoundsInScreen().y();
AddNotification();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(1u, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(top_y, GetPopup(id)->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_LT(top_y, GetPopup(id)->GetBoundsInScreen().y());
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, ExpandLatestWithMoveDown) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications + 1; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
GetPopup(ids[1])->set_expandable(true);
const int top_y = GetPopup(ids[1])->GetBoundsInScreen().y();
MessageCenter::Get()->MarkSinglePopupAsShown(ids.front(), false);
AnimateToEnd();
EXPECT_TRUE(IsAnimating());
EXPECT_EQ(kMaxVisiblePopupNotifications - 1, GetPopupCounts());
AnimateToMiddle();
EXPECT_LT(top_y, GetPopup(ids[2])->GetBoundsInScreen().y());
AnimateToEnd();
EXPECT_EQ(kMaxVisiblePopupNotifications, GetPopupCounts());
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
TEST_F(MessagePopupCollectionTest, HoverClose) {
std::string id0 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(256);
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(84);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
GetPopup(id0)->SetHovered(true);
EXPECT_FALSE(IsPopupTimerStarted());
const int first_popup_top = GetPopup(id0)->GetBoundsInScreen().y();
MessageCenter::Get()->RemoveNotification(id0, true);
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_TRUE(IsAnimating());
AnimateToMiddle();
GetPopup(id1)->SetHovered(true);
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
EXPECT_FALSE(IsPopupTimerStarted());
GetPopup(id1)->SetHovered(false);
EXPECT_TRUE(IsAnimating());
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
EXPECT_GT(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
}
// Popup timers should be paused if a notification has focus.
// Once the focus is lost or the notification is resumed, popup timers
// should restart.
TEST_F(MessagePopupCollectionTest, FocusedClose) {
std::string id0 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(256);
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(84);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
GetPopup(id0)->Activate();
// Activating a popup should not pause timers.
EXPECT_TRUE(IsPopupTimerStarted());
// If the popup gets keyboard focus the timers should pause.
GetPopup(id0)->SimulateFocused();
EXPECT_FALSE(IsPopupTimerStarted());
const int first_popup_top = GetPopup(id0)->GetBoundsInScreen().y();
MessageCenter::Get()->RemoveNotification(id0, true);
AnimateToEnd();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_GT(first_popup_top, GetPopup(id1)->GetBoundsInScreen().y());
EXPECT_TRUE(IsPopupTimerStarted());
}
TEST_F(MessagePopupCollectionTest, SlideOutClose) {
std::vector<std::string> ids;
for (size_t i = 0; i < kMaxVisiblePopupNotifications; ++i)
ids.push_back(AddNotification());
AnimateUntilIdle();
GetPopup(ids[1])->SetOpacity(0);
MessageCenter::Get()->RemoveNotification(ids[1], true);
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(IsPopupTimerStarted());
}
TEST_F(MessagePopupCollectionTest, TooTallNotification) {
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
popup_collection()->set_new_popup_height(400);
std::string id2 = AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id1, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, TooTallNotificationInverse) {
popup_collection()->set_inverse();
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
// 2 popus shall fit. 3 popups shall not.
popup_collection()->set_new_popup_height(200);
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
std::string id2 = AddNotification();
EXPECT_FALSE(IsAnimating());
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DisplaySizeChanged) {
std::string id0 = AddNotification();
AnimateToEnd();
std::string id1 = AddNotification();
AnimateToEnd();
popup_collection()->set_new_popup_height(400);
std::string id2 = AddNotification();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
popup_collection()->ResetBounds();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(work_area().Contains(GetPopup(id0)->GetBoundsInScreen()));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(work_area().Contains(GetPopup(id1)->GetBoundsInScreen()));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
MessageCenter::Get()->MarkSinglePopupAsShown(id1, false);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, PopupResizedAndOverflown) {
SetDisplayInfo(gfx::Rect(0, 0, 800, 470), // taskbar at the bottom.
gfx::Rect(0, 0, 800, 480));
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
const int changed_height = 300;
GetPopup(id1)->SetPreferredHeight(changed_height);
AnimateUntilIdle();
RunPendingMessages();
EXPECT_TRUE(GetPopup(id0));
EXPECT_TRUE(work_area().Contains(GetPopup(id0)->GetBoundsInScreen()));
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(work_area().Contains(GetPopup(id1)->GetBoundsInScreen()));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->MarkSinglePopupAsShown(id0, false);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DismissOnClick) {
MessageCenter::Get()->SetHasMessageCenterView(true);
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotification(id2);
AnimateUntilIdle();
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotificationButton(id1, 0);
AnimateUntilIdle();
EXPECT_EQ(0u, GetPopupCounts());
EXPECT_FALSE(GetPopup(id1));
EXPECT_FALSE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, NotDismissedOnClick) {
MessageCenter::Get()->SetHasMessageCenterView(false);
std::string id1 = AddNotification();
std::string id2 = AddNotification();
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotification(id2);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
MessageCenter::Get()->ClickOnNotificationButton(id1, 0);
AnimateUntilIdle();
EXPECT_EQ(2u, GetPopupCounts());
EXPECT_TRUE(GetPopup(id1));
EXPECT_TRUE(GetPopup(id2));
}
TEST_F(MessagePopupCollectionTest, DefaultPositioning) {
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
std::string id3 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
gfx::Rect r2 = GetPopup(id2)->GetBoundsInScreen();
// The 4th toast is not shown yet.
EXPECT_FALSE(GetPopup(id3));
// 3 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r1.width(), r2.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_EQ(r1.height(), r2.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_GT(r1.y(), r2.y());
EXPECT_EQ(r0.x(), r1.x());
EXPECT_EQ(r1.x(), r2.x());
}
TEST_F(MessagePopupCollectionTest, DefaultPositioningInverse) {
popup_collection()->set_inverse();
std::string id0 = AddNotification();
std::string id1 = AddNotification();
std::string id2 = AddNotification();
std::string id3 = AddNotification();
AnimateUntilIdle();
// This part is inverted.
gfx::Rect r0 = GetPopup(id2)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
gfx::Rect r2 = GetPopup(id0)->GetBoundsInScreen();
// The 4th toast is not shown yet.
EXPECT_FALSE(GetPopup(id3));
// 3 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r1.width(), r2.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_EQ(r1.height(), r2.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_GT(r1.y(), r2.y());
EXPECT_EQ(r0.x(), r1.x());
EXPECT_EQ(r1.x(), r2.x());
}
TEST_F(MessagePopupCollectionTest, DefaultPositioningWithRightTaskbar) {
// If taskbar is on the right we show the toasts bottom to top as usual.
// Simulate a taskbar at the right.
SetDisplayInfo(gfx::Rect(0, 0, 590, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithTopTaskbar) {
// Simulate a taskbar at the top.
SetDisplayInfo(gfx::Rect(0, 10, 600, 390), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithLeftAndTopTaskbar) {
// If there "seems" to be a taskbar on left and top (like in Unity), it is
// assumed that the actual taskbar is the top one.
// Simulate a taskbar at the top and left.
SetDisplayInfo(gfx::Rect(10, 10, 590, 390), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, TopDownPositioningWithBottomAndTopTaskbar) {
// If there "seems" to be a taskbar on bottom and top (like in Gnome), it is
// assumed that the actual taskbar is the top one.
// Simulate a taskbar at the top and bottom.
SetDisplayInfo(gfx::Rect(0, 10, 580, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
// 2 toasts are shown, equal size, vertical stack.
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_LT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
}
TEST_F(MessagePopupCollectionTest, LeftPositioningWithLeftTaskbar) {
// Simulate a taskbar at the left.
SetDisplayInfo(gfx::Rect(10, 0, 590, 400), // Work-area.
gfx::Rect(0, 0, 600, 400)); // Display-bounds.
std::string id0 = AddNotification();
std::string id1 = AddNotification();
AnimateUntilIdle();
gfx::Rect r0 = GetPopup(id0)->GetBoundsInScreen();
gfx::Rect r1 = GetPopup(id1)->GetBoundsInScreen();
EXPECT_EQ(r0.width(), r1.width());
EXPECT_EQ(r0.height(), r1.height());
EXPECT_GT(r0.y(), r1.y());
EXPECT_EQ(r0.x(), r1.x());
// Ensure that toasts are on the left.
EXPECT_LT(r1.x(), work_area().CenterPoint().x());
EXPECT_TRUE(work_area().Contains(r0));
EXPECT_TRUE(work_area().Contains(r1));
}
TEST_F(MessagePopupCollectionTest, PopupWidgetClosedOutsideDuringFadeOut) {
std::string id = AddNotification();
AnimateUntilIdle();
MessageCenter::Get()->MarkSinglePopupAsShown(id, false);
AnimateToMiddle();
// On Windows it might be possible that the widget is closed outside
// MessagePopupCollection? https://crbug.com/871199
GetPopup(id)->GetWidget()->CloseNow();
AnimateToEnd();
EXPECT_FALSE(IsAnimating());
}
// Notification removing may occur while the animation triggered by the previous
// operation is running. As result, notification is removed from the message
// center but its popup is still kept. At this moment, a new notification with
// the same notification id may be added to the message center. This can happen
// on Chrome OS when an external display is connected with the Chromebook device
// (see https://crbug.com/921402). This test case emulates the procedure of
// the external display connection that is mentioned in the link above. Verifies
// that under this circumstance the notification popup is updated.
TEST_F(MessagePopupCollectionTest, RemoveNotificationWhileAnimating) {
const std::string notification_id("test_id");
const std::string old_notification_title("old_title");
const std::string new_notification_title("new_title");
// Create a notification and add it to message center.
auto old_notification =
CreateNotification(notification_id, old_notification_title);
MessageCenter::Get()->AddNotification(std::move(old_notification));
AnimateToMiddle();
// On real device, MessageCenter::RemoveNotification is called before the
// animation ends. As result, notification is removed while popup keeps still.
EXPECT_TRUE(IsAnimating());
MessageCenter::Get()->RemoveNotification(notification_id, false);
EXPECT_FALSE(MessageCenter::Get()->HasPopupNotifications());
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_EQ(old_notification_title, GetPopup(notification_id)->title());
// On real device, the new notification with the same notification id is
// created and added to message center before the animation ends.
auto new_notification =
CreateNotification(notification_id, new_notification_title);
EXPECT_TRUE(IsAnimating());
MessageCenter::Get()->AddNotification(std::move(new_notification));
AnimateUntilIdle();
// Verifies that the new notification popup is shown.
EXPECT_EQ(1u, GetPopupCounts());
EXPECT_EQ(new_notification_title, GetPopup(notification_id)->title());
}
} // namespace message_center
| bsd-3-clause |
balena/sandboxed | chrome/base/thread_local_posix.cc | 826 | // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/thread_local.h"
#include <pthread.h>
#include "base/logging.h"
namespace base {
// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
int error = pthread_key_create(&slot, NULL);
CHECK(error == 0);
}
// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
int error = pthread_key_delete(slot);
DCHECK(error == 0);
}
// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
return pthread_getspecific(slot);
}
// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
int error = pthread_setspecific(slot, value);
CHECK(error == 0);
}
} // namespace base
| bsd-3-clause |
mehulsbhatt/unbound | util/data/msgreply.h | 14843 | /*
* util/data/msgreply.h - store message and reply data.
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains a data structure to store a message and its reply.
*/
#ifndef UTIL_DATA_MSGREPLY_H
#define UTIL_DATA_MSGREPLY_H
#include "util/storage/lruhash.h"
#include "util/data/packed_rrset.h"
struct comm_reply;
struct alloc_cache;
struct iovec;
struct regional;
struct edns_data;
struct msg_parse;
struct rrset_parse;
/** calculate the prefetch TTL as 90% of original. Calculation
* without numerical overflow (uin32_t) */
#define PREFETCH_TTL_CALC(ttl) ((ttl) - (ttl)/10)
/**
* Structure to store query information that makes answers to queries
* different.
*/
struct query_info {
/**
* Salient data on the query: qname, in wireformat.
* can be allocated or a pointer to outside buffer.
* User has to keep track on the status of this.
*/
uint8_t* qname;
/** length of qname (including last 0 octet) */
size_t qname_len;
/** qtype, host byte order */
uint16_t qtype;
/** qclass, host byte order */
uint16_t qclass;
};
/**
* Information to reference an rrset
*/
struct rrset_ref {
/** the key with lock, and ptr to packed data. */
struct ub_packed_rrset_key* key;
/** id needed */
rrset_id_t id;
};
/**
* Structure to store DNS query and the reply packet.
* To use it, copy over the flags from reply and modify using flags from
* the query (RD,CD if not AA). prepend ID.
*
* Memory layout is:
* o struct
* o rrset_ref array
* o packed_rrset_key* array.
*
* Memory layout is sometimes not packed, when the message is synthesized,
* for easy of the generation. It is allocated packed when it is copied
* from the region allocation to the malloc allocation.
*/
struct reply_info {
/** the flags for the answer, host byte order. */
uint16_t flags;
/**
* This flag informs unbound the answer is authoritative and
* the AA flag should be preserved.
*/
uint8_t authoritative;
/**
* Number of RRs in the query section.
* If qdcount is not 0, then it is 1, and the data that appears
* in the reply is the same as the query_info.
* Host byte order.
*/
uint8_t qdcount;
/**
* TTL of the entire reply (for negative caching).
* only for use when there are 0 RRsets in this message.
* if there are RRsets, check those instead.
*/
uint32_t ttl;
/**
* TTL for prefetch. After it has expired, a prefetch is suitable.
* Smaller than the TTL, otherwise the prefetch would not happen.
*/
uint32_t prefetch_ttl;
/** 32 bit padding to pad struct member alignment to 64 bits. */
uint32_t padding;
/**
* The security status from DNSSEC validation of this message.
*/
enum sec_status security;
/**
* Number of RRsets in each section.
* The answer section. Add up the RRs in every RRset to calculate
* the number of RRs, and the count for the dns packet.
* The number of RRs in RRsets can change due to RRset updates.
*/
size_t an_numrrsets;
/** Count of authority section RRsets */
size_t ns_numrrsets;
/** Count of additional section RRsets */
size_t ar_numrrsets;
/** number of RRsets: an_numrrsets + ns_numrrsets + ar_numrrsets */
size_t rrset_count;
/**
* List of pointers (only) to the rrsets in the order in which
* they appear in the reply message.
* Number of elements is ancount+nscount+arcount RRsets.
* This is a pointer to that array.
* Use the accessor function for access.
*/
struct ub_packed_rrset_key** rrsets;
/**
* Packed array of ids (see counts) and pointers to packed_rrset_key.
* The number equals ancount+nscount+arcount RRsets.
* These are sorted in ascending pointer, the locking order. So
* this list can be locked (and id, ttl checked), to see if
* all the data is available and recent enough.
*
* This is defined as an array of size 1, so that the compiler
* associates the identifier with this position in the structure.
* Array bound overflow on this array then gives access to the further
* elements of the array, which are allocated after the main structure.
*
* It could be more pure to define as array of size 0, ref[0].
* But ref[1] may be less confusing for compilers.
* Use the accessor function for access.
*/
struct rrset_ref ref[1];
};
/**
* Structure to keep hash table entry for message replies.
*/
struct msgreply_entry {
/** the hash table key */
struct query_info key;
/** the hash table entry, data is struct reply_info* */
struct lruhash_entry entry;
};
/**
* Parse wire query into a queryinfo structure, return 0 on parse error.
* initialises the (prealloced) queryinfo structure as well.
* This query structure contains a pointer back info the buffer!
* This pointer avoids memory allocation. allocqname does memory allocation.
* @param m: the prealloced queryinfo structure to put query into.
* must be unused, or _clear()ed.
* @param query: the wireformat packet query. starts with ID.
* @return: 0 on format error.
*/
int query_info_parse(struct query_info* m, ldns_buffer* query);
/**
* Parse query reply.
* Fills in preallocated query_info structure (with ptr into buffer).
* Allocates reply_info and packed_rrsets. These are not yet added to any
* caches or anything, this is only parsing. Returns formerror on qdcount > 1.
* @param pkt: the packet buffer. Must be positioned after the query section.
* @param alloc: creates packed rrset key structures.
* @param rep: allocated reply_info is returned (only on no error).
* @param qinf: query_info is returned (only on no error).
* @param region: where to store temporary data (for parsing).
* @param edns: where to store edns information, does not need to be inited.
* @return: zero is OK, or DNS error code in case of error
* o FORMERR for parse errors.
* o SERVFAIL for memory allocation errors.
*/
int reply_info_parse(ldns_buffer* pkt, struct alloc_cache* alloc,
struct query_info* qinf, struct reply_info** rep,
struct regional* region, struct edns_data* edns);
/**
* Allocate and decompress parsed message and rrsets.
* @param pkt: for name decompression.
* @param msg: parsed message in scratch region.
* @param alloc: alloc cache for special rrset key structures.
* Not used if region!=NULL, it can be NULL in that case.
* @param qinf: where to store query info.
* qinf itself is allocated by the caller.
* @param rep: reply info is allocated and returned.
* @param region: if this parameter is NULL then malloc and the alloc is used.
* otherwise, everything is allocated in this region.
* In a region, no special rrset key structures are needed (not shared),
* and no rrset_ref array in the reply is built up.
* @return 0 if allocation failed.
*/
int parse_create_msg(ldns_buffer* pkt, struct msg_parse* msg,
struct alloc_cache* alloc, struct query_info* qinf,
struct reply_info** rep, struct regional* region);
/**
* Sorts the ref array.
* @param rep: reply info. rrsets must be filled in.
*/
void reply_info_sortref(struct reply_info* rep);
/**
* Set TTLs inside the replyinfo to absolute values.
* @param rep: reply info. rrsets must be filled in.
* Also refs must be filled in.
* @param timenow: the current time.
*/
void reply_info_set_ttls(struct reply_info* rep, uint32_t timenow);
/**
* Delete reply_info and packed_rrsets (while they are not yet added to the
* hashtables.). Returns rrsets to the alloc cache.
* @param rep: reply_info to delete.
* @param alloc: where to return rrset structures to.
*/
void reply_info_parsedelete(struct reply_info* rep, struct alloc_cache* alloc);
/**
* Compare two queryinfo structures, on query and type, class.
* It is _not_ sorted in canonical ordering.
* @param m1: struct query_info* , void* here to ease use as function pointer.
* @param m2: struct query_info* , void* here to ease use as function pointer.
* @return: 0 = same, -1 m1 is smaller, +1 m1 is larger.
*/
int query_info_compare(void* m1, void* m2);
/** clear out query info structure */
void query_info_clear(struct query_info* m);
/** calculate size of struct query_info + reply_info */
size_t msgreply_sizefunc(void* k, void* d);
/** delete msgreply_entry key structure */
void query_entry_delete(void *q, void* arg);
/** delete reply_info data structure */
void reply_info_delete(void* d, void* arg);
/** calculate hash value of query_info, lowercases the qname */
hashvalue_t query_info_hash(struct query_info *q);
/**
* Setup query info entry
* @param q: query info to copy. Emptied as if clear is called.
* @param r: reply to init data.
* @param h: hash value.
* @return: newly allocated message reply cache item.
*/
struct msgreply_entry* query_info_entrysetup(struct query_info* q,
struct reply_info* r, hashvalue_t h);
/**
* Copy reply_info and all rrsets in it and allocate.
* @param rep: what to copy, probably inside region, no ref[] array in it.
* @param alloc: how to allocate rrset keys.
* Not used if region!=NULL, it can be NULL in that case.
* @param region: if this parameter is NULL then malloc and the alloc is used.
* otherwise, everything is allocated in this region.
* In a region, no special rrset key structures are needed (not shared),
* and no rrset_ref array in the reply is built up.
* @return new reply info or NULL on memory error.
*/
struct reply_info* reply_info_copy(struct reply_info* rep,
struct alloc_cache* alloc, struct regional* region);
/**
* Copy a parsed rrset into given key, decompressing and allocating rdata.
* @param pkt: packet for decompression
* @param msg: the parser message (for flags for trust).
* @param pset: the parsed rrset to copy.
* @param region: if NULL - malloc, else data is allocated in this region.
* @param pk: a freshly obtained rrsetkey structure. No dname is set yet,
* will be set on return.
* Note that TTL will still be relative on return.
* @return false on alloc failure.
*/
int parse_copy_decompress_rrset(ldns_buffer* pkt, struct msg_parse* msg,
struct rrset_parse *pset, struct regional* region,
struct ub_packed_rrset_key* pk);
/**
* Find final cname target in reply, the one matching qinfo. Follows CNAMEs.
* @param qinfo: what to start with.
* @param rep: looks in answer section of this message.
* @return: pointer dname, or NULL if not found.
*/
uint8_t* reply_find_final_cname_target(struct query_info* qinfo,
struct reply_info* rep);
/**
* Check if cname chain in cached reply is still valid.
* @param rep: reply to check.
* @return: true if valid, false if invalid.
*/
int reply_check_cname_chain(struct reply_info* rep);
/**
* Check security status of all RRs in the message.
* @param rep: reply to check
* @return: true if all RRs are secure. False if not.
* True if there are zero RRs.
*/
int reply_all_rrsets_secure(struct reply_info* rep);
/**
* Find answer rrset in reply, the one matching qinfo. Follows CNAMEs, so the
* result may have a different owner name.
* @param qinfo: what to look for.
* @param rep: looks in answer section of this message.
* @return: pointer to rrset, or NULL if not found.
*/
struct ub_packed_rrset_key* reply_find_answer_rrset(struct query_info* qinfo,
struct reply_info* rep);
/**
* Find rrset in reply, inside the answer section. Does not follow CNAMEs.
* @param rep: looks in answer section of this message.
* @param name: what to look for.
* @param namelen: length of name.
* @param type: looks for (host order).
* @param dclass: looks for (host order).
* @return: pointer to rrset, or NULL if not found.
*/
struct ub_packed_rrset_key* reply_find_rrset_section_an(struct reply_info* rep,
uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass);
/**
* Find rrset in reply, inside the authority section. Does not follow CNAMEs.
* @param rep: looks in authority section of this message.
* @param name: what to look for.
* @param namelen: length of name.
* @param type: looks for (host order).
* @param dclass: looks for (host order).
* @return: pointer to rrset, or NULL if not found.
*/
struct ub_packed_rrset_key* reply_find_rrset_section_ns(struct reply_info* rep,
uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass);
/**
* Find rrset in reply, inside any section. Does not follow CNAMEs.
* @param rep: looks in answer,authority and additional section of this message.
* @param name: what to look for.
* @param namelen: length of name.
* @param type: looks for (host order).
* @param dclass: looks for (host order).
* @return: pointer to rrset, or NULL if not found.
*/
struct ub_packed_rrset_key* reply_find_rrset(struct reply_info* rep,
uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass);
/**
* Debug send the query info and reply info to the log in readable form.
* @param str: descriptive string printed with packet content.
* @param qinfo: query section.
* @param rep: rest of message.
*/
void log_dns_msg(const char* str, struct query_info* qinfo,
struct reply_info* rep);
/**
* Print string with neat domain name, type, class from query info.
* @param v: at what verbosity level to print this.
* @param str: string of message.
* @param qinf: query info structure with name, type and class.
*/
void log_query_info(enum verbosity_value v, const char* str,
struct query_info* qinf);
#endif /* UTIL_DATA_MSGREPLY_H */
| bsd-3-clause |
chromium/chromium | third_party/blink/renderer/core/paint/paint_invalidator.cc | 15422 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/paint/paint_invalidator.h"
#include "base/trace_event/trace_event.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/layout/layout_block_flow.h"
#include "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "third_party/blink/renderer/core/layout/layout_table.h"
#include "third_party/blink/renderer/core/layout/layout_table_section.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h"
#include "third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/core/mobile_metrics/mobile_friendliness_checker.h"
#include "third_party/blink/renderer/core/page/link_highlight.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/object_paint_properties.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/paint/pre_paint_tree_walk.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
namespace blink {
void PaintInvalidator::UpdatePaintingLayer(const LayoutObject& object,
PaintInvalidatorContext& context) {
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer()) {
context.painting_layer = To<LayoutBoxModelObject>(object).Layer();
} else if (object.IsColumnSpanAll() ||
object.IsFloatingWithNonContainingBlockParent()) {
// See |LayoutObject::PaintingLayer| for the special-cases of floating under
// inline and multicolumn.
// Post LayoutNG the |LayoutObject::IsFloatingWithNonContainingBlockParent|
// check can be removed as floats will be painted by the correct layer.
context.painting_layer = object.PaintingLayer();
}
auto* layout_block_flow = DynamicTo<LayoutBlockFlow>(object);
if (layout_block_flow && !object.IsLayoutNGBlockFlow() &&
layout_block_flow->ContainsFloats())
context.painting_layer->SetNeedsPaintPhaseFloat();
if (object.IsFloating() &&
(object.IsInLayoutNGInlineFormattingContext() ||
IsLayoutNGContainingBlock(object.ContainingBlock())))
context.painting_layer->SetNeedsPaintPhaseFloat();
if (!context.painting_layer->NeedsPaintPhaseDescendantOutlines() &&
((object != context.painting_layer->GetLayoutObject() &&
object.StyleRef().HasOutline()) ||
// If this is a block-in-inline, it may need to paint outline.
// See |StyleForContinuationOutline|.
(layout_block_flow && layout_block_flow->StyleForContinuationOutline())))
context.painting_layer->SetNeedsPaintPhaseDescendantOutlines();
}
void PaintInvalidator::UpdateFromTreeBuilderContext(
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
DCHECK_EQ(tree_builder_context.current.paint_offset,
context.fragment_data->PaintOffset());
// For performance, we ignore subpixel movement of composited layers for paint
// invalidation. This will result in imperfect pixel-snapped painting.
// See crbug.com/833083 for details.
if (!RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled() &&
tree_builder_context.current
.directly_composited_container_paint_offset_subpixel_delta ==
tree_builder_context.current.paint_offset -
tree_builder_context.old_paint_offset) {
context.old_paint_offset = tree_builder_context.current.paint_offset;
} else {
context.old_paint_offset = tree_builder_context.old_paint_offset;
}
context.transform_ = tree_builder_context.current.transform;
}
void PaintInvalidator::UpdateLayoutShiftTracking(
const LayoutObject& object,
const PaintPropertyTreeBuilderFragmentContext& tree_builder_context,
PaintInvalidatorContext& context) {
if (!object.ShouldCheckGeometryForPaintInvalidation())
return;
if (tree_builder_context.this_or_ancestor_opacity_is_zero ||
context.inside_opaque_layout_shift_root) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
auto& layout_shift_tracker = object.GetFrameView()->GetLayoutShiftTracker();
if (!layout_shift_tracker.NeedsToTrack(object)) {
object.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(true);
return;
}
PropertyTreeStateOrAlias property_tree_state(
*tree_builder_context.current.transform,
*tree_builder_context.current.clip, *tree_builder_context.current_effect);
// Adjust old_paint_offset so that LayoutShiftTracker will see the change of
// offset caused by change of paint offset translations and scroll offset
// below the layout shift root. For more details, see
// renderer/core/layout/layout-shift-tracker-old-paint-offset.md.
PhysicalOffset adjusted_old_paint_offset =
context.old_paint_offset -
tree_builder_context.current
.additional_offset_to_layout_shift_root_delta -
PhysicalOffset::FromVector2dFRound(
tree_builder_context.translation_2d_to_layout_shift_root_delta +
tree_builder_context.current
.scroll_offset_to_layout_shift_root_delta);
PhysicalOffset new_paint_offset = tree_builder_context.current.paint_offset;
if (object.IsText()) {
const auto& text = To<LayoutText>(object);
LogicalOffset new_starting_point;
LayoutUnit logical_height;
text.LogicalStartingPointAndHeight(new_starting_point, logical_height);
LogicalOffset old_starting_point = text.PreviousLogicalStartingPoint();
if (new_starting_point == old_starting_point)
return;
text.SetPreviousLogicalStartingPoint(new_starting_point);
if (old_starting_point == LayoutText::UninitializedLogicalStartingPoint())
return;
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return;
layout_shift_tracker.NotifyTextPrePaint(
text, property_tree_state, old_starting_point, new_starting_point,
adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset, logical_height);
return;
}
DCHECK(object.IsBox());
const auto& box = To<LayoutBox>(object);
PhysicalRect new_rect = box.PhysicalVisualOverflowRectAllowingUnset();
new_rect.Move(new_paint_offset);
PhysicalRect old_rect = box.PreviousPhysicalVisualOverflowRect();
old_rect.Move(adjusted_old_paint_offset);
// TODO(crbug.com/1178618): We may want to do better than this. For now, just
// don't report anything inside multicol containers.
const auto* block_flow = DynamicTo<LayoutBlockFlow>(&box);
if (block_flow && block_flow->IsFragmentationContextRoot() &&
block_flow->IsLayoutNGObject())
context.inside_opaque_layout_shift_root = true;
bool should_create_containing_block_scope =
// TODO(crbug.com/1178618): Support multiple-fragments when switching to
// LayoutNGFragmentTraversal.
context.fragment_data == &box.FirstFragment() && block_flow &&
block_flow->ChildrenInline() && block_flow->FirstChild();
if (should_create_containing_block_scope) {
// For layout shift tracking of contained LayoutTexts.
context.containing_block_scope_.emplace(
PhysicalSizeToBeNoop(box.PreviousSize()),
PhysicalSizeToBeNoop(box.Size()), old_rect, new_rect);
}
bool should_report_layout_shift = [&]() -> bool {
if (box.ShouldSkipNextLayoutShiftTracking()) {
box.GetMutableForPainting().SetShouldSkipNextLayoutShiftTracking(false);
return false;
}
// If the layout shift root has changed, LayoutShiftTracker can't use the
// current paint property tree to map the old rect.
if (tree_builder_context.current.layout_shift_root_changed)
return false;
if (new_rect.IsEmpty() || old_rect.IsEmpty())
return false;
// Track self-painting layers separately because their ancestors'
// PhysicalVisualOverflowRect may not cover them.
if (object.HasLayer() &&
To<LayoutBoxModelObject>(object).HasSelfPaintingLayer())
return true;
// Always track if the parent doesn't need to track (e.g. it has visibility:
// hidden), while this object needs (e.g. it has visibility: visible).
// This also includes non-anonymous child with an anonymous parent.
if (object.Parent()->ShouldSkipNextLayoutShiftTracking())
return true;
// Report if the parent is in a different transform space.
const auto* parent_context = context.ParentContext();
if (!parent_context || !parent_context->transform_ ||
parent_context->transform_ != tree_builder_context.current.transform)
return true;
// Report if this object has local movement (i.e. delta of paint offset is
// different from that of the parent).
return parent_context->fragment_data->PaintOffset() -
parent_context->old_paint_offset !=
new_paint_offset - context.old_paint_offset;
}();
if (should_report_layout_shift) {
layout_shift_tracker.NotifyBoxPrePaint(
box, property_tree_state, old_rect, new_rect, adjusted_old_paint_offset,
tree_builder_context.translation_2d_to_layout_shift_root_delta,
tree_builder_context.current.scroll_offset_to_layout_shift_root_delta,
tree_builder_context.current.pending_scroll_anchor_adjustment,
new_paint_offset);
}
}
bool PaintInvalidator::InvalidatePaint(
const LayoutObject& object,
const NGPrePaintInfo* pre_paint_info,
const PaintPropertyTreeBuilderContext* tree_builder_context,
PaintInvalidatorContext& context) {
TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"PaintInvalidator::InvalidatePaint()", "object",
object.DebugName().Ascii());
if (object.IsSVGHiddenContainer() || object.IsLayoutTableCol())
context.subtree_flags |= PaintInvalidatorContext::kSubtreeNoInvalidation;
if (context.subtree_flags & PaintInvalidatorContext::kSubtreeNoInvalidation)
return false;
object.GetMutableForPainting().EnsureIsReadyForPaintInvalidation();
UpdatePaintingLayer(object, context);
// Assert that the container state in the invalidation context is consistent
// with what the LayoutObject tree says. We cannot do this if we're fragment-
// traversing an "orphaned" object (an object that has a fragment inside a
// fragmentainer, even though not all its ancestor objects have it; this may
// happen to OOFs, and also to floats, if they are inside a non-atomic
// inline). In such cases we'll just have to live with the inconsitency, which
// means that we'll lose any paint effects from such "missing" ancestors.
DCHECK_EQ(context.painting_layer, object.PaintingLayer()) << object;
if (AXObjectCache* cache = object.GetDocument().ExistingAXObjectCache())
cache->InvalidateBoundingBox(&object);
if (!object.ShouldCheckForPaintInvalidation() && !context.NeedsSubtreeWalk())
return false;
if (object.SubtreeShouldDoFullPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeFullInvalidation |
PaintInvalidatorContext::kSubtreeFullInvalidationForStackedContents;
}
if (object.SubtreeShouldCheckForPaintInvalidation()) {
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (UNLIKELY(object.ContainsInlineWithOutlineAndContinuation()) &&
// Need this only if the subtree needs to check geometry change.
PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(object)) {
// Force subtree invalidation checking to ensure invalidation of focus rings
// when continuation's geometry changes.
context.subtree_flags |=
PaintInvalidatorContext::kSubtreeInvalidationChecking;
}
if (pre_paint_info) {
FragmentData& fragment_data = *pre_paint_info->fragment_data;
context.fragment_data = &fragment_data;
if (tree_builder_context) {
DCHECK_EQ(tree_builder_context->fragments.size(), 1u);
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[0];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context, context);
} else {
context.old_paint_offset = fragment_data.PaintOffset();
}
object.InvalidatePaint(context);
} else {
unsigned tree_builder_index = 0;
for (auto* fragment_data = &object.GetMutableForPainting().FirstFragment();
fragment_data;
fragment_data = fragment_data->NextFragment(), tree_builder_index++) {
context.fragment_data = fragment_data;
DCHECK(!tree_builder_context ||
tree_builder_index < tree_builder_context->fragments.size());
if (tree_builder_context) {
const auto& fragment_tree_builder_context =
tree_builder_context->fragments[tree_builder_index];
UpdateFromTreeBuilderContext(fragment_tree_builder_context, context);
UpdateLayoutShiftTracking(object, fragment_tree_builder_context,
context);
} else {
context.old_paint_offset = fragment_data->PaintOffset();
}
object.InvalidatePaint(context);
}
}
auto reason = static_cast<const DisplayItemClient&>(object)
.GetPaintInvalidationReason();
if (object.ShouldDelayFullPaintInvalidation() &&
(!IsFullPaintInvalidationReason(reason) ||
// Delay invalidation if the client has never been painted.
reason == PaintInvalidationReason::kJustCreated))
pending_delayed_paint_invalidations_.push_back(&object);
if (auto* local_frame = DynamicTo<LocalFrame>(object.GetFrame()->Top())) {
if (auto* mf_checker =
local_frame->View()->GetMobileFriendlinessChecker()) {
if (tree_builder_context &&
(!pre_paint_info || pre_paint_info->is_last_for_node))
mf_checker->NotifyInvalidatePaint(object);
}
}
return reason != PaintInvalidationReason::kNone;
}
void PaintInvalidator::ProcessPendingDelayedPaintInvalidations() {
for (const auto& target : pending_delayed_paint_invalidations_)
target->GetMutableForPainting().SetShouldDelayFullPaintInvalidation();
}
} // namespace blink
| bsd-3-clause |
windyuuy/opera | chromium/src/ash/test/test_session_state_delegate.h | 3514 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_TEST_TEST_SESSION_STATE_DELEGATE_H_
#define ASH_TEST_TEST_SESSION_STATE_DELEGATE_H_
#include "ash/session_state_delegate.h"
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "ui/gfx/image/image_skia.h"
namespace ash {
namespace test {
class TestSessionStateDelegate : public SessionStateDelegate {
public:
TestSessionStateDelegate();
virtual ~TestSessionStateDelegate();
void set_logged_in_users(int users) { logged_in_users_ = users; }
const std::string& get_activated_user() { return activated_user_; }
// SessionStateDelegate:
virtual int GetMaximumNumberOfLoggedInUsers() const OVERRIDE;
virtual int NumberOfLoggedInUsers() const OVERRIDE;
virtual bool IsActiveUserSessionStarted() const OVERRIDE;
virtual bool CanLockScreen() const OVERRIDE;
virtual bool IsScreenLocked() const OVERRIDE;
virtual void LockScreen() OVERRIDE;
virtual void UnlockScreen() OVERRIDE;
virtual const base::string16 GetUserDisplayName(
ash::MultiProfileIndex index) const OVERRIDE;
virtual const std::string GetUserEmail(
ash::MultiProfileIndex index) const OVERRIDE;
virtual const gfx::ImageSkia& GetUserImage(
ash::MultiProfileIndex index) const OVERRIDE;
virtual void GetLoggedInUsers(UserIdList* users) OVERRIDE;
virtual void SwitchActiveUser(const std::string& email) OVERRIDE;
virtual void AddSessionStateObserver(
ash::SessionStateObserver* observer) OVERRIDE;
virtual void RemoveSessionStateObserver(
ash::SessionStateObserver* observer) OVERRIDE;
// Updates the internal state that indicates whether a session is in progress
// and there is an active user. If |has_active_user| is |false|,
// |active_user_session_started_| is reset to |false| as well (see below for
// the difference between these two flags).
void SetHasActiveUser(bool has_active_user);
// Updates the internal state that indicates whether the session has been
// fully started for the active user. If |active_user_session_started| is
// |true|, |has_active_user_| is set to |true| as well (see below for the
// difference between these two flags).
void SetActiveUserSessionStarted(bool active_user_session_started);
// Updates the internal state that indicates whether the screen can be locked.
// Locking will only actually be allowed when this value is |true| and there
// is an active user.
void SetCanLockScreen(bool can_lock_screen);
private:
// Whether a session is in progress and there is an active user.
bool has_active_user_;
// When a user becomes active, the profile and browser UI are not immediately
// available. Only once this flag becomes |true| is the browser startup
// complete and both profile and UI are fully available.
bool active_user_session_started_;
// Whether the screen can be locked. Locking will only actually be allowed
// when this is |true| and there is an active user.
bool can_lock_screen_;
// Whether the screen is currently locked.
bool screen_locked_;
// The number of users logged in.
int logged_in_users_;
// The activated user.
std::string activated_user_;
// A test user image.
gfx::ImageSkia null_image_;
DISALLOW_COPY_AND_ASSIGN(TestSessionStateDelegate);
};
} // namespace test
} // namespace ash
#endif // ASH_TEST_TEST_SESSION_STATE_DELEGATE_H_
| bsd-3-clause |
js0701/chromium-crosswalk | components/html_viewer/layout_test_content_handler_impl.cc | 4105 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/html_viewer/layout_test_content_handler_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/macros.h"
#include "components/html_viewer/global_state.h"
#include "components/html_viewer/html_document_application_delegate.h"
#include "components/html_viewer/html_widget.h"
#include "components/html_viewer/layout_test_blink_settings_impl.h"
#include "components/html_viewer/web_test_delegate_impl.h"
#include "components/test_runner/web_frame_test_proxy.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebTestingSupport.h"
#include "third_party/WebKit/public/web/WebView.h"
namespace html_viewer {
class TestHTMLFrame : public HTMLFrame {
public:
explicit TestHTMLFrame(HTMLFrame::CreateParams* params)
: HTMLFrame(params), test_interfaces_(nullptr) {}
void set_test_interfaces(test_runner::WebTestInterfaces* test_interfaces) {
test_interfaces_ = test_interfaces;
}
protected:
~TestHTMLFrame() override {}
private:
// blink::WebFrameClient::
void didClearWindowObject(blink::WebLocalFrame* frame) override {
HTMLFrame::didClearWindowObject(frame);
blink::WebTestingSupport::injectInternalsObject(frame);
DCHECK(test_interfaces_);
test_interfaces_->BindTo(frame);
}
test_runner::WebTestInterfaces* test_interfaces_;
DISALLOW_COPY_AND_ASSIGN(TestHTMLFrame);
};
LayoutTestContentHandlerImpl::LayoutTestContentHandlerImpl(
GlobalState* global_state,
mojo::ApplicationImpl* app,
mojo::InterfaceRequest<mojo::ContentHandler> request,
test_runner::WebTestInterfaces* test_interfaces,
WebTestDelegateImpl* test_delegate)
: ContentHandlerImpl(global_state, app, std::move(request)),
test_interfaces_(test_interfaces),
test_delegate_(test_delegate),
web_widget_proxy_(nullptr),
app_refcount_(app->app_lifetime_helper()->CreateAppRefCount()) {}
LayoutTestContentHandlerImpl::~LayoutTestContentHandlerImpl() {
}
void LayoutTestContentHandlerImpl::StartApplication(
mojo::InterfaceRequest<mojo::Application> request,
mojo::URLResponsePtr response,
const mojo::Callback<void()>& destruct_callback) {
test_interfaces_->SetTestIsRunning(true);
test_interfaces_->ConfigureForTestWithURL(GURL(), false);
// HTMLDocumentApplicationDelegate deletes itself.
HTMLDocumentApplicationDelegate* delegate =
new HTMLDocumentApplicationDelegate(
std::move(request), std::move(response), global_state(),
app()->app_lifetime_helper()->CreateAppRefCount(), destruct_callback);
delegate->set_html_factory(this);
}
HTMLWidgetRootLocal* LayoutTestContentHandlerImpl::CreateHTMLWidgetRootLocal(
HTMLWidgetRootLocal::CreateParams* params) {
web_widget_proxy_ = new WebWidgetProxy(params);
return web_widget_proxy_;
}
HTMLFrame* LayoutTestContentHandlerImpl::CreateHTMLFrame(
HTMLFrame::CreateParams* params) {
params->manager->global_state()->set_blink_settings(
new LayoutTestBlinkSettingsImpl());
// The test harness isn't correctly set-up for iframes yet. So return a normal
// HTMLFrame for iframes.
if (params->parent || !params->window || params->window->id() != params->id)
return new HTMLFrame(params);
using ProxyType =
test_runner::WebFrameTestProxy<TestHTMLFrame, HTMLFrame::CreateParams*>;
ProxyType* proxy = new ProxyType(params);
proxy->set_test_interfaces(test_interfaces_);
web_widget_proxy_->SetInterfaces(test_interfaces_);
web_widget_proxy_->SetDelegate(test_delegate_);
proxy->set_base_proxy(web_widget_proxy_);
test_delegate_->set_test_proxy(web_widget_proxy_);
test_interfaces_->SetWebView(web_widget_proxy_->web_view(),
web_widget_proxy_);
web_widget_proxy_->set_widget(web_widget_proxy_->web_view());
test_interfaces_->BindTo(web_widget_proxy_->web_view()->mainFrame());
return proxy;
}
} // namespace html_viewer
| bsd-3-clause |
js0701/chromium-crosswalk | third_party/WebKit/Source/platform/graphics/GeneratedImage.cpp | 3311 | /*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/graphics/GeneratedImage.h"
#include "platform/geometry/FloatRect.h"
#include "platform/graphics/paint/SkPictureBuilder.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace blink {
void GeneratedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
Image::computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
intrinsicRatio = FloatSize();
}
void GeneratedImage::drawPattern(GraphicsContext& destContext, const FloatRect& srcRect, const FloatSize& scale,
const FloatPoint& phase, SkXfermode::Mode compositeOp, const FloatRect& destRect,
const FloatSize& repeatSpacing)
{
FloatRect tileRect = srcRect;
tileRect.expand(FloatSize(repeatSpacing));
SkPictureBuilder builder(tileRect, nullptr, &destContext);
builder.context().beginRecording(tileRect);
drawTile(builder.context(), srcRect);
RefPtr<const SkPicture> tilePicture = builder.endRecording();
AffineTransform patternTransform;
patternTransform.translate(phase.x(), phase.y());
patternTransform.scale(scale.width(), scale.height());
patternTransform.translate(tileRect.x(), tileRect.y());
RefPtr<Pattern> picturePattern = Pattern::createPicturePattern(tilePicture);
picturePattern->setPatternSpaceTransform(patternTransform);
SkPaint fillPaint = destContext.fillPaint();
picturePattern->applyToPaint(fillPaint);
fillPaint.setColor(SK_ColorBLACK);
fillPaint.setXfermodeMode(compositeOp);
destContext.drawRect(destRect, fillPaint);
}
PassRefPtr<SkImage> GeneratedImage::imageForCurrentFrame()
{
return nullptr;
}
} // namespace blink
| bsd-3-clause |
leighpauls/k2cro4 | base/task_runner_util.h | 2492 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_TASK_RUNNER_UTIL_H_
#define BASE_TASK_RUNNER_UTIL_H_
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback_internal.h"
#include "base/logging.h"
#include "base/task_runner.h"
namespace base {
namespace internal {
// Helper class for TaskRunner::PostTaskAndReplyWithResult.
template <typename ReturnType>
void ReturnAsParamAdapter(const Callback<ReturnType(void)>& func,
ReturnType* result) {
if (!func.is_null())
*result = func.Run();
}
// Helper class for TaskRunner::PostTaskAndReplyWithResult.
template <typename ReturnType>
Closure ReturnAsParam(const Callback<ReturnType(void)>& func,
ReturnType* result) {
DCHECK(result);
return Bind(&ReturnAsParamAdapter<ReturnType>, func, result);
}
// Helper class for TaskRunner::PostTaskAndReplyWithResult.
template <typename ReturnType>
void ReplyAdapter(const Callback<void(ReturnType)>& callback,
ReturnType* result) {
DCHECK(result);
if(!callback.is_null())
callback.Run(CallbackForward(*result));
}
// Helper class for TaskRunner::PostTaskAndReplyWithResult.
template <typename ReturnType, typename OwnedType>
Closure ReplyHelper(const Callback<void(ReturnType)>& callback,
OwnedType result) {
return Bind(&ReplyAdapter<ReturnType>, callback, result);
}
} // namespace internal
// When you have these methods
//
// R DoWorkAndReturn();
// void Callback(const R& result);
//
// and want to call them in a PostTaskAndReply kind of fashion where the
// result of DoWorkAndReturn is passed to the Callback, you can use
// PostTaskAndReplyWithResult as in this example:
//
// PostTaskAndReplyWithResult(
// target_thread_.message_loop_proxy(),
// FROM_HERE,
// Bind(&DoWorkAndReturn),
// Bind(&Callback));
template <typename ReturnType>
bool PostTaskAndReplyWithResult(
TaskRunner* task_runner,
const tracked_objects::Location& from_here,
const Callback<ReturnType(void)>& task,
const Callback<void(ReturnType)>& reply) {
ReturnType* result = new ReturnType;
return task_runner->PostTaskAndReply(
from_here,
internal::ReturnAsParam<ReturnType>(task, result),
internal::ReplyHelper(reply, Owned(result)));
}
} // namespace base
#endif // BASE_TASK_RUNNER_UTIL_H_
| bsd-3-clause |
danakj/chromium | third_party/WebKit/LayoutTests/media/track/track-webvtt-tc028-unsupported-markup.html | 1514 | <!DOCTYPE html>
<title>Tests that unsupported markup is properly ignored.</title>
<script src="track-helpers.js"></script>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script>
// TODO(srirama.m): Rewrite the test in a better way.
// See https://codereview.chromium.org/2030383002/ for details.
check_cues_from_track("captions-webvtt/tc028-unsupported-markup.vtt", function(track) {
var expected = [
{
innerHTML: "Bear is Coming!!!!!\nAnd what kind of a bear it is - just have look.",
text: "<h1>Bear is Coming!!!!!</h1>\n<p>And what kind of a bear it is - just have <a href=\"webpage.html\">look</a>.</p>"
},
{
innerHTML: "\n I said Bear is coming!!!!\n I said Bear is still coming!!!!\n",
text: "<ul>\n <li>I said Bear is coming!!!!</li>\n <li>I said Bear is still coming!!!!</li>\n</ul>"
},
{
innerHTML: "\n I said Bear is coming now!!!!\n \n \n",
text: "<ol>\n <li>I said Bear is coming now!!!!</li>\n <li><img src=\"bear.png\" alt=\"mighty bear\"></li>\n <li><video src=\"bear_ad.webm\" controls></video></li>\n</ol>"
}
];
var cues = track.cues;
assert_equals(cues.length, expected.length);
for (var i = 0; i < cues.length; i++) {
assert_equals(cues[i].getCueAsHTML().textContent, expected[i].innerHTML);
assert_equals(cues[i].text, expected[i].text);
}
});
</script> | bsd-3-clause |
chromium/chromium | third_party/blink/renderer/modules/csspaint/paint_rendering_context_2d.h | 5042 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_RENDERING_CONTEXT_2D_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_RENDERING_CONTEXT_2D_H_
#include <memory>
#include "third_party/blink/renderer/bindings/modules/v8/v8_paint_rendering_context_2d_settings.h"
#include "third_party/blink/renderer/modules/canvas/canvas2d/base_rendering_context_2d.h"
#include "third_party/blink/renderer/modules/csspaint/paint_worklet_global_scope.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_recorder.h"
namespace blink {
class CanvasImageSource;
class Color;
// In our internal implementation, there are different kinds of canvas such as
// recording canvas, GPU canvas. The CSS Paint API uses the recording canvas and
// this class is specifically designed for the recording canvas.
//
// The main difference between this class and other contexts is that
// PaintRenderingContext2D operates on CSS pixels rather than physical pixels.
class MODULES_EXPORT PaintRenderingContext2D : public ScriptWrappable,
public BaseRenderingContext2D {
DEFINE_WRAPPERTYPEINFO();
public:
PaintRenderingContext2D(const gfx::Size& container_size,
const PaintRenderingContext2DSettings*,
float zoom,
float device_scale_factor,
PaintWorkletGlobalScope* global_scope = nullptr);
PaintRenderingContext2D(const PaintRenderingContext2D&) = delete;
PaintRenderingContext2D& operator=(const PaintRenderingContext2D&) = delete;
void Trace(Visitor* visitor) const override {
visitor->Trace(context_settings_);
visitor->Trace(global_scope_);
ScriptWrappable::Trace(visitor);
BaseRenderingContext2D::Trace(visitor);
}
// PaintRenderingContext2D doesn't have any pixel readback so the origin
// is always clean, and unable to taint it.
bool OriginClean() const final { return true; }
void SetOriginTainted() final {}
bool WouldTaintOrigin(CanvasImageSource*) final { return false; }
int Width() const final;
int Height() const final;
bool ParseColorOrCurrentColor(Color&, const String& color_string) const final;
cc::PaintCanvas* GetOrCreatePaintCanvas() final { return GetPaintCanvas(); }
cc::PaintCanvas* GetPaintCanvas() const final;
cc::PaintCanvas* GetPaintCanvasForDraw(
const SkIRect&,
CanvasPerformanceMonitor::DrawType) final;
double shadowOffsetX() const final;
void setShadowOffsetX(double) final;
double shadowOffsetY() const final;
void setShadowOffsetY(double) final;
double shadowBlur() const final;
void setShadowBlur(double) final;
sk_sp<PaintFilter> StateGetFilter() final;
void SnapshotStateForFilter() final {}
void ValidateStateStackWithCanvas(const cc::PaintCanvas*) const final;
bool HasAlpha() const final { return context_settings_->alpha(); }
// PaintRenderingContext2D cannot lose it's context.
bool isContextLost() const final { return false; }
// PaintRenderingContext2D uses a recording canvas, so it should never
// allocate a pixel buffer and is not accelerated.
bool CanCreateCanvas2dResourceProvider() const final { return false; }
bool IsAccelerated() const final { return false; }
// CSS Paint doesn't have any notion of image orientation.
RespectImageOrientationEnum RespectImageOrientation() const final {
return kRespectImageOrientation;
}
DOMMatrix* getTransform() final;
void resetTransform() final;
void FlushCanvas() final {}
sk_sp<PaintRecord> GetRecord();
cc::PaintCanvas* GetDrawingPaintCanvas();
ExecutionContext* GetTopExecutionContext() const override {
return global_scope_.Get();
}
protected:
PredefinedColorSpace GetDefaultImageDataColorSpace() const final;
bool IsPaint2D() const override { return true; }
void WillOverwriteCanvas() override;
private:
void InitializePaintRecorder();
std::unique_ptr<PaintRecorder> paint_recorder_;
sk_sp<PaintRecord> previous_frame_;
gfx::Size container_size_;
Member<const PaintRenderingContext2DSettings> context_settings_;
bool did_record_draw_commands_in_paint_recorder_;
// The paint worklet canvas operates on CSS pixels, and that's different than
// the HTML canvas which operates on physical pixels. In other words, the
// paint worklet canvas needs to handle device scale factor and browser zoom,
// and this is designed for that purpose.
const float effective_zoom_;
WeakMember<PaintWorkletGlobalScope> global_scope_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_CSSPAINT_PAINT_RENDERING_CONTEXT_2D_H_
| bsd-3-clause |
espadrine/opera | chromium/src/chrome/browser/extensions/api/cookies/cookies_api.h | 7506 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Defines the Chrome Extensions Cookies API functions for accessing internet
// cookies, as specified in the extension API JSON.
#ifndef CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
#include <string>
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/extensions/api/profile_keyed_api_factory.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_function.h"
#include "chrome/browser/net/chrome_cookie_notification_details.h"
#include "chrome/common/extensions/api/cookies.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "googleurl/src/gurl.h"
#include "net/cookies/canonical_cookie.h"
namespace net {
class URLRequestContextGetter;
}
namespace extensions {
// Observes CookieMonster notifications and routes them as events to the
// extension system.
class CookiesEventRouter : public content::NotificationObserver {
public:
explicit CookiesEventRouter(Profile* profile);
virtual ~CookiesEventRouter();
private:
// content::NotificationObserver implementation.
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// Handler for the COOKIE_CHANGED event. The method takes the details of such
// an event and constructs a suitable JSON formatted extension event from it.
void CookieChanged(Profile* profile, ChromeCookieDetails* details);
// This method dispatches events to the extension message service.
void DispatchEvent(Profile* context,
const std::string& event_name,
scoped_ptr<base::ListValue> event_args,
GURL& cookie_domain);
// Used for tracking registrations to CookieMonster notifications.
content::NotificationRegistrar registrar_;
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(CookiesEventRouter);
};
// Serves as a base class for all cookies API functions, and defines some
// common functionality for parsing cookies API function arguments.
// Note that all of the functions in this file derive from
// AsyncExtensionFunction, and are not threadsafe, so they should not be
// concurrently accessed from multiple threads. They modify |result_| and other
// member variables directly.
// See chrome/browser/extensions/extension_function.h for more information.
class CookiesFunction : public AsyncExtensionFunction {
protected:
virtual ~CookiesFunction() {}
// Constructs a GURL from the given url string. Returns false and assigns the
// internal error_ value if the URL is invalid. If |check_host_permissions| is
// true, the URL is also checked against the extension's host permissions, and
// if there is no permission for the URL, this function returns false.
bool ParseUrl(const std::string& url_string, GURL* url,
bool check_host_permissions);
// Gets the store identified by |store_id| and returns it in |context|.
// If |store_id| contains an empty string, retrieves the current execution
// context's store. In this case, |store_id| is populated with the found
// store, and |context| can be NULL if the caller only wants |store_id|.
bool ParseStoreContext(std::string* store_id,
net::URLRequestContextGetter** context);
};
// Implements the cookies.get() extension function.
class CookiesGetFunction : public CookiesFunction {
public:
DECLARE_EXTENSION_FUNCTION("cookies.get", COOKIES_GET)
CookiesGetFunction();
protected:
virtual ~CookiesGetFunction();
// ExtensionFunction:
virtual bool RunImpl() OVERRIDE;
private:
void GetCookieOnIOThread();
void RespondOnUIThread();
void GetCookieCallback(const net::CookieList& cookie_list);
GURL url_;
scoped_refptr<net::URLRequestContextGetter> store_context_;
scoped_ptr<extensions::api::cookies::Get::Params> parsed_args_;
};
// Implements the cookies.getAll() extension function.
class CookiesGetAllFunction : public CookiesFunction {
public:
DECLARE_EXTENSION_FUNCTION("cookies.getAll", COOKIES_GETALL)
CookiesGetAllFunction();
protected:
virtual ~CookiesGetAllFunction();
// ExtensionFunction:
virtual bool RunImpl() OVERRIDE;
private:
void GetAllCookiesOnIOThread();
void RespondOnUIThread();
void GetAllCookiesCallback(const net::CookieList& cookie_list);
GURL url_;
scoped_refptr<net::URLRequestContextGetter> store_context_;
scoped_ptr<extensions::api::cookies::GetAll::Params> parsed_args_;
};
// Implements the cookies.set() extension function.
class CookiesSetFunction : public CookiesFunction {
public:
DECLARE_EXTENSION_FUNCTION("cookies.set", COOKIES_SET)
CookiesSetFunction();
protected:
virtual ~CookiesSetFunction();
virtual bool RunImpl() OVERRIDE;
private:
void SetCookieOnIOThread();
void RespondOnUIThread();
void PullCookie(bool set_cookie_);
void PullCookieCallback(const net::CookieList& cookie_list);
GURL url_;
bool success_;
scoped_refptr<net::URLRequestContextGetter> store_context_;
scoped_ptr<extensions::api::cookies::Set::Params> parsed_args_;
};
// Implements the cookies.remove() extension function.
class CookiesRemoveFunction : public CookiesFunction {
public:
DECLARE_EXTENSION_FUNCTION("cookies.remove", COOKIES_REMOVE)
CookiesRemoveFunction();
protected:
virtual ~CookiesRemoveFunction();
// ExtensionFunction:
virtual bool RunImpl() OVERRIDE;
private:
void RemoveCookieOnIOThread();
void RespondOnUIThread();
void RemoveCookieCallback();
GURL url_;
scoped_refptr<net::URLRequestContextGetter> store_context_;
scoped_ptr<extensions::api::cookies::Remove::Params> parsed_args_;
};
// Implements the cookies.getAllCookieStores() extension function.
class CookiesGetAllCookieStoresFunction : public CookiesFunction {
public:
DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores",
COOKIES_GETALLCOOKIESTORES)
protected:
virtual ~CookiesGetAllCookieStoresFunction() {}
// ExtensionFunction:
// CookiesGetAllCookieStoresFunction is sync.
virtual void Run() OVERRIDE;
virtual bool RunImpl() OVERRIDE;
};
class CookiesAPI : public ProfileKeyedAPI,
public extensions::EventRouter::Observer {
public:
explicit CookiesAPI(Profile* profile);
virtual ~CookiesAPI();
// BrowserContextKeyedService implementation.
virtual void Shutdown() OVERRIDE;
// ProfileKeyedAPI implementation.
static ProfileKeyedAPIFactory<CookiesAPI>* GetFactoryInstance();
// EventRouter::Observer implementation.
virtual void OnListenerAdded(const extensions::EventListenerInfo& details)
OVERRIDE;
private:
friend class ProfileKeyedAPIFactory<CookiesAPI>;
Profile* profile_;
// ProfileKeyedAPI implementation.
static const char* service_name() {
return "CookiesAPI";
}
static const bool kServiceIsNULLWhileTesting = true;
// Created lazily upon OnListenerAdded.
scoped_ptr<CookiesEventRouter> cookies_event_router_;
DISALLOW_COPY_AND_ASSIGN(CookiesAPI);
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_COOKIES_COOKIES_API_H_
| bsd-3-clause |
sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Data/Fortune.cs | 902 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Benchmarks.Data
{
[Table("fortune")]
public class Fortune : IComparable<Fortune>, IComparable
{
[Column("id")]
public int Id { get; set; }
[Column("message")]
[StringLength(2048)]
[Required]
public string Message { get; set; }
public int CompareTo(object obj)
{
return CompareTo((Fortune)obj);
}
public int CompareTo(Fortune other)
{
// Performance critical, using culture insensitive comparison
return String.CompareOrdinal(Message, other.Message);
}
}
}
| bsd-3-clause |
ChromeDevTools/devtools-frontend | test/e2e/resources/sources/filesystem/special-characters.html | 87 |
<script src="./with%20space.js"></script>
<script src="./with%2520space.js"></script>
| bsd-3-clause |
robclark/chromium | chrome/browser/ui/view_ids.h | 1902 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This defines an enumeration of IDs that can uniquely identify a view within
// the scope of a container view.
#ifndef CHROME_BROWSER_UI_VIEW_IDS_H_
#define CHROME_BROWSER_UI_VIEW_IDS_H_
#pragma once
enum ViewID {
VIEW_ID_NONE = 0,
// BROWSER WINDOW VIEWS
// ------------------------------------------------------
// Tabs within a window/tab strip, counting from the left.
VIEW_ID_TAB_0,
VIEW_ID_TAB_1,
VIEW_ID_TAB_2,
VIEW_ID_TAB_3,
VIEW_ID_TAB_4,
VIEW_ID_TAB_5,
VIEW_ID_TAB_6,
VIEW_ID_TAB_7,
VIEW_ID_TAB_8,
VIEW_ID_TAB_9,
VIEW_ID_TAB_LAST,
// ID for any tab. Currently only used on views.
VIEW_ID_TAB,
VIEW_ID_TAB_STRIP,
// Toolbar & toolbar elements.
VIEW_ID_TOOLBAR = 1000,
VIEW_ID_BACK_BUTTON,
VIEW_ID_FORWARD_BUTTON,
VIEW_ID_RELOAD_BUTTON,
VIEW_ID_HOME_BUTTON,
VIEW_ID_STAR_BUTTON,
VIEW_ID_LOCATION_BAR,
VIEW_ID_APP_MENU,
VIEW_ID_AUTOCOMPLETE,
VIEW_ID_BROWSER_ACTION_TOOLBAR,
VIEW_ID_FEEDBACK_BUTTON,
VIEW_ID_OMNIBOX,
VIEW_ID_CHROME_TO_MOBILE_BUTTON,
// The Bookmark Bar.
VIEW_ID_BOOKMARK_BAR,
VIEW_ID_OTHER_BOOKMARKS,
// Used for bookmarks/folders on the bookmark bar.
VIEW_ID_BOOKMARK_BAR_ELEMENT,
// Find in page.
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD,
VIEW_ID_FIND_IN_PAGE,
// Tab Container window.
VIEW_ID_TAB_CONTAINER,
// Docked dev tools.
VIEW_ID_DEV_TOOLS_DOCKED,
// The contents split.
VIEW_ID_CONTENTS_SPLIT,
// The Infobar container.
VIEW_ID_INFO_BAR_CONTAINER,
// The Download shelf.
VIEW_ID_DOWNLOAD_SHELF,
// Used in chrome/browser/ui/gtk/view_id_util_browsertests.cc
// If you add new ids, make sure the above test passes.
VIEW_ID_PREDEFINED_COUNT
};
#endif // CHROME_BROWSER_UI_VIEW_IDS_H_
| bsd-3-clause |
sumeetchhetri/FrameworkBenchmarks | frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesRawMiddleware.cs | 2038 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Benchmarks.Middleware
{
public class MultipleUpdatesRawMiddleware
{
private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateRaw));
private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
private readonly RequestDelegate _next;
public MultipleUpdatesRawMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
{
var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
var db = httpContext.RequestServices.GetService<RawDb>();
var rows = await db.LoadMultipleUpdatesRows(count);
var result = JsonSerializer.Serialize(rows, _serializerOptions);
httpContext.Response.StatusCode = StatusCodes.Status200OK;
httpContext.Response.ContentType = "application/json";
httpContext.Response.ContentLength = result.Length;
await httpContext.Response.WriteAsync(result);
return;
}
await _next(httpContext);
}
}
public static class MultipleUpdatesRawMiddlewareExtensions
{
public static IApplicationBuilder UseMultipleUpdatesRaw(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MultipleUpdatesRawMiddleware>();
}
}
}
| bsd-3-clause |
RIVeR-Lab/walrus | walrus_firmware/rosserial_teensyduino/teensyduino_sdk/arduino-1.0.6/hardware/teensy/cores/usb_midi/usb.c | 21804 | /* USB Serial Example for Teensy USB Development Board
* http://www.pjrc.com/teensy/usb_serial.html
* Copyright (c) 2008 PJRC.COM, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "usb_common.h"
#include "usb_private.h"
/**************************************************************************
*
* Endpoint Buffer Configuration
*
**************************************************************************/
static const uint8_t PROGMEM endpoint_config_table[] = {
1, EP_TYPE_INTERRUPT_IN, EP_SIZE(DEBUG_TX_SIZE) | DEBUG_TX_BUFFER,
1, EP_TYPE_INTERRUPT_OUT, EP_SIZE(DEBUG_RX_SIZE) | DEBUG_RX_BUFFER,
1, EP_TYPE_BULK_IN, EP_SIZE(MIDI_TX_SIZE) | MIDI_TX_BUFFER,
1, EP_TYPE_BULK_OUT, EP_SIZE(MIDI_RX_SIZE) | MIDI_RX_BUFFER
};
/**************************************************************************
*
* Descriptor Data
*
**************************************************************************/
// Descriptors are the data that your computer reads when it auto-detects
// this USB device (called "enumeration" in USB lingo). The most commonly
// changed items are editable at the top of this file. Changing things
// in here should only be done by those who've read chapter 9 of the USB
// spec and relevant portions of any USB class specifications!
static const uint8_t PROGMEM device_descriptor[] = {
18, // bLength
1, // bDescriptorType
0x00, 0x02, // bcdUSB
0, // bDeviceClass
0, // bDeviceSubClass
0, // bDeviceProtocol
ENDPOINT0_SIZE, // bMaxPacketSize0
LSB(VENDOR_ID), MSB(VENDOR_ID), // idVendor
LSB(PRODUCT_ID), MSB(PRODUCT_ID), // idProduct
0x00, 0x01, // bcdDevice
0, // iManufacturer
1, // iProduct
0, // iSerialNumber
1 // bNumConfigurations
};
static const uint8_t PROGMEM debug_hid_report_desc[] = {
0x06, 0xC9, 0xFF, // Usage Page 0xFFC9 (vendor defined)
0x09, 0x04, // Usage 0x04
0xA1, 0x5C, // Collection 0x5C
0x75, 0x08, // report size = 8 bits (global)
0x15, 0x00, // logical minimum = 0 (global)
0x26, 0xFF, 0x00, // logical maximum = 255 (global)
0x95, DEBUG_TX_SIZE, // report count (global)
0x09, 0x75, // usage (local)
0x81, 0x02, // Input
0x95, DEBUG_RX_SIZE, // report count (global)
0x09, 0x76, // usage (local)
0x91, 0x02, // Output
0x95, 0x04, // report count (global)
0x09, 0x76, // usage (local)
0xB1, 0x02, // Feature
0xC0 // end collection
};
#define CONFIG1_DESC_SIZE ( 9 + 74 + 32 )
#define DEBUG_HID_DESC_OFFSET ( 9 + 74 + 9 )
//#define CONFIG1_DESC_SIZE ( 9 + 92 + 32 )
//#define DEBUG_HID_DESC_OFFSET ( 9 + 92 + 9 )
static const uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
// configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
9, // bLength;
2, // bDescriptorType;
LSB(CONFIG1_DESC_SIZE), // wTotalLength
MSB(CONFIG1_DESC_SIZE),
NUM_INTERFACE, // bNumInterfaces
1, // bConfigurationValue
0, // iConfiguration
0xC0, // bmAttributes
50, // bMaxPower
// This MIDI stuff is a copy of the example from the Audio Class
// MIDI spec 1.0 (Nov 1, 1999), Appendix B, pages 37 to 43.
#if 0
http://www.usb.org/developers/devclass_docs/midi10.pdf
Section B.3 seems to say these extra descriptors are required,
but when I add them, MIDI breaks on Linux (haven't tried Mac and
Windows yet). TODO: investigate these....
reported by "John K." on May 7, 2012, subject "USB MIDI descriptors"
// Standard AC Interface Descriptor
9, // bLength
4, // bDescriptorType = INTERFACE
0, // bInterfaceNumber
0, // bAlternateSetting
0, // bNumEndpoints
1, // bInterfaceClass = AUDIO
1, // bInterfaceSubclass = AUDIO_CONTROL
0, // bInterfaceProtocol
0, // iInterface
// Class-specific AC Interface Descriptor
9, // bLength
0x24, // bDescriptorType = CS_INTERFACE
1, // bDescriptorSubtype = HEADER
0x00, 0x01, // bcdADC
0x09, 0x00, // wTotalLength
1, // bInCollection
1, // baInterfaceNr(1)
#endif
// Standard MS Interface Descriptor,
9, // bLength
4, // bDescriptorType
MIDI_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x01, // bInterfaceClass (0x01 = Audio)
0x03, // bInterfaceSubClass (0x03 = MIDI)
0x00, // bInterfaceProtocol (unused for MIDI)
0, // iInterface
// MIDI MS Interface Header, USB MIDI 6.1.2.1, page 21, Table 6-2
7, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x01, // bDescriptorSubtype = MS_HEADER
0x00, 0x01, // bcdMSC = revision 01.00
0x41, 0x00, // wTotalLength
// MIDI IN Jack Descriptor, B.4.3, Table B-7 (embedded), page 40
6, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x02, // bDescriptorSubtype = MIDI_IN_JACK
0x01, // bJackType = EMBEDDED
1, // bJackID, ID = 1
0, // iJack
// MIDI IN Jack Descriptor, B.4.3, Table B-8 (external), page 40
6, // bLength
0x24, // bDescriptorType = CS_INTERFACE
0x02, // bDescriptorSubtype = MIDI_IN_JACK
0x02, // bJackType = EXTERNAL
2, // bJackID, ID = 2
0, // iJack
// MIDI OUT Jack Descriptor, B.4.4, Table B-9, page 41
9,
0x24, // bDescriptorType = CS_INTERFACE
0x03, // bDescriptorSubtype = MIDI_OUT_JACK
0x01, // bJackType = EMBEDDED
3, // bJackID, ID = 3
1, // bNrInputPins = 1 pin
2, // BaSourceID(1) = 2
1, // BaSourcePin(1) = first pin
0, // iJack
// MIDI OUT Jack Descriptor, B.4.4, Table B-10, page 41
9,
0x24, // bDescriptorType = CS_INTERFACE
0x03, // bDescriptorSubtype = MIDI_OUT_JACK
0x02, // bJackType = EXTERNAL
4, // bJackID, ID = 4
1, // bNrInputPins = 1 pin
1, // BaSourceID(1) = 1
1, // BaSourcePin(1) = first pin
0, // iJack
// Standard Bulk OUT Endpoint Descriptor, B.5.1, Table B-11, pae 42
9, // bLength
5, // bDescriptorType = ENDPOINT
MIDI_RX_ENDPOINT, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MIDI_RX_SIZE, 0, // wMaxPacketSize
0, // bInterval
0, // bRefresh
0, // bSynchAddress
// Class-specific MS Bulk OUT Endpoint Descriptor, B.5.2, Table B-12, page 42
5, // bLength
0x25, // bDescriptorSubtype = CS_ENDPOINT
0x01, // bJackType = MS_GENERAL
1, // bNumEmbMIDIJack = 1 jack
1, // BaAssocJackID(1) = jack ID #1
// Standard Bulk IN Endpoint Descriptor, B.5.1, Table B-11, pae 42
9, // bLength
5, // bDescriptorType = ENDPOINT
MIDI_TX_ENDPOINT | 0x80, // bEndpointAddress
0x02, // bmAttributes (0x02=bulk)
MIDI_TX_SIZE, 0, // wMaxPacketSize
0, // bInterval
0, // bRefresh
0, // bSynchAddress
// Class-specific MS Bulk IN Endpoint Descriptor, B.5.2, Table B-12, page 42
5, // bLength
0x25, // bDescriptorSubtype = CS_ENDPOINT
0x01, // bJackType = MS_GENERAL
1, // bNumEmbMIDIJack = 1 jack
3, // BaAssocJackID(1) = jack ID #3
// interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
9, // bLength
4, // bDescriptorType
DEBUG_INTERFACE, // bInterfaceNumber
0, // bAlternateSetting
2, // bNumEndpoints
0x03, // bInterfaceClass (0x03 = HID)
0x00, // bInterfaceSubClass
0x00, // bInterfaceProtocol
0, // iInterface
// HID interface descriptor, HID 1.11 spec, section 6.2.1
9, // bLength
0x21, // bDescriptorType
0x11, 0x01, // bcdHID
0, // bCountryCode
1, // bNumDescriptors
0x22, // bDescriptorType
sizeof(debug_hid_report_desc), // wDescriptorLength
0,
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
DEBUG_TX_ENDPOINT | 0x80, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
DEBUG_TX_SIZE, 0, // wMaxPacketSize
DEBUG_TX_INTERVAL, // bInterval
// endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
7, // bLength
5, // bDescriptorType
DEBUG_RX_ENDPOINT, // bEndpointAddress
0x03, // bmAttributes (0x03=intr)
DEBUG_RX_SIZE, 0, // wMaxPacketSize
DEBUG_RX_INTERVAL, // bInterval
};
// If you're desperate for a little extra code memory, these strings
// can be completely removed if iManufacturer, iProduct, iSerialNumber
// in the device desciptor are changed to zeros.
struct usb_string_descriptor_struct {
uint8_t bLength;
uint8_t bDescriptorType;
int16_t wString[];
};
static const struct usb_string_descriptor_struct PROGMEM string0 = {
4,
3,
{0x0409}
};
static const struct usb_string_descriptor_struct PROGMEM string1 = {
sizeof(STR_PRODUCT),
3,
STR_PRODUCT
};
// This table defines which descriptor data is sent for each specific
// request from the host (in wValue and wIndex).
static const struct descriptor_list_struct {
uint16_t wValue;
uint16_t wIndex;
const uint8_t *addr;
uint8_t length;
} PROGMEM descriptor_list[] = {
{0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
{0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)},
{0x2200, DEBUG_INTERFACE, debug_hid_report_desc, sizeof(debug_hid_report_desc)},
{0x2100, DEBUG_INTERFACE, config1_descriptor+DEBUG_HID_DESC_OFFSET, 9},
{0x0300, 0x0000, (const uint8_t *)&string0, 4},
{0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_PRODUCT)},
};
#define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct))
/**************************************************************************
*
* Variables - these are the only non-stack RAM usage
*
**************************************************************************/
// zero when we are not configured, non-zero when enumerated
volatile uint8_t usb_configuration USBSTATE;
volatile uint8_t usb_suspended USBSTATE;
// the time remaining before we transmit any partially full
// packet, or send a zero length packet.
volatile uint8_t debug_flush_timer USBSTATE;
/**************************************************************************
*
* Public Functions - these are the API intended for the user
*
**************************************************************************/
// initialize USB serial
void usb_init(void)
{
uint8_t u;
u = USBCON;
if ((u & (1<<USBE)) && !(u & (1<<FRZCLK))) return;
HW_CONFIG();
USB_FREEZE(); // enable USB
PLL_CONFIG(); // config PLL
while (!(PLLCSR & (1<<PLOCK))) ; // wait for PLL lock
USB_CONFIG(); // start USB clock
UDCON = 0; // enable attach resistor
usb_configuration = 0;
usb_suspended = 0;
debug_flush_timer = 0;
UDINT = 0;
UDIEN = (1<<EORSTE)|(1<<SOFE);
//sei(); // init() in wiring.c does this
}
void usb_shutdown(void)
{
UDIEN = 0; // disable interrupts
UDCON = 1; // disconnect attach resistor
USBCON = 0; // shut off USB periperal
PLLCSR = 0; // shut off PLL
usb_configuration = 0;
usb_suspended = 1;
}
// Public API functions moved to usb_api.cpp
/**************************************************************************
*
* Private Functions - not intended for general user consumption....
*
**************************************************************************/
// USB Device Interrupt - handle all device-level events
// the transmit buffer flushing is triggered by the start of frame
//
ISR(USB_GEN_vect)
{
uint8_t intbits, t;
intbits = UDINT;
UDINT = 0;
if (intbits & (1<<EORSTI)) {
UENUM = 0;
UECONX = 1;
UECFG0X = EP_TYPE_CONTROL;
UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
UEIENX = (1<<RXSTPE);
usb_configuration = 0;
}
if ((intbits & (1<<SOFI)) && usb_configuration) {
t = debug_flush_timer;
if (t) {
debug_flush_timer = --t;
if (!t) {
UENUM = DEBUG_TX_ENDPOINT;
while ((UEINTX & (1<<RWAL))) {
UEDATX = 0;
}
UEINTX = 0x3A;
}
}
UENUM = MIDI_TX_ENDPOINT;
if (UEBCLX) UEINTX = 0x3A;
}
if (intbits & (1<<SUSPI)) {
// USB Suspend (inactivity for 3ms)
UDIEN = (1<<WAKEUPE);
usb_configuration = 0;
usb_suspended = 1;
#if (F_CPU >= 8000000L)
// WAKEUPI does not work with USB clock freeze
// when CPU is running less than 8 MHz.
// Is this a hardware bug?
USB_FREEZE(); // shut off USB
PLLCSR = 0; // shut off PLL
#endif
// to properly meet the USB spec, current must
// reduce to less than 2.5 mA, which means using
// powerdown mode, but that breaks the Arduino
// user's paradigm....
}
if (usb_suspended && (intbits & (1<<WAKEUPI))) {
// USB Resume (pretty much any activity)
#if (F_CPU >= 8000000L)
PLL_CONFIG();
while (!(PLLCSR & (1<<PLOCK))) ;
USB_CONFIG();
#endif
UDIEN = (1<<EORSTE)|(1<<SOFE)|(1<<SUSPE);
usb_suspended = 0;
return;
}
}
// Misc functions to wait for ready and send/receive packets
static inline void usb_wait_in_ready(void)
{
while (!(UEINTX & (1<<TXINI))) ;
}
static inline void usb_send_in(void)
{
UEINTX = ~(1<<TXINI);
}
static inline void usb_wait_receive_out(void)
{
while (!(UEINTX & (1<<RXOUTI))) ;
}
static inline void usb_ack_out(void)
{
UEINTX = ~(1<<RXOUTI);
}
// USB Endpoint Interrupt - endpoint 0 is handled here. The
// other endpoints are manipulated by the user-callable
// functions, and the start-of-frame interrupt.
//
ISR(USB_COM_vect)
{
uint8_t intbits;
const uint8_t *list;
const uint8_t *cfg;
uint8_t i, n, len, en;
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
uint16_t desc_val;
const uint8_t *desc_addr;
uint8_t desc_length;
UENUM = 0;
intbits = UEINTX;
if (intbits & (1<<RXSTPI)) {
bmRequestType = UEDATX;
bRequest = UEDATX;
read_word_lsbfirst(wValue, UEDATX);
read_word_lsbfirst(wIndex, UEDATX);
read_word_lsbfirst(wLength, UEDATX);
UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
if (bRequest == GET_DESCRIPTOR) {
list = (const uint8_t *)descriptor_list;
for (i=0; ; i++) {
if (i >= NUM_DESC_LIST) {
UECONX = (1<<STALLRQ)|(1<<EPEN); //stall
return;
}
pgm_read_word_postinc(desc_val, list);
if (desc_val != wValue) {
list += sizeof(struct descriptor_list_struct)-2;
continue;
}
pgm_read_word_postinc(desc_val, list);
if (desc_val != wIndex) {
list += sizeof(struct descriptor_list_struct)-4;
continue;
}
pgm_read_word_postinc(desc_addr, list);
desc_length = pgm_read_byte(list);
break;
}
len = (wLength < 256) ? wLength : 255;
if (len > desc_length) len = desc_length;
list = desc_addr;
do {
// wait for host ready for IN packet
do {
i = UEINTX;
} while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
if (i & (1<<RXOUTI)) return; // abort
// send IN packet
n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
for (i = n; i; i--) {
pgm_read_byte_postinc(UEDATX, list);
}
len -= n;
usb_send_in();
} while (len || n == ENDPOINT0_SIZE);
return;
}
if (bRequest == SET_ADDRESS) {
usb_send_in();
usb_wait_in_ready();
UDADDR = wValue | (1<<ADDEN);
return;
}
if (bRequest == SET_CONFIGURATION && bmRequestType == 0) {
usb_configuration = wValue;
debug_flush_timer = 0;
usb_send_in();
cfg = endpoint_config_table;
for (i=1; i<NUM_ENDPOINTS; i++) {
UENUM = i;
pgm_read_byte_postinc(en, cfg);
UECONX = en;
if (en) {
pgm_read_byte_postinc(UECFG0X, cfg);
pgm_read_byte_postinc(UECFG1X, cfg);
}
}
UERST = 0x1E;
UERST = 0;
return;
}
if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
usb_wait_in_ready();
UEDATX = usb_configuration;
usb_send_in();
return;
}
if (bRequest == GET_STATUS) {
usb_wait_in_ready();
i = 0;
if (bmRequestType == 0x82) {
UENUM = wIndex;
if (UECONX & (1<<STALLRQ)) i = 1;
UENUM = 0;
}
UEDATX = i;
UEDATX = 0;
usb_send_in();
return;
}
if ((bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE)
&& bmRequestType == 0x02 && wValue == 0) {
i = wIndex & 0x7F;
if (i >= 1 && i <= MAX_ENDPOINT) {
usb_send_in();
UENUM = i;
if (bRequest == SET_FEATURE) {
UECONX = (1<<STALLRQ)|(1<<EPEN);
} else {
UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
UERST = (1 << i);
UERST = 0;
}
return;
}
}
if (wIndex == DEBUG_INTERFACE) {
if (bRequest == HID_GET_REPORT && bmRequestType == 0xA1) {
len = wLength;
do {
// wait for host ready for IN packet
do {
i = UEINTX;
} while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
if (i & (1<<RXOUTI)) return; // abort
// send IN packet
n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
for (i = n; i; i--) {
UEDATX = 0;
}
len -= n;
usb_send_in();
} while (len || n == ENDPOINT0_SIZE);
return;
}
if (bRequest == HID_SET_REPORT && bmRequestType == 0x21) {
if (wValue == 0x0300 && wLength == 0x0004) {
uint8_t b1, b2, b3, b4;
usb_wait_receive_out();
b1 = UEDATX;
b2 = UEDATX;
b3 = UEDATX;
b4 = UEDATX;
usb_ack_out();
usb_send_in();
if (b1 == 0xA9 && b2 == 0x45 && b3 == 0xC2 && b4 == 0x6B)
_reboot_Teensyduino_();
if (b1 == 0x8B && b2 == 0xC5 && b3 == 0x1D && b4 == 0x70)
_restart_Teensyduino_();
}
}
}
if (bRequest == 0xC9 && bmRequestType == 0x40) {
usb_send_in();
usb_wait_in_ready();
_restart_Teensyduino_();
}
}
UECONX = (1<<STALLRQ) | (1<<EPEN); // stall
}
| bsd-3-clause |
BellScurry/gem5-fault-injection | src/cpu/o3/fetch_impl.hh | 54320 | /*
* Copyright (c) 2010-2014 ARM Limited
* Copyright (c) 2012-2013 AMD
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Kevin Lim
* Korey Sewell
*/
#ifndef __CPU_O3_FETCH_IMPL_HH__
#define __CPU_O3_FETCH_IMPL_HH__
#include <algorithm>
#include <cstring>
#include <list>
#include <map>
#include <queue>
#include "arch/isa_traits.hh"
#include "arch/tlb.hh"
#include "arch/utility.hh"
#include "arch/vtophys.hh"
#include "base/random.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
//#include "cpu/checker/cpu.hh"
#include "cpu/o3/fetch.hh"
#include "cpu/exetrace.hh"
#include "debug/Activity.hh"
#include "debug/Drain.hh"
#include "debug/Fetch.hh"
#include "debug/O3PipeView.hh"
#include "mem/packet.hh"
#include "params/DerivO3CPU.hh"
#include "sim/byteswap.hh"
#include "sim/core.hh"
#include "sim/eventq.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
#include "cpu/o3/isa_specific.hh"
using namespace std;
template<class Impl>
DefaultFetch<Impl>::DefaultFetch(O3CPU *_cpu, DerivO3CPUParams *params)
: cpu(_cpu),
decodeToFetchDelay(params->decodeToFetchDelay),
renameToFetchDelay(params->renameToFetchDelay),
iewToFetchDelay(params->iewToFetchDelay),
commitToFetchDelay(params->commitToFetchDelay),
fetchWidth(params->fetchWidth),
decodeWidth(params->decodeWidth),
retryPkt(NULL),
retryTid(InvalidThreadID),
cacheBlkSize(cpu->cacheLineSize()),
fetchBufferSize(params->fetchBufferSize),
fetchBufferMask(fetchBufferSize - 1),
fetchQueueSize(params->fetchQueueSize),
numThreads(params->numThreads),
numFetchingThreads(params->smtNumFetchingThreads),
finishTranslationEvent(this)
{
if (numThreads > Impl::MaxThreads)
fatal("numThreads (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxThreads in src/cpu/o3/impl.hh\n",
numThreads, static_cast<int>(Impl::MaxThreads));
if (fetchWidth > Impl::MaxWidth)
fatal("fetchWidth (%d) is larger than compiled limit (%d),\n"
"\tincrease MaxWidth in src/cpu/o3/impl.hh\n",
fetchWidth, static_cast<int>(Impl::MaxWidth));
if (fetchBufferSize > cacheBlkSize)
fatal("fetch buffer size (%u bytes) is greater than the cache "
"block size (%u bytes)\n", fetchBufferSize, cacheBlkSize);
if (cacheBlkSize % fetchBufferSize)
fatal("cache block (%u bytes) is not a multiple of the "
"fetch buffer (%u bytes)\n", cacheBlkSize, fetchBufferSize);
std::string policy = params->smtFetchPolicy;
// Convert string to lowercase
std::transform(policy.begin(), policy.end(), policy.begin(),
(int(*)(int)) tolower);
// Figure out fetch policy
if (policy == "singlethread") {
fetchPolicy = SingleThread;
if (numThreads > 1)
panic("Invalid Fetch Policy for a SMT workload.");
} else if (policy == "roundrobin") {
fetchPolicy = RoundRobin;
DPRINTF(Fetch, "Fetch policy set to Round Robin\n");
} else if (policy == "branch") {
fetchPolicy = Branch;
DPRINTF(Fetch, "Fetch policy set to Branch Count\n");
} else if (policy == "iqcount") {
fetchPolicy = IQ;
DPRINTF(Fetch, "Fetch policy set to IQ count\n");
} else if (policy == "lsqcount") {
fetchPolicy = LSQ;
DPRINTF(Fetch, "Fetch policy set to LSQ count\n");
} else {
fatal("Invalid Fetch Policy. Options Are: {SingleThread,"
" RoundRobin,LSQcount,IQcount}\n");
}
// Get the size of an instruction.
instSize = sizeof(TheISA::MachInst);
for (int i = 0; i < Impl::MaxThreads; i++) {
decoder[i] = NULL;
fetchBuffer[i] = NULL;
fetchBufferPC[i] = 0;
fetchBufferValid[i] = false;
}
branchPred = params->branchPred;
for (ThreadID tid = 0; tid < numThreads; tid++) {
decoder[tid] = new TheISA::Decoder(params->isa[tid]);
// Create space to buffer the cache line data,
// which may not hold the entire cache line.
fetchBuffer[tid] = new uint8_t[fetchBufferSize];
}
}
template <class Impl>
std::string
DefaultFetch<Impl>::name() const
{
return cpu->name() + ".fetch";
}
template <class Impl>
void
DefaultFetch<Impl>::regProbePoints()
{
ppFetch = new ProbePointArg<DynInstPtr>(cpu->getProbeManager(), "Fetch");
ppFetchRequestSent = new ProbePointArg<RequestPtr>(cpu->getProbeManager(),
"FetchRequest");
}
template <class Impl>
void
DefaultFetch<Impl>::regStats()
{
icacheStallCycles
.name(name() + ".icacheStallCycles")
.desc("Number of cycles fetch is stalled on an Icache miss")
.prereq(icacheStallCycles);
fetchedInsts
.name(name() + ".Insts")
.desc("Number of instructions fetch has processed")
.prereq(fetchedInsts);
fetchedBranches
.name(name() + ".Branches")
.desc("Number of branches that fetch encountered")
.prereq(fetchedBranches);
predictedBranches
.name(name() + ".predictedBranches")
.desc("Number of branches that fetch has predicted taken")
.prereq(predictedBranches);
fetchCycles
.name(name() + ".Cycles")
.desc("Number of cycles fetch has run and was not squashing or"
" blocked")
.prereq(fetchCycles);
fetchSquashCycles
.name(name() + ".SquashCycles")
.desc("Number of cycles fetch has spent squashing")
.prereq(fetchSquashCycles);
fetchTlbCycles
.name(name() + ".TlbCycles")
.desc("Number of cycles fetch has spent waiting for tlb")
.prereq(fetchTlbCycles);
fetchIdleCycles
.name(name() + ".IdleCycles")
.desc("Number of cycles fetch was idle")
.prereq(fetchIdleCycles);
fetchBlockedCycles
.name(name() + ".BlockedCycles")
.desc("Number of cycles fetch has spent blocked")
.prereq(fetchBlockedCycles);
fetchedCacheLines
.name(name() + ".CacheLines")
.desc("Number of cache lines fetched")
.prereq(fetchedCacheLines);
fetchMiscStallCycles
.name(name() + ".MiscStallCycles")
.desc("Number of cycles fetch has spent waiting on interrupts, or "
"bad addresses, or out of MSHRs")
.prereq(fetchMiscStallCycles);
fetchPendingDrainCycles
.name(name() + ".PendingDrainCycles")
.desc("Number of cycles fetch has spent waiting on pipes to drain")
.prereq(fetchPendingDrainCycles);
fetchNoActiveThreadStallCycles
.name(name() + ".NoActiveThreadStallCycles")
.desc("Number of stall cycles due to no active thread to fetch from")
.prereq(fetchNoActiveThreadStallCycles);
fetchPendingTrapStallCycles
.name(name() + ".PendingTrapStallCycles")
.desc("Number of stall cycles due to pending traps")
.prereq(fetchPendingTrapStallCycles);
fetchPendingQuiesceStallCycles
.name(name() + ".PendingQuiesceStallCycles")
.desc("Number of stall cycles due to pending quiesce instructions")
.prereq(fetchPendingQuiesceStallCycles);
fetchIcacheWaitRetryStallCycles
.name(name() + ".IcacheWaitRetryStallCycles")
.desc("Number of stall cycles due to full MSHR")
.prereq(fetchIcacheWaitRetryStallCycles);
fetchIcacheSquashes
.name(name() + ".IcacheSquashes")
.desc("Number of outstanding Icache misses that were squashed")
.prereq(fetchIcacheSquashes);
fetchTlbSquashes
.name(name() + ".ItlbSquashes")
.desc("Number of outstanding ITLB misses that were squashed")
.prereq(fetchTlbSquashes);
fetchNisnDist
.init(/* base value */ 0,
/* last value */ fetchWidth,
/* bucket size */ 1)
.name(name() + ".rateDist")
.desc("Number of instructions fetched each cycle (Total)")
.flags(Stats::pdf);
idleRate
.name(name() + ".idleRate")
.desc("Percent of cycles fetch was idle")
.prereq(idleRate);
idleRate = fetchIdleCycles * 100 / cpu->numCycles;
branchRate
.name(name() + ".branchRate")
.desc("Number of branch fetches per cycle")
.flags(Stats::total);
branchRate = fetchedBranches / cpu->numCycles;
fetchRate
.name(name() + ".rate")
.desc("Number of inst fetches per cycle")
.flags(Stats::total);
fetchRate = fetchedInsts / cpu->numCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *time_buffer)
{
timeBuffer = time_buffer;
// Create wires to get information from proper places in time buffer.
fromDecode = timeBuffer->getWire(-decodeToFetchDelay);
fromRename = timeBuffer->getWire(-renameToFetchDelay);
fromIEW = timeBuffer->getWire(-iewToFetchDelay);
fromCommit = timeBuffer->getWire(-commitToFetchDelay);
}
template<class Impl>
void
DefaultFetch<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
{
activeThreads = at_ptr;
}
template<class Impl>
void
DefaultFetch<Impl>::setFetchQueue(TimeBuffer<FetchStruct> *ftb_ptr)
{
// Create wire to write information to proper place in fetch time buf.
toDecode = ftb_ptr->getWire(0);
}
template<class Impl>
void
DefaultFetch<Impl>::startupStage()
{
assert(priorityList.empty());
resetStage();
// Fetch needs to start fetching instructions at the very beginning,
// so it must start up in active state.
switchToActive();
}
template<class Impl>
void
DefaultFetch<Impl>::resetStage()
{
numInst = 0;
interruptPending = false;
cacheBlocked = false;
priorityList.clear();
// Setup PC and nextPC with initial state.
for (ThreadID tid = 0; tid < numThreads; ++tid) {
fetchStatus[tid] = Running;
pc[tid] = cpu->pcState(tid);
fetchOffset[tid] = 0;
macroop[tid] = NULL;
delayedCommit[tid] = false;
memReq[tid] = NULL;
stalls[tid].decode = false;
stalls[tid].drain = false;
fetchBufferPC[tid] = 0;
fetchBufferValid[tid] = false;
fetchQueue[tid].clear();
priorityList.push_back(tid);
}
wroteToTimeBuffer = false;
_status = Inactive;
}
template<class Impl>
void
DefaultFetch<Impl>::processCacheCompletion(PacketPtr pkt)
{
ThreadID tid = cpu->contextToThread(pkt->req->contextId());
DPRINTF(Fetch, "[tid:%u] Waking up from cache miss.\n", tid);
assert(!cpu->switchedOut());
// Only change the status if it's still waiting on the icache access
// to return.
if (fetchStatus[tid] != IcacheWaitResponse ||
pkt->req != memReq[tid]) {
++fetchIcacheSquashes;
delete pkt->req;
delete pkt;
return;
}
memcpy(fetchBuffer[tid], pkt->getConstPtr<uint8_t>(), fetchBufferSize);
fetchBufferValid[tid] = true;
// Wake up the CPU (if it went to sleep and was waiting on
// this completion event).
cpu->wakeCPU();
DPRINTF(Activity, "[tid:%u] Activating fetch due to cache completion\n",
tid);
switchToActive();
// Only switch to IcacheAccessComplete if we're not stalled as well.
if (checkStall(tid)) {
fetchStatus[tid] = Blocked;
} else {
fetchStatus[tid] = IcacheAccessComplete;
}
pkt->req->setAccessLatency();
cpu->ppInstAccessComplete->notify(pkt);
// Reset the mem req to NULL.
delete pkt->req;
delete pkt;
memReq[tid] = NULL;
}
template <class Impl>
void
DefaultFetch<Impl>::drainResume()
{
for (ThreadID i = 0; i < numThreads; ++i)
stalls[i].drain = false;
}
template <class Impl>
void
DefaultFetch<Impl>::drainSanityCheck() const
{
assert(isDrained());
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
assert(!cacheBlocked);
assert(!interruptPending);
for (ThreadID i = 0; i < numThreads; ++i) {
assert(!memReq[i]);
assert(fetchStatus[i] == Idle || stalls[i].drain);
}
branchPred->drainSanityCheck();
}
template <class Impl>
bool
DefaultFetch<Impl>::isDrained() const
{
/* Make sure that threads are either idle of that the commit stage
* has signaled that draining has completed by setting the drain
* stall flag. This effectively forces the pipeline to be disabled
* until the whole system is drained (simulation may continue to
* drain other components).
*/
for (ThreadID i = 0; i < numThreads; ++i) {
// Verify fetch queues are drained
if (!fetchQueue[i].empty())
return false;
// Return false if not idle or drain stalled
if (fetchStatus[i] != Idle) {
if (fetchStatus[i] == Blocked && stalls[i].drain)
continue;
else
return false;
}
}
/* The pipeline might start up again in the middle of the drain
* cycle if the finish translation event is scheduled, so make
* sure that's not the case.
*/
return !finishTranslationEvent.scheduled();
}
template <class Impl>
void
DefaultFetch<Impl>::takeOverFrom()
{
assert(cpu->getInstPort().isConnected());
resetStage();
}
template <class Impl>
void
DefaultFetch<Impl>::drainStall(ThreadID tid)
{
assert(cpu->isDraining());
assert(!stalls[tid].drain);
DPRINTF(Drain, "%i: Thread drained.\n", tid);
stalls[tid].drain = true;
}
template <class Impl>
void
DefaultFetch<Impl>::wakeFromQuiesce()
{
DPRINTF(Fetch, "Waking up from quiesce\n");
// Hopefully this is safe
// @todo: Allow other threads to wake from quiesce.
fetchStatus[0] = Running;
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToActive()
{
if (_status == Inactive) {
DPRINTF(Activity, "Activating stage.\n");
cpu->activateStage(O3CPU::FetchIdx);
_status = Active;
}
}
template <class Impl>
inline void
DefaultFetch<Impl>::switchToInactive()
{
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
_status = Inactive;
}
}
template <class Impl>
void
DefaultFetch<Impl>::deactivateThread(ThreadID tid)
{
// Update priority list
auto thread_it = std::find(priorityList.begin(), priorityList.end(), tid);
if (thread_it != priorityList.end()) {
priorityList.erase(thread_it);
}
}
template <class Impl>
bool
DefaultFetch<Impl>::lookupAndUpdateNextPC(
DynInstPtr &inst, TheISA::PCState &nextPC)
{
// Do branch prediction check here.
// A bit of a misnomer...next_PC is actually the current PC until
// this function updates it.
bool predict_taken;
if (!inst->isControl()) {
TheISA::advancePC(nextPC, inst->staticInst);
inst->setPredTarg(nextPC);
inst->setPredTaken(false);
return false;
}
ThreadID tid = inst->threadNumber;
predict_taken = branchPred->predict(inst->staticInst, inst->seqNum,
nextPC, tid);
if (predict_taken) {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]: Branch predicted to be taken to %s.\n",
tid, inst->seqNum, nextPC);
} else {
DPRINTF(Fetch, "[tid:%i]: [sn:%i]:Branch predicted to be not taken.\n",
tid, inst->seqNum);
}
DPRINTF(Fetch, "[tid:%i]: [sn:%i] Branch predicted to go to %s.\n",
tid, inst->seqNum, nextPC);
inst->setPredTarg(nextPC);
inst->setPredTaken(predict_taken);
++fetchedBranches;
if (predict_taken) {
++predictedBranches;
}
return predict_taken;
}
template <class Impl>
bool
DefaultFetch<Impl>::fetchCacheLine(Addr vaddr, ThreadID tid, Addr pc)
{
Fault fault = NoFault;
assert(!cpu->switchedOut());
// @todo: not sure if these should block translation.
//AlphaDep
if (cacheBlocked) {
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, cache blocked\n",
tid);
return false;
} else if (checkInterrupt(pc) && !delayedCommit[tid]) {
// Hold off fetch from getting new instructions when:
// Cache is blocked, or
// while an interrupt is pending and we're not in PAL mode, or
// fetch is switched out.
DPRINTF(Fetch, "[tid:%i] Can't fetch cache line, interrupt pending\n",
tid);
return false;
}
// Align the fetch address to the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(vaddr);
DPRINTF(Fetch, "[tid:%i] Fetching cache line %#x for addr %#x\n",
tid, fetchBufferBlockPC, vaddr);
// Setup the memReq to do a read of the first instruction's address.
// Set the appropriate read size and flags as well.
// Build request here.
RequestPtr mem_req =
new Request(tid, fetchBufferBlockPC, fetchBufferSize,
Request::INST_FETCH, cpu->instMasterId(), pc,
cpu->thread[tid]->contextId());
mem_req->taskId(cpu->taskId());
memReq[tid] = mem_req;
// Initiate translation of the icache block
fetchStatus[tid] = ItlbWait;
FetchTranslation *trans = new FetchTranslation(this);
cpu->itb->translateTiming(mem_req, cpu->thread[tid]->getTC(),
trans, BaseTLB::Execute);
return true;
}
template <class Impl>
void
DefaultFetch<Impl>::finishTranslation(const Fault &fault, RequestPtr mem_req)
{
ThreadID tid = cpu->contextToThread(mem_req->contextId());
Addr fetchBufferBlockPC = mem_req->getVaddr();
assert(!cpu->switchedOut());
// Wake up CPU if it was idle
cpu->wakeCPU();
if (fetchStatus[tid] != ItlbWait || mem_req != memReq[tid] ||
mem_req->getVaddr() != memReq[tid]->getVaddr()) {
DPRINTF(Fetch, "[tid:%i] Ignoring itlb completed after squash\n",
tid);
++fetchTlbSquashes;
delete mem_req;
return;
}
// If translation was successful, attempt to read the icache block.
if (fault == NoFault) {
// Check that we're not going off into random memory
// If we have, just wait around for commit to squash something and put
// us on the right track
if (!cpu->system->isMemAddr(mem_req->getPaddr())) {
warn("Address %#x is outside of physical memory, stopping fetch\n",
mem_req->getPaddr());
fetchStatus[tid] = NoGoodAddr;
delete mem_req;
memReq[tid] = NULL;
return;
}
// Build packet here.
PacketPtr data_pkt = new Packet(mem_req, MemCmd::ReadReq);
data_pkt->dataDynamic(new uint8_t[fetchBufferSize]);
fetchBufferPC[tid] = fetchBufferBlockPC;
fetchBufferValid[tid] = false;
DPRINTF(Fetch, "Fetch: Doing instruction read.\n");
fetchedCacheLines++;
// Access the cache.
if (!cpu->getInstPort().sendTimingReq(data_pkt)) {
assert(retryPkt == NULL);
assert(retryTid == InvalidThreadID);
DPRINTF(Fetch, "[tid:%i] Out of MSHRs!\n", tid);
fetchStatus[tid] = IcacheWaitRetry;
retryPkt = data_pkt;
retryTid = tid;
cacheBlocked = true;
} else {
DPRINTF(Fetch, "[tid:%i]: Doing Icache access.\n", tid);
DPRINTF(Activity, "[tid:%i]: Activity: Waiting on I-cache "
"response.\n", tid);
lastIcacheStall[tid] = curTick();
fetchStatus[tid] = IcacheWaitResponse;
// Notify Fetch Request probe when a packet containing a fetch
// request is successfully sent
ppFetchRequestSent->notify(mem_req);
}
} else {
// Don't send an instruction to decode if we can't handle it.
if (!(numInst < fetchWidth) || !(fetchQueue[tid].size() < fetchQueueSize)) {
assert(!finishTranslationEvent.scheduled());
finishTranslationEvent.setFault(fault);
finishTranslationEvent.setReq(mem_req);
cpu->schedule(finishTranslationEvent,
cpu->clockEdge(Cycles(1)));
return;
}
DPRINTF(Fetch, "[tid:%i] Got back req with addr %#x but expected %#x\n",
tid, mem_req->getVaddr(), memReq[tid]->getVaddr());
// Translation faulted, icache request won't be sent.
delete mem_req;
memReq[tid] = NULL;
// Send the fault to commit. This thread will not do anything
// until commit handles the fault. The only other way it can
// wake up is if a squash comes along and changes the PC.
TheISA::PCState fetchPC = pc[tid];
DPRINTF(Fetch, "[tid:%i]: Translation faulted, building noop.\n", tid);
// We will use a nop in ordier to carry the fault.
DynInstPtr instruction = buildInst(tid,
decoder[tid]->decode(TheISA::NoopMachInst, fetchPC.instAddr()),
NULL, fetchPC, fetchPC, false);
instruction->setPredTarg(fetchPC);
instruction->fault = fault;
wroteToTimeBuffer = true;
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
fetchStatus[tid] = TrapPending;
DPRINTF(Fetch, "[tid:%i]: Blocked, need to handle the trap.\n", tid);
DPRINTF(Fetch, "[tid:%i]: fault (%s) detected @ PC %s.\n",
tid, fault->name(), pc[tid]);
}
_status = updateFetchStatus();
}
template <class Impl>
inline void
DefaultFetch<Impl>::doSquash(const TheISA::PCState &newPC,
const DynInstPtr squashInst, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing, setting PC to: %s.\n",
tid, newPC);
pc[tid] = newPC;
fetchOffset[tid] = 0;
if (squashInst && squashInst->pcState().instAddr() == newPC.instAddr())
macroop[tid] = squashInst->macroop;
else
macroop[tid] = NULL;
decoder[tid]->reset();
// Clear the icache miss if it's outstanding.
if (fetchStatus[tid] == IcacheWaitResponse) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding Icache miss.\n",
tid);
memReq[tid] = NULL;
} else if (fetchStatus[tid] == ItlbWait) {
DPRINTF(Fetch, "[tid:%i]: Squashing outstanding ITLB miss.\n",
tid);
memReq[tid] = NULL;
}
// Get rid of the retrying packet if it was from this thread.
if (retryTid == tid) {
assert(cacheBlocked);
if (retryPkt) {
delete retryPkt->req;
delete retryPkt;
}
retryPkt = NULL;
retryTid = InvalidThreadID;
}
fetchStatus[tid] = Squashing;
// Empty fetch queue
fetchQueue[tid].clear();
// microops are being squashed, it is not known wheather the
// youngest non-squashed microop was marked delayed commit
// or not. Setting the flag to true ensures that the
// interrupts are not handled when they cannot be, though
// some opportunities to handle interrupts may be missed.
delayedCommit[tid] = true;
++fetchSquashCycles;
}
template<class Impl>
void
DefaultFetch<Impl>::squashFromDecode(const TheISA::PCState &newPC,
const DynInstPtr squashInst,
const InstSeqNum seq_num, ThreadID tid)
{
DPRINTF(Fetch, "[tid:%i]: Squashing from decode.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are in flight between
// fetch and decode.
cpu->removeInstsUntil(seq_num, tid);
}
template<class Impl>
bool
DefaultFetch<Impl>::checkStall(ThreadID tid) const
{
bool ret_val = false;
if (stalls[tid].drain) {
assert(cpu->isDraining());
DPRINTF(Fetch,"[tid:%i]: Drain stall detected.\n",tid);
ret_val = true;
}
return ret_val;
}
template<class Impl>
typename DefaultFetch<Impl>::FetchStatus
DefaultFetch<Impl>::updateFetchStatus()
{
//Check Running
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == Squashing ||
fetchStatus[tid] == IcacheAccessComplete) {
if (_status == Inactive) {
DPRINTF(Activity, "[tid:%i]: Activating stage.\n",tid);
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Activity, "[tid:%i]: Activating fetch due to cache"
"completion\n",tid);
}
cpu->activateStage(O3CPU::FetchIdx);
}
return Active;
}
}
// Stage is switching from active to inactive, notify CPU of it.
if (_status == Active) {
DPRINTF(Activity, "Deactivating stage.\n");
cpu->deactivateStage(O3CPU::FetchIdx);
}
return Inactive;
}
template <class Impl>
void
DefaultFetch<Impl>::squash(const TheISA::PCState &newPC,
const InstSeqNum seq_num, DynInstPtr squashInst,
ThreadID tid)
{
DPRINTF(Fetch, "[tid:%u]: Squash from commit.\n", tid);
doSquash(newPC, squashInst, tid);
// Tell the CPU to remove any instructions that are not in the ROB.
cpu->removeInstsNotInROB(tid);
}
template <class Impl>
void
DefaultFetch<Impl>::tick()
{
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
bool status_change = false;
wroteToTimeBuffer = false;
for (ThreadID i = 0; i < numThreads; ++i) {
issuePipelinedIfetch[i] = false;
}
while (threads != end) {
ThreadID tid = *threads++;
// Check the signals for each thread to determine the proper status
// for each thread.
bool updated_status = checkSignalsAndUpdate(tid);
status_change = status_change || updated_status;
}
DPRINTF(Fetch, "Running stage.\n");
if (FullSystem) {
if (fromCommit->commitInfo[0].interruptPending) {
interruptPending = true;
}
if (fromCommit->commitInfo[0].clearInterrupt) {
interruptPending = false;
}
}
for (threadFetched = 0; threadFetched < numFetchingThreads;
threadFetched++) {
// Fetch each of the actively fetching threads.
fetch(status_change);
}
// Record number of instructions fetched this cycle for distribution.
fetchNisnDist.sample(numInst);
if (status_change) {
// Change the fetch stage status if there was a status change.
_status = updateFetchStatus();
}
// Issue the next I-cache request if possible.
for (ThreadID i = 0; i < numThreads; ++i) {
if (issuePipelinedIfetch[i]) {
pipelineIcacheAccesses(i);
}
}
// Send instructions enqueued into the fetch queue to decode.
// Limit rate by fetchWidth. Stall if decode is stalled.
unsigned insts_to_decode = 0;
unsigned available_insts = 0;
for (auto tid : *activeThreads) {
if (!stalls[tid].decode) {
available_insts += fetchQueue[tid].size();
}
}
// Pick a random thread to start trying to grab instructions from
auto tid_itr = activeThreads->begin();
std::advance(tid_itr, random_mt.random<uint8_t>(0, activeThreads->size() - 1));
while (available_insts != 0 && insts_to_decode < decodeWidth) {
ThreadID tid = *tid_itr;
if (!stalls[tid].decode && !fetchQueue[tid].empty()) {
auto inst = fetchQueue[tid].front();
toDecode->insts[toDecode->size++] = inst;
DPRINTF(Fetch, "[tid:%i][sn:%i]: Sending instruction to decode from "
"fetch queue. Fetch queue size: %i.\n",
tid, inst->seqNum, fetchQueue[tid].size());
wroteToTimeBuffer = true;
fetchQueue[tid].pop_front();
insts_to_decode++;
available_insts--;
}
tid_itr++;
// Wrap around if at end of active threads list
if (tid_itr == activeThreads->end())
tid_itr = activeThreads->begin();
}
// If there was activity this cycle, inform the CPU of it.
if (wroteToTimeBuffer) {
DPRINTF(Activity, "Activity this cycle.\n");
cpu->activityThisCycle();
}
// Reset the number of the instruction we've fetched.
numInst = 0;
}
template <class Impl>
bool
DefaultFetch<Impl>::checkSignalsAndUpdate(ThreadID tid)
{
// Update the per thread stall statuses.
if (fromDecode->decodeBlock[tid]) {
stalls[tid].decode = true;
}
if (fromDecode->decodeUnblock[tid]) {
assert(stalls[tid].decode);
assert(!fromDecode->decodeBlock[tid]);
stalls[tid].decode = false;
}
// Check squash signals from commit.
if (fromCommit->commitInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from commit.\n",tid);
// In any case, squash.
squash(fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].squashInst, tid);
// If it was a branch mispredict on a control instruction, update the
// branch predictor with that instruction, otherwise just kill the
// invalid state we generated in after sequence number
if (fromCommit->commitInfo[tid].mispredictInst &&
fromCommit->commitInfo[tid].mispredictInst->isControl()) {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
fromCommit->commitInfo[tid].pc,
fromCommit->commitInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromCommit->commitInfo[tid].doneSeqNum,
tid);
}
return true;
} else if (fromCommit->commitInfo[tid].doneSeqNum) {
// Update the branch predictor if it wasn't a squashed instruction
// that was broadcasted.
branchPred->update(fromCommit->commitInfo[tid].doneSeqNum, tid);
}
// Check squash signals from decode.
if (fromDecode->decodeInfo[tid].squash) {
DPRINTF(Fetch, "[tid:%u]: Squashing instructions due to squash "
"from decode.\n",tid);
// Update the branch predictor.
if (fromDecode->decodeInfo[tid].branchMispredict) {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].branchTaken,
tid);
} else {
branchPred->squash(fromDecode->decodeInfo[tid].doneSeqNum,
tid);
}
if (fetchStatus[tid] != Squashing) {
DPRINTF(Fetch, "Squashing from decode with PC = %s\n",
fromDecode->decodeInfo[tid].nextPC);
// Squash unless we're already squashing
squashFromDecode(fromDecode->decodeInfo[tid].nextPC,
fromDecode->decodeInfo[tid].squashInst,
fromDecode->decodeInfo[tid].doneSeqNum,
tid);
return true;
}
}
if (checkStall(tid) &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != QuiescePending) {
DPRINTF(Fetch, "[tid:%i]: Setting to blocked\n",tid);
fetchStatus[tid] = Blocked;
return true;
}
if (fetchStatus[tid] == Blocked ||
fetchStatus[tid] == Squashing) {
// Switch status to running if fetch isn't being told to block or
// squash this cycle.
DPRINTF(Fetch, "[tid:%i]: Done squashing, switching to running.\n",
tid);
fetchStatus[tid] = Running;
return true;
}
// If we've reached this point, we have not gotten any signals that
// cause fetch to change its status. Fetch remains the same as before.
return false;
}
template<class Impl>
typename Impl::DynInstPtr
DefaultFetch<Impl>::buildInst(ThreadID tid, StaticInstPtr staticInst,
StaticInstPtr curMacroop, TheISA::PCState thisPC,
TheISA::PCState nextPC, bool trace)
{
// Get a sequence number.
InstSeqNum seq = cpu->getAndIncrementInstSeq();
// Create a new DynInst from the instruction fetched.
DynInstPtr instruction =
new DynInst(staticInst, curMacroop, thisPC, nextPC, seq, cpu);
instruction->setTid(tid);
instruction->setASID(tid);
instruction->setThreadState(cpu->thread[tid]);
DPRINTF(Fetch, "[tid:%i]: Instruction PC %#x (%d) created "
"[sn:%lli].\n", tid, thisPC.instAddr(),
thisPC.microPC(), seq);
DPRINTF(Fetch, "[tid:%i]: Instruction is: %s\n", tid,
instruction->staticInst->
disassemble(thisPC.instAddr()));
#if TRACING_ON
if (trace) {
instruction->traceData =
cpu->getTracer()->getInstRecord(curTick(), cpu->tcBase(tid),
instruction->staticInst, thisPC, curMacroop);
}
#else
instruction->traceData = NULL;
#endif
// Add instruction to the CPU's list of instructions.
instruction->setInstListIt(cpu->addInst(instruction));
// Write the instruction to the first slot in the queue
// that heads to decode.
assert(numInst < fetchWidth);
fetchQueue[tid].push_back(instruction);
assert(fetchQueue[tid].size() <= fetchQueueSize);
DPRINTF(Fetch, "[tid:%i]: Fetch queue entry created (%i/%i).\n",
tid, fetchQueue[tid].size(), fetchQueueSize);
//toDecode->insts[toDecode->size++] = instruction;
// Keep track of if we can take an interrupt at this boundary
delayedCommit[tid] = instruction->isDelayedCommit();
return instruction;
}
template<class Impl>
void
DefaultFetch<Impl>::fetch(bool &status_change)
{
//////////////////////////////////////////
// Start actual fetch
//////////////////////////////////////////
ThreadID tid = getFetchingThread(fetchPolicy);
assert(!cpu->switchedOut());
if (tid == InvalidThreadID) {
// Breaks looping condition in tick()
threadFetched = numFetchingThreads;
if (numThreads == 1) { // @todo Per-thread stats
profileStall(0);
}
return;
}
DPRINTF(Fetch, "Attempting to fetch from [tid:%i]\n", tid);
// The current PC.
TheISA::PCState thisPC = pc[tid];
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
bool inRom = isRomMicroPC(thisPC.microPC());
// If returning from the delay of a cache miss, then update the status
// to running, otherwise do the cache access. Possibly move this up
// to tick() function.
if (fetchStatus[tid] == IcacheAccessComplete) {
DPRINTF(Fetch, "[tid:%i]: Icache miss is complete.\n", tid);
fetchStatus[tid] = Running;
status_change = true;
} else if (fetchStatus[tid] == Running) {
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block, AND we have no remaining ucode
// from a macro-op, then start fetch from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])
&& !inRom && !macroop[tid]) {
DPRINTF(Fetch, "[tid:%i]: Attempting to translate and read "
"instruction, starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
if (fetchStatus[tid] == IcacheWaitResponse)
++icacheStallCycles;
else if (fetchStatus[tid] == ItlbWait)
++fetchTlbCycles;
else
++fetchMiscStallCycles;
return;
} else if ((checkInterrupt(thisPC.instAddr()) && !delayedCommit[tid])) {
// Stall CPU if an interrupt is posted and we're not issuing
// an delayed commit micro-op currently (delayed commit instructions
// are not interruptable by interrupts, only faults)
++fetchMiscStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is stalled!\n", tid);
return;
}
} else {
if (fetchStatus[tid] == Idle) {
++fetchIdleCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is idle!\n", tid);
}
// Status is Idle, so fetch should do nothing.
return;
}
++fetchCycles;
TheISA::PCState nextPC = thisPC;
StaticInstPtr staticInst = NULL;
StaticInstPtr curMacroop = macroop[tid];
// If the read of the first instruction was successful, then grab the
// instructions from the rest of the cache line and put them into the
// queue heading to decode.
DPRINTF(Fetch, "[tid:%i]: Adding instructions to queue to "
"decode.\n", tid);
// Need to keep track of whether or not a predicted branch
// ended this fetch block.
bool predictedBranch = false;
// Need to halt fetch if quiesce instruction detected
bool quiesce = false;
TheISA::MachInst *cacheInsts =
reinterpret_cast<TheISA::MachInst *>(fetchBuffer[tid]);
const unsigned numInsts = fetchBufferSize / instSize;
unsigned blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
// Loop through instruction memory from the cache.
// Keep issuing while fetchWidth is available and branch is not
// predicted taken
while (numInst < fetchWidth && fetchQueue[tid].size() < fetchQueueSize
&& !predictedBranch && !quiesce) {
// We need to process more memory if we aren't going to get a
// StaticInst from the rom, the current macroop, or what's already
// in the decoder.
bool needMem = !inRom && !curMacroop &&
!decoder[tid]->instReady();
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
if (needMem) {
// If buffer is no longer valid or fetchAddr has moved to point
// to the next cache block then start fetch from icache.
if (!fetchBufferValid[tid] ||
fetchBufferBlockPC != fetchBufferPC[tid])
break;
if (blkOffset >= numInsts) {
// We need to process more memory, but we've run out of the
// current block.
break;
}
if (ISA_HAS_DELAY_SLOT && pcOffset == 0) {
// Walk past any annulled delay slot instructions.
Addr pcAddr = thisPC.instAddr() & BaseCPU::PCMask;
while (fetchAddr != pcAddr && blkOffset < numInsts) {
blkOffset++;
fetchAddr += instSize;
}
if (blkOffset >= numInsts)
break;
}
MachInst inst = TheISA::gtoh(cacheInsts[blkOffset]);
decoder[tid]->moreBytes(thisPC, fetchAddr, inst);
if (decoder[tid]->needMoreBytes()) {
blkOffset++;
fetchAddr += instSize;
pcOffset += instSize;
}
}
// Extract as many instructions and/or microops as we can from
// the memory we've processed so far.
do {
if (!(curMacroop || inRom)) {
if (decoder[tid]->instReady()) {
staticInst = decoder[tid]->decode(thisPC);
// Increment stat of fetched instructions.
++fetchedInsts;
if (staticInst->isMacroop()) {
curMacroop = staticInst;
} else {
pcOffset = 0;
}
} else {
// We need more bytes for this instruction so blkOffset and
// pcOffset will be updated
break;
}
}
// Whether we're moving to a new macroop because we're at the
// end of the current one, or the branch predictor incorrectly
// thinks we are...
bool newMacro = false;
if (curMacroop || inRom) {
if (inRom) {
staticInst = cpu->microcodeRom.fetchMicroop(
thisPC.microPC(), curMacroop);
} else {
staticInst = curMacroop->fetchMicroop(thisPC.microPC());
}
newMacro |= staticInst->isLastMicroop();
}
DynInstPtr instruction =
buildInst(tid, staticInst, curMacroop,
thisPC, nextPC, true);
ppFetch->notify(instruction);
numInst++;
#if TRACING_ON
if (DTRACE(O3PipeView)) {
instruction->fetchTick = curTick();
}
#endif
nextPC = thisPC;
// If we're branching after this instruction, quit fetching
// from the same block.
predictedBranch |= thisPC.branching();
predictedBranch |=
lookupAndUpdateNextPC(instruction, nextPC);
if (predictedBranch) {
DPRINTF(Fetch, "Branch detected with PC = %s\n", thisPC);
}
newMacro |= thisPC.instAddr() != nextPC.instAddr();
// Move to the next instruction, unless we have a branch.
thisPC = nextPC;
inRom = isRomMicroPC(thisPC.microPC());
if (newMacro) {
fetchAddr = thisPC.instAddr() & BaseCPU::PCMask;
blkOffset = (fetchAddr - fetchBufferPC[tid]) / instSize;
pcOffset = 0;
curMacroop = NULL;
}
if (instruction->isQuiesce()) {
DPRINTF(Fetch,
"Quiesce instruction encountered, halting fetch!\n");
fetchStatus[tid] = QuiescePending;
status_change = true;
quiesce = true;
break;
}
} while ((curMacroop || decoder[tid]->instReady()) &&
numInst < fetchWidth &&
fetchQueue[tid].size() < fetchQueueSize);
// Re-evaluate whether the next instruction to fetch is in micro-op ROM
// or not.
inRom = isRomMicroPC(thisPC.microPC());
}
if (predictedBranch) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, predicted branch "
"instruction encountered.\n", tid);
} else if (numInst >= fetchWidth) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached fetch bandwidth "
"for this cycle.\n", tid);
} else if (blkOffset >= fetchBufferSize) {
DPRINTF(Fetch, "[tid:%i]: Done fetching, reached the end of the"
"fetch buffer.\n", tid);
}
macroop[tid] = curMacroop;
fetchOffset[tid] = pcOffset;
if (numInst > 0) {
wroteToTimeBuffer = true;
}
pc[tid] = thisPC;
// pipeline a fetch if we're crossing a fetch buffer boundary and not in
// a state that would preclude fetching
fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
issuePipelinedIfetch[tid] = fetchBufferBlockPC != fetchBufferPC[tid] &&
fetchStatus[tid] != IcacheWaitResponse &&
fetchStatus[tid] != ItlbWait &&
fetchStatus[tid] != IcacheWaitRetry &&
fetchStatus[tid] != QuiescePending &&
!curMacroop;
}
template<class Impl>
void
DefaultFetch<Impl>::recvReqRetry()
{
if (retryPkt != NULL) {
assert(cacheBlocked);
assert(retryTid != InvalidThreadID);
assert(fetchStatus[retryTid] == IcacheWaitRetry);
if (cpu->getInstPort().sendTimingReq(retryPkt)) {
fetchStatus[retryTid] = IcacheWaitResponse;
// Notify Fetch Request probe when a retryPkt is successfully sent.
// Note that notify must be called before retryPkt is set to NULL.
ppFetchRequestSent->notify(retryPkt->req);
retryPkt = NULL;
retryTid = InvalidThreadID;
cacheBlocked = false;
}
} else {
assert(retryTid == InvalidThreadID);
// Access has been squashed since it was sent out. Just clear
// the cache being blocked.
cacheBlocked = false;
}
}
///////////////////////////////////////
// //
// SMT FETCH POLICY MAINTAINED HERE //
// //
///////////////////////////////////////
template<class Impl>
ThreadID
DefaultFetch<Impl>::getFetchingThread(FetchPriority &fetch_priority)
{
if (numThreads > 1) {
switch (fetch_priority) {
case SingleThread:
return 0;
case RoundRobin:
return roundRobin();
case IQ:
return iqCount();
case LSQ:
return lsqCount();
case Branch:
return branchCount();
default:
return InvalidThreadID;
}
} else {
list<ThreadID>::iterator thread = activeThreads->begin();
if (thread == activeThreads->end()) {
return InvalidThreadID;
}
ThreadID tid = *thread;
if (fetchStatus[tid] == Running ||
fetchStatus[tid] == IcacheAccessComplete ||
fetchStatus[tid] == Idle) {
return tid;
} else {
return InvalidThreadID;
}
}
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::roundRobin()
{
list<ThreadID>::iterator pri_iter = priorityList.begin();
list<ThreadID>::iterator end = priorityList.end();
ThreadID high_pri;
while (pri_iter != end) {
high_pri = *pri_iter;
assert(high_pri <= numThreads);
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle) {
priorityList.erase(pri_iter);
priorityList.push_back(high_pri);
return high_pri;
}
pri_iter++;
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::iqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned iqCount = fromIEW->iewInfo[tid].iqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(iqCount);
threadMap[iqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::lsqCount()
{
//sorted from lowest->highest
std::priority_queue<unsigned,vector<unsigned>,
std::greater<unsigned> > PQ;
std::map<unsigned, ThreadID> threadMap;
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
unsigned ldstqCount = fromIEW->iewInfo[tid].ldstqCount;
//we can potentially get tid collisions if two threads
//have the same iqCount, but this should be rare.
PQ.push(ldstqCount);
threadMap[ldstqCount] = tid;
}
while (!PQ.empty()) {
ThreadID high_pri = threadMap[PQ.top()];
if (fetchStatus[high_pri] == Running ||
fetchStatus[high_pri] == IcacheAccessComplete ||
fetchStatus[high_pri] == Idle)
return high_pri;
else
PQ.pop();
}
return InvalidThreadID;
}
template<class Impl>
ThreadID
DefaultFetch<Impl>::branchCount()
{
#if 0
list<ThreadID>::iterator thread = activeThreads->begin();
assert(thread != activeThreads->end());
ThreadID tid = *thread;
#endif
panic("Branch Count Fetch policy unimplemented\n");
return InvalidThreadID;
}
template<class Impl>
void
DefaultFetch<Impl>::pipelineIcacheAccesses(ThreadID tid)
{
if (!issuePipelinedIfetch[tid]) {
return;
}
// The next PC to access.
TheISA::PCState thisPC = pc[tid];
if (isRomMicroPC(thisPC.microPC())) {
return;
}
Addr pcOffset = fetchOffset[tid];
Addr fetchAddr = (thisPC.instAddr() + pcOffset) & BaseCPU::PCMask;
// Align the fetch PC so its at the start of a fetch buffer segment.
Addr fetchBufferBlockPC = fetchBufferAlignPC(fetchAddr);
// Unless buffer already got the block, fetch it from icache.
if (!(fetchBufferValid[tid] && fetchBufferBlockPC == fetchBufferPC[tid])) {
DPRINTF(Fetch, "[tid:%i]: Issuing a pipelined I-cache access, "
"starting at PC %s.\n", tid, thisPC);
fetchCacheLine(fetchAddr, tid, thisPC.instAddr());
}
}
template<class Impl>
void
DefaultFetch<Impl>::profileStall(ThreadID tid) {
DPRINTF(Fetch,"There are no more threads available to fetch from.\n");
// @todo Per-thread stats
if (stalls[tid].drain) {
++fetchPendingDrainCycles;
DPRINTF(Fetch, "Fetch is waiting for a drain!\n");
} else if (activeThreads->empty()) {
++fetchNoActiveThreadStallCycles;
DPRINTF(Fetch, "Fetch has no active thread!\n");
} else if (fetchStatus[tid] == Blocked) {
++fetchBlockedCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is blocked!\n", tid);
} else if (fetchStatus[tid] == Squashing) {
++fetchSquashCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is squashing!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitResponse) {
++icacheStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting cache response!\n",
tid);
} else if (fetchStatus[tid] == ItlbWait) {
++fetchTlbCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting ITLB walk to "
"finish!\n", tid);
} else if (fetchStatus[tid] == TrapPending) {
++fetchPendingTrapStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending trap!\n",
tid);
} else if (fetchStatus[tid] == QuiescePending) {
++fetchPendingQuiesceStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for a pending quiesce "
"instruction!\n", tid);
} else if (fetchStatus[tid] == IcacheWaitRetry) {
++fetchIcacheWaitRetryStallCycles;
DPRINTF(Fetch, "[tid:%i]: Fetch is waiting for an I-cache retry!\n",
tid);
} else if (fetchStatus[tid] == NoGoodAddr) {
DPRINTF(Fetch, "[tid:%i]: Fetch predicted non-executable address\n",
tid);
} else {
DPRINTF(Fetch, "[tid:%i]: Unexpected fetch stall reason (Status: %i).\n",
tid, fetchStatus[tid]);
}
}
#endif//__CPU_O3_FETCH_IMPL_HH__
| bsd-3-clause |
BreemsEmporiumMensToiletriesFragrances/webgl-fundamentals | webgl/lessons/webgl-shaders-and-glsl.md | 14178 | Title: WebGL Shaders and GLSL
Description: What's a shader and what's GLSL
This is a continuation from [WebGL Fundamentals](webgl-fundamentals.html).
If you haven't read about how WebGL works you might want to [read this first](webgl-how-it-works.html).
We've talked about shaders and GLSL but haven't really given them any specific details.
I think I was hoping it would be clear by example but let's try to make it clearer just in case.
As mentioned in [how it works](webgl-how-it-works.html) WebGL requires 2 shaders everytime you
draw something. A *vertex shader* and a *fragment shader*. Each shader is a *function*. A vertex
shader and fragment shader are linked together into a shader program (or just program). A typical
WebGL app will have many shader programs.
## Vertex Shader
A Vertex Shader's job is to generate clipspace coordinates. It always takes the form
void main() {
gl_Position = doMathToMakeClipspaceCoordinates
}
Your shader is called once per vertex. Each time it's called you are required to set the
the special global variable, `gl_Position` to some clipspace coordinates.
Vertex shaders need data. They can get that data in 3 ways.
1. [Attributes](#attributes) (data pulled from buffers)
2. [Uniforms](#uniforms) (values that stay the same during for all vertices of a single draw call)
3. [Textures](#textures-in-vertex-shaders) (data from pixels/texels)
### Attributes
The most common way is through buffers and *attributes*.
[How it works](webgl-how-it-works.html) covered buffers and
attributes. You create buffers,
var buf = gl.createBuffer();
put data in those buffers
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, someData, gl.STATIC_DRAW);
Then, given a shader program you made you look up the location of its attributes,
var positionLoc = gl.getAttribLocation(someShaderProgram, "a_position");
then tell WebGL how to pull data out of those buffers and into the attribute
// turn on getting data out of a buffer for this attribute
gl.enableVertexAttribArray(positionLoc);
var numComponents = 3; // (x, y, z)
var type = gl.FLOAT;
var normalize = false; // leave the values as they are
var offset = 0; // start at the beginning of the buffer
var stride = 0; // how many bytes to move to the next vertex
// 0 = use the correct stride for type and numComponents
gl.vertexAttribPointer(positionLoc, numComponents, type, false, stride, offset);
In [webgl fundamentals](webgl-fundamentals.html) we showed that we can do no math
in the shader and just pass the data directly through.
attribute vec4 a_position;
void main() {
gl_Position = a_position;
}
If we put clipsapce vertices into our buffers it will work.
Attributes can use `float`, `vec2`, `vec3`, `vec4`, `mat2`, `mat3`, and `mat4` as types.
### Uniforms
For a vertex shader uniforms are values passed to the vertex shader that stay the same
for all vertices in a draw call. As a very simple example we could add an offset to
the vertex shader above
attribute vec4 a_position;
+uniform vec4 u_offset;
void main() {
gl_Position = a_position + u_offset;
}
And now we could offset every vertex by a certain amount. First we'd look up the
location of the uniform
var offsetLoc = gl.getUniformLocation(someProgram, "u_offset");
And then before drawing we'd set the uniform
gl.uniform4fv(offsetLoc, [1, 0, 0, 0]); // offset it to the right half the screen
Uniforms can be many types. For each type you have to call the corresponding function to set it.
gl.uniform1f (floatUniformLoc, v); // for float
gl.uniform1fv(floatUniformLoc, [v]); // for float or float array
gl.uniform2f (vec2UniformLoc, v0, v1); // for vec2
gl.uniform2fv(vec2UniformLoc, [v0, v1]); // for vec2 or vec2 array
gl.uniform3f (vec3UniformLoc, v0, v1, v2); // for vec3
gl.uniform3fv(vec3UniformLoc, [v0, v1, v2]); // for vec3 or vec3 array
gl.uniform4f (vec4UniformLoc, v0, v1, v2, v4); // for vec4
gl.uniform4fv(vec4UniformLoc, [v0, v1, v2, v4]); // for vec4 or vec4 array
gl.uniformMatrix2fv(mat2UniformLoc, false, [ 4x element array ]) // for mat2 or mat2 array
gl.uniformMatrix3fv(mat3UniformLoc, false, [ 9x element array ]) // for mat3 or mat3 array
gl.uniformMatrix4fv(mat4UniformLoc, false, [ 16x element array ]) // for mat4 or mat4 array
gl.uniform1i (intUniformLoc, v); // for int
gl.uniform1iv(intUniformLoc, [v]); // for int or int array
gl.uniform2i (ivec2UniformLoc, v0, v1); // for ivec2
gl.uniform2iv(ivec2UniformLoc, [v0, v1]); // for ivec2 or ivec2 array
gl.uniform3i (ivec3UniformLoc, v0, v1, v2); // for ivec3
gl.uniform3iv(ivec3UniformLoc, [v0, v1, v2]); // for ivec3 or ivec3 array
gl.uniform4i (ivec4UniformLoc, v0, v1, v2, v4); // for ivec4
gl.uniform4iv(ivec4UniformLoc, [v0, v1, v2, v4]); // for ivec4 or ivec4 array
gl.uniform1i (sampler2DUniformLoc, v); // for sampler2D (textures)
gl.uniform1iv(sampler2DUniformLoc, [v]); // for sampler2D or sampler2D array
gl.uniform1i (samplerCubeUniformLoc, v); // for samplerCube (textures)
gl.uniform1iv(samplerCubeUniformLoc, [v]); // for samplerCube or samplerCube array
There's also types `bool`, `bvec2`, `bvec3`, and `bvec4`. They use either the `gl.uniform?f?` or `gl.uniform?i?`
functions.
Note that for an array you can set all the uniforms of the array at once. For example
// in shader
uniform vec2 u_someVec2[3];
// in JavaScript at init time
var someVec2Loc = gl.getUniformLocation(someProgram, "u_someVec2");
// at render time
gl.uniform2fv(someVec2Loc, [1, 2, 3, 4, 5, 6]); // set the entire array of u_someVec3
But if you want to set individual elements of the array you must look up the location of
each element individually.
// in JavaScript at init time
var someVec2Element0Loc = gl.getUniformLocation(someProgram, "u_someVec2[0]");
var someVec2Element1Loc = gl.getUniformLocation(someProgram, "u_someVec2[1]");
var someVec2Element2Loc = gl.getUniformLocation(someProgram, "u_someVec2[2]");
// at render time
gl.uniform2fv(someVec2Element0Loc, [1, 2]); // set element 0
gl.uniform2fv(someVec2Element1Loc, [3, 4]); // set element 1
gl.uniform2fv(someVec2Element2Loc, [5, 6]); // set element 2
Similarly if you create a struct
struct SomeStruct {
bool active;
vec2 someVec2;
};
uniform SomeStruct u_someThing;
you have to look up each field individually
var someThingActiveLoc = gl.getUniformLocation(someProgram, "u_someThing.active");
var someThingSomeVec2Loc = gl.getUniformLocation(someProgram, "u_someThing.someVec2");
### Textures in Vertex Shaders
See [Textures in Fragment Shaders](#textures-in-fragment-shaders).
## Fragment Shader
A Fragment Shader's job is to provide a color for the current pixel being rasterized.
It always takes the form
precision mediump float;
void main() {
gl_FragColor = doMathToMakeAColor;
}
Your fragment shader is called one per pixel. Each time it's called you are required
to set the special global variable, `gl_FragColor` to some color.
Fragment shaders need data. They can get data in 3 ways
1. [Uniforms](#uniforms) (values that stay the same for every pixel of a single draw call)
2. [Textures](#textures-in-fragment-shaders) (data from pixels/texels)
3. [Varyings](#varyings) (data passed from the vertex shader and interpolated)
### Uniforms in Fragment Shaders
See [Uniforms in Vertex Shaders](#uniforms).
### Textures in Fragment Shaders
Getting a value from a texture in a shader we create a `sampler2D` uniform and use the GLSL
function `texture2D` to extract a value from it.
precision mediump float;
uniform sampler2D u_texture;
void main() {
vec2 texcoord = vec2(0.5, 0.5) // get a value from the middle of the texture
gl_FragColor = texture2D(u_texture, texcoord);
}
What data comes out of the texture is [dependent on many settings](webgl-3d-textures.html).
At a minimum we need to create and put data in the texture, for example
var tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
var level = 0;
var width = 2;
var height = 1;
var data = new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255]);
gl.texImage2D(gl.TEXTURE_2D, level, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
Then look up the uniform location in the shader program
var someSamplerLoc = gl.getUniformLocation(someProgram, "u_texture");
WebGL then requires you to bind it to a texture unit
var unit = 5; // Pick some texture unit
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, tex);
And tell the shader which unit you bound the texture to
gl.uniform1i(someSamplerLoc, unit);
### Varyings
A varying is a way to pass a value from a vertex shader to a fragment shader which we
covered in [how it works](webgl-how-it-works.html).
To use a varying we need to declare matching varyings in both a vertex and fragment shaders.
We set the varying in the vertex shader with some value per vertex. When WebGL draws pixels
it will interpolate between those values and pass them to the corresponding varying in
the fragment shaders
Vertex shader
attribute vec4 a_position;
uniform vec4 u_offset;
+varying vec4 v_positionWithOffset;
void main() {
gl_Position = a_position + u_offset;
+ v_positionWithOffset = a_position + u_offset;
}
Fragment shader
precision mediump float;
+varying vec4 v_positionWithOffset;
void main() {
+ // convert from clipsapce (-1 <-> +1) to color space (0 -> 1).
+ vec4 color = v_positionWithOffset * 0.5 + 0.5
+ gl_FragColor = color;
}
The example above is a mostly nonsense example. It doesn't generally make sense to
directly copy the clipsapce values the fragment shader and use them as colors. Never the less
it will work and produce colors.
## GLSL
GLSL stands for Graphics Library Shader Language. It's the language shaders are written
in. It has some special semi unique features that are certainly not common in JavaScript.
It's designed to do the math that is commonly needed to compute things for rasterizing
graphics. So for example it has built in types like `vec2`, `vec3`, and `vec4` which
represent 2 values, 3 values, and 4 values respectively. Similarly it has `mat2`, `mat3`
and `mat4` which represent 2x2, 3x3, and 4x4 matrices. You can do things like multiply
a `vec` by a scalar.
vec4 a = vec4(1, 2, 3, 4);
vec4 b = a * 2.0;
// b is now vec4(2, 4, 6, 8);
Similarly it can do matrix multiplication and vector to matrix multiplication
mat4 a = ???
mat4 b = ???
mat4 c = a * b;
vec4 v = ???
vec4 y = c * v;
It also has various selectors for the parts of a vec. For a vec4
vec4 v;
* `v.x` is the same as `v.s` and `v.r` and `v[0]`.
* `v.y` is the same as `v.t` and `v.g` and `v[1]`.
* `v.z` is the same as `v.p` and `v.b` and `v[2]`.
* `v.w` is the same as `v.q` and `v.a` and `v[3]`.
It it able to *swizzle* vec components which means you can swap or repeat components.
v.yyyy
is the same as
vec4(v.y, v.y, v.y, v.y)
Similarly
v.bgra
is the same as
vec4(v.b, v.g, v.r, v.a)
when constructing a vec or a mat you can supply multiple parts at once. So for example
vec4(v.rgb, 1)
Is the same as
vec4(v.r, v.g, v.b, 1)
One thing you'll likely get caught up on is that GLSL is very type strict.
float f = 1; // ERROR 1 is an int. You can't assign an int to a float
The correct way is one of these
float f = 1.0; // use float
float f = float(1) // cast the integer to a float
The example above of `vec4(v.rgb, 1)` doesn't complain about the `1` because `vec4` is
casting the things inside just like `float(1)`.
GLSL as a bunch of built in functions. Many of them operate on multiple components at once.
So for example
T sin(T angle)
Means T can be `float`, `vec2`, `vec3` or `vec4`. If you pass in `vec4` you get `vec4` back
which the sine of each of the components. In other words given if `v` is a `vec4` then
vec4 s = sin(v);
is the same as
vec4 s = vec4(sin(v.x), sin(v.y), sin(v.z), sin(v.w));
Sometimes one argument is a float and the rest is `T`. That means that float will be applied
to all the components. For example if `v1` and `v2` are `vec4` and `f` is a float then
vec4 m = mix(v1, v2, f);
is the same as
vec4 m = vec4(
mix(v1.x, v2.x, f),
mix(v1.y, v2.y, f),
mix(v1.z, v2.z, f),
mix(v1.w, v2.w, f));
You can see list of all the GLSL functions on the last page of [the WebGL
Reference Card](https://www.khronos.org/files/webgl/webgl-reference-card-1_0.pdf).
If you like really dry and verbose stuff you can try
[the GLSL spec](https://www.khronos.org/files/opengles_shading_language.pdf).
## Putting it all togehter
That's the point of this entire series of posts. WebGL is all about creating various shaders, supplying
the data to those shaders and then calling `gl.drawArrays` or `gl.drawElements` to have WebGL process
the vertices by calling the current vertex shader for each vertex and then render pixels by calling the
the current fragment shader for each pixel.
Actually creating the shaders requires several lines of code. Since those lines are the same in
most WebGL programs and since once written you can pretty much ignore them [how to compile GLSL shaders
and link them into a shader program is covered here](webgl-boilerplate.html).
If you're just starting from here you can go in 2 directions. If you are interested in image procesing
I'll show you [how to do some 2D image processing](webgl-image-processing.html).
If you are interesting in learning about translation,
rotation and scale then [start here](webgl-2d-translation.html).
| bsd-3-clause |
bxshi/gem5 | src/sim/sim_object.cc | 4656 | /*
* Copyright (c) 2001-2005 The Regents of The University of Michigan
* Copyright (c) 2010 Advanced Micro Devices, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Nathan Binkert
*/
#include <cassert>
#include "base/callback.hh"
#include "base/inifile.hh"
#include "base/match.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "debug/Checkpoint.hh"
#include "sim/probe/probe.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
using namespace std;
////////////////////////////////////////////////////////////////////////
//
// SimObject member definitions
//
////////////////////////////////////////////////////////////////////////
//
// static list of all SimObjects, used for initialization etc.
//
SimObject::SimObjectList SimObject::simObjectList;
//
// SimObject constructor: used to maintain static simObjectList
//
SimObject::SimObject(const Params *p)
: EventManager(getEventQueue(p->eventq_index)), _params(p)
{
#ifdef DEBUG
doDebugBreak = false;
#endif
simObjectList.push_back(this);
probeManager = new ProbeManager(this);
}
void
SimObject::init()
{
}
void
SimObject::loadState(Checkpoint *cp)
{
if (cp->sectionExists(name())) {
DPRINTF(Checkpoint, "unserializing\n");
unserialize(cp, name());
} else {
DPRINTF(Checkpoint, "no checkpoint section found\n");
}
}
void
SimObject::initState()
{
}
void
SimObject::startup()
{
}
//
// no default statistics, so nothing to do in base implementation
//
void
SimObject::regStats()
{
}
void
SimObject::resetStats()
{
}
/**
* No probe points by default, so do nothing in base.
*/
void
SimObject::regProbePoints()
{
}
/**
* No probe listeners by default, so do nothing in base.
*/
void
SimObject::regProbeListeners()
{
}
ProbeManager *
SimObject::getProbeManager()
{
return probeManager;
}
//
// static function: serialize all SimObjects.
//
void
SimObject::serializeAll(std::ostream &os)
{
SimObjectList::reverse_iterator ri = simObjectList.rbegin();
SimObjectList::reverse_iterator rend = simObjectList.rend();
for (; ri != rend; ++ri) {
SimObject *obj = *ri;
obj->nameOut(os);
obj->serialize(os);
}
}
#ifdef DEBUG
//
// static function: flag which objects should have the debugger break
//
void
SimObject::debugObjectBreak(const string &objs)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
ObjectMatch match(objs);
for (; i != end; ++i) {
SimObject *obj = *i;
obj->doDebugBreak = match.match(obj->name());
}
}
void
debugObjectBreak(const char *objs)
{
SimObject::debugObjectBreak(string(objs));
}
#endif
unsigned int
SimObject::drain(DrainManager *drain_manager)
{
setDrainState(Drained);
return 0;
}
SimObject *
SimObject::find(const char *name)
{
SimObjectList::const_iterator i = simObjectList.begin();
SimObjectList::const_iterator end = simObjectList.end();
for (; i != end; ++i) {
SimObject *obj = *i;
if (obj->name() == name)
return obj;
}
return NULL;
}
| bsd-3-clause |
hucongyang/yii | vendor/kartik-v/yii2-grid/GridExportAsset.php | 631 | <?php
/**
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.8
*/
namespace kartik\grid;
use kartik\base\AssetBundle;
/**
* Asset bundle for GridView Widget (for exporting content)
*
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @since 1.0
*/
class GridExportAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public function init()
{
$this->setSourcePath(__DIR__ . '/assets');
$this->setupAssets('js', ['js/kv-grid-export']);
parent::init();
}
}
| bsd-3-clause |
lilothar/walle-c11 | walle/sys/Filesystem.cpp | 5052 | #include <walle/sys/wallesys.h>
using namespace std;
/// Web Application Library namaspace
namespace walle {
namespace sys {
bool Filesystem::fileExist( const string &file ) {
if ( ::access(file.c_str(),F_OK) == 0 )
return true;
else
return false;
}
bool Filesystem::isLink( const string &file ) {
struct stat statbuf;
if( ::lstat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISLNK(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::isDir( const string &file ) {
struct stat statbuf;
if( ::stat(file.c_str(),&statbuf) == 0 ) {
if ( S_ISDIR(statbuf.st_mode) != 0 )
return true;
}
return false;
}
bool Filesystem::mkLink( const string &srcfile, const string &destfile ) {
if ( ::symlink(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::link(const string &srcfile, const string &destfile)
{
if ( ::link(srcfile.c_str(),destfile.c_str()) == 0 )
return true;
else
return false;
}
size_t Filesystem::fileSize( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_size;
else
return -1;
}
time_t Filesystem::fileTime( const string &file ) {
struct stat statbuf;
if( stat(file.c_str(),&statbuf)==0 )
return statbuf.st_mtime;
else
return -1;
}
string Filesystem::filePath( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( 0, p );
return string( "" );
}
string Filesystem::fileName( const string &file ) {
size_t p;
if ( (p=file.rfind("/")) != file.npos )
return file.substr( p+1 );
return file;
}
bool Filesystem::renameFile( const string &oldname, const string &newname ) {
if ( ::rename(oldname.c_str(),newname.c_str()) != -1 )
return true;
else
return false;
}
bool Filesystem::copyFile( const string &srcfile, const string &destfile ) {
FILE *src=NULL, *dest=NULL;
if ( (src=fopen(srcfile.c_str(),"rb")) == NULL ) {
return false;
}
if ( (dest=fopen(destfile.c_str(),"wb+")) == NULL ) {
fclose( src );
return false;
}
const int bufsize = 8192;
char buf[bufsize];
size_t n;
while ( (n=fread(buf,1,bufsize,src)) >= 1 ) {
if ( fwrite(buf,1,n,dest) != n ) {
fclose( src );
fclose( dest );
return false;
}
}
fclose( src );
fclose( dest );
//chmod to 0666
mode_t mask = umask( 0 );
chmod( destfile.c_str(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH );
umask( mask );
return true;
}
bool Filesystem::deleteFile( const string &file ) {
if ( ::remove(file.c_str()) == 0 )
return true;
else
return false;
}
bool Filesystem::moveFile( const string &srcfile, const string &destfile ) {
if ( renameFile(srcfile,destfile) )
return true;
// rename fail, copy and delete file
if ( copyFile(srcfile,destfile) ) {
if ( deleteFile(srcfile) )
return true;
}
return false;
}
vector<string> Filesystem::dirFiles( const string &dir ) {
vector<string> files;
string file;
DIR *pdir = NULL;
dirent *pdirent = NULL;
if ( (pdir = ::opendir(dir.c_str())) != NULL ) {
while ( (pdirent=readdir(pdir)) != NULL ) {
file = pdirent->d_name;
if ( file!="." && file!=".." ) {
if ( isDir(dir+"/"+file) )
file = "/"+file;
files.push_back( file );
}
}
::closedir( pdir );
}
return files;
}
bool Filesystem::makeDir( const string &dir, const mode_t mode ) {
// check
size_t len = dir.length();
if ( len <= 0 ) return false;
string tomake;
char curchr;
for( size_t i=0; i<len; ++i ) {
// append
curchr = dir[i];
tomake += curchr;
if ( curchr=='/' || i==(len-1) ) {
// need to mkdir
if ( !fileExist(tomake) && !isDir(tomake) ) {
// able to mkdir
mode_t mask = umask( 0 );
if ( mkdir(tomake.c_str(),mode) == -1 ) {
umask( mask );
return false;
}
umask( mask );
}
}
}
return true;
}
bool Filesystem::copyDir( const string &srcdir, const string &destdir ) {
vector<string> files = dirFiles( srcdir );
string from;
string to;
if ( !fileExist(destdir) )
makeDir( destdir );
for ( size_t i=0; i<files.size(); ++i ) {
from = srcdir + "/" + files[i];
to = destdir + "/" + files[i];
if ( files[i][0] == '/' ) {
if ( !copyDir(from,to) )
return false;
}
else if ( !copyFile(from,to) )
return false;
}
return true;
}
bool Filesystem::deleteDir( const string &dir ) {
vector<string> files = dirFiles( dir );
string todel;
// ɾ³ýÎļþ
for ( size_t i=0; i<files.size(); ++i ) {
todel = dir + "/" + files[i];
// ×ÓĿ¼,µÝ¹éµ÷ÓÃ
if ( files[i][0] == '/' ) {
if ( !deleteDir(todel) )
return false;
}
// Îļþ
else if ( !deleteFile(todel) )
return false;
}
// ɾ³ýĿ¼
if ( rmdir(dir.c_str()) == 0 )
return true;
return false;
}
bool Filesystem::moveDir( const string &srcdir, const string &destdir ) {
if ( renameFile(srcdir,destdir) )
return true;
// rename fail, copy and delete dir
if ( copyDir(srcdir,destdir) ) {
if (deleteDir(srcdir) )
return true;
}
return false;
}
}
} // namespace
| bsd-3-clause |
windyuuy/opera | chromium/src/ash/launcher/launcher_tooltip_manager.h | 3512 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_LAUNCHER_LAUNCHER_TOOLTIP_MANAGER_H_
#define ASH_LAUNCHER_LAUNCHER_TOOLTIP_MANAGER_H_
#include "ash/ash_export.h"
#include "ash/shelf/shelf_layout_manager_observer.h"
#include "ash/shelf/shelf_types.h"
#include "base/basictypes.h"
#include "base/strings/string16.h"
#include "ui/base/events/event_handler.h"
#include "ui/gfx/rect.h"
#include "ui/views/bubble/bubble_border.h"
#include "ui/views/bubble/bubble_delegate.h"
namespace base {
class Timer;
}
namespace views {
class BubbleDelegateView;
class Label;
}
namespace ash {
namespace test {
class LauncherTooltipManagerTest;
class LauncherViewTest;
}
namespace internal {
class LauncherView;
class ShelfLayoutManager;
// LauncherTooltipManager manages the tooltip balloon poping up on launcher
// items.
class ASH_EXPORT LauncherTooltipManager : public ui::EventHandler,
public ShelfLayoutManagerObserver {
public:
LauncherTooltipManager(ShelfLayoutManager* shelf_layout_manager,
LauncherView* launcher_view);
virtual ~LauncherTooltipManager();
ShelfLayoutManager* shelf_layout_manager() {
return shelf_layout_manager_;
}
// Called when the bubble is closed.
void OnBubbleClosed(views::BubbleDelegateView* view);
// Shows the tooltip after a delay. It also has the appearing animation.
void ShowDelayed(views::View* anchor, const base::string16& text);
// Shows the tooltip immediately. It omits the appearing animation.
void ShowImmediately(views::View* anchor, const base::string16& text);
// Closes the tooltip.
void Close();
// Changes the arrow location of the tooltip in case that the launcher
// arrangement has changed.
void UpdateArrow();
// Resets the timer for the delayed showing |view_|. If the timer isn't
// running, it starts a new timer.
void ResetTimer();
// Stops the timer for the delayed showing |view_|.
void StopTimer();
// Returns true if the tooltip is currently visible.
bool IsVisible();
// Create an instant timer for test purposes.
void CreateZeroDelayTimerForTest();
protected:
// ui::EventHandler overrides:
virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE;
virtual void OnTouchEvent(ui::TouchEvent* event) OVERRIDE;
virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
virtual void OnCancelMode(ui::CancelModeEvent* event) OVERRIDE;
// ShelfLayoutManagerObserver overrides:
virtual void WillDeleteShelf() OVERRIDE;
virtual void WillChangeVisibilityState(
ShelfVisibilityState new_state) OVERRIDE;
virtual void OnAutoHideStateChanged(ShelfAutoHideState new_state) OVERRIDE;
private:
class LauncherTooltipBubble;
friend class test::LauncherViewTest;
friend class test::LauncherTooltipManagerTest;
void CancelHidingAnimation();
void CloseSoon();
void ShowInternal();
void CreateBubble(views::View* anchor, const base::string16& text);
void CreateTimer(int delay_in_ms);
LauncherTooltipBubble* view_;
views::Widget* widget_;
views::View* anchor_;
base::string16 text_;
scoped_ptr<base::Timer> timer_;
ShelfLayoutManager* shelf_layout_manager_;
LauncherView* launcher_view_;
DISALLOW_COPY_AND_ASSIGN(LauncherTooltipManager);
};
} // namespace internal
} // namespace ash
#endif // ASH_LAUNCHER_LAUNCHER_TOOLTIP_MANAGER_H_
| bsd-3-clause |
chromium/chromium | third_party/blink/renderer/core/css/cssom/css_numeric_array.h | 1376 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_NUMERIC_ARRAY_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_NUMERIC_ARRAY_H_
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/cssom/css_numeric_value.h"
namespace blink {
// See CSSNumericArray.idl for more information about this class.
class CORE_EXPORT CSSNumericArray final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
explicit CSSNumericArray(CSSNumericValueVector values)
: values_(std::move(values)) {}
CSSNumericArray(const CSSNumericArray&) = delete;
CSSNumericArray& operator=(const CSSNumericArray&) = delete;
void Trace(Visitor* visitor) const override {
visitor->Trace(values_);
ScriptWrappable::Trace(visitor);
}
unsigned length() const { return values_.size(); }
CSSNumericValue* AnonymousIndexedGetter(unsigned index) {
if (index < values_.size())
return values_[index].Get();
return nullptr;
}
const CSSNumericValueVector& Values() const { return values_; }
private:
CSSNumericValueVector values_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_CSS_NUMERIC_ARRAY_H_
| bsd-3-clause |
bestrauc/seqan | tests/index/test_index_fm_stree.h | 16008 | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2016, Knut Reinert, FU Berlin
// Copyright (c) 2013 NVIDIA Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Jochen Singer <jochen.singer@fu-berlin.de>
// ==========================================================================
#ifndef TESTS_INDEX_TEST_INDEX_FM_ITER_H_
#define TESTS_INDEX_TEST_INDEX_FM_ITER_H_
using namespace seqan;
template <typename TIter>
void fmIndexIteratorConstuctor(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text;
generateText(text);
Index<TText> esa(text);
typename Iterator<Index<TText>, TopDown<> >::Type esaIt(esa);
goDown(esaIt);
TIndex fmIndex(text, 10);
TIter it(fmIndex);
SEQAN_ASSERT_EQ(isRoot(it), true);
SEQAN_ASSERT_EQ(repLength(it), 0u);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(isRoot(it), false);
SEQAN_ASSERT_EQ(repLength(it), 1u);
SEQAN_ASSERT_EQ(representative(it), 'A');
SEQAN_ASSERT_EQ(goRight(it), true);
SEQAN_ASSERT_EQ(representative(it), 'C');
SEQAN_ASSERT_EQ(repLength(it), 1u);
SEQAN_ASSERT_EQ(goRight(it), true);
SEQAN_ASSERT_EQ(representative(it), 'G');
SEQAN_ASSERT_EQ(repLength(it), 1u);
SEQAN_ASSERT_EQ(goRight(it), true);
SEQAN_ASSERT_EQ(representative(it), 'T');
SEQAN_ASSERT_EQ(repLength(it), 1u);
SEQAN_ASSERT_EQ(goRight(it), false);
SEQAN_ASSERT_EQ(representative(it), 'T');
SEQAN_ASSERT_EQ(repLength(it), 1u);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(goDown(it), true);
}
template <typename TIter>
void fmIndexIteratorGoDown(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text;
text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(representative(it), "ACGA");
SEQAN_ASSERT_EQ(goDown(it), false);
SEQAN_ASSERT_EQ(representative(it), "ACGA");
}
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it, 'G'), true);
SEQAN_ASSERT_EQ(representative(it), "G");
SEQAN_ASSERT_EQ(goDown(it, 'G'), false);
SEQAN_ASSERT_EQ(representative(it), "G");
}
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it, 'G'), true);
SEQAN_ASSERT_EQ(goDown(it, 'C'), true);
SEQAN_ASSERT_EQ(goDown(it, 'A'), true);
SEQAN_ASSERT_EQ(goDown(it, 'G'), true);
SEQAN_ASSERT_EQ(goDown(it, 'C'), true);
SEQAN_ASSERT_EQ(goDown(it, 'A'), true);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
SEQAN_ASSERT_EQ(goDown(it, 'G'), false);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
}
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it, "GCAGCA"), true);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
SEQAN_ASSERT_EQ(goDown(it, 'G'), false);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
}
}
template <typename TIter>
void fmIndexIteratorIsLeaf(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(isLeaf(it), false);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(isLeaf(it), false);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(isLeaf(it), false);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(isLeaf(it), false);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(isLeaf(it), true);
SEQAN_ASSERT_EQ(representative(it), "ACGA");
SEQAN_ASSERT_EQ(goDown(it), false);
SEQAN_ASSERT_EQ(representative(it), "ACGA");
}
}
template <typename TIter>
void fmIndexIteratorGoRight(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it), true);
SEQAN_ASSERT_EQ(representative(it), "A");
SEQAN_ASSERT_EQ(goRight(it), true);
SEQAN_ASSERT_EQ(representative(it), "C");
SEQAN_ASSERT_EQ(goRight(it), true);
SEQAN_ASSERT_EQ(representative(it), "G");
SEQAN_ASSERT_EQ(goRight(it), false);
SEQAN_ASSERT_EQ(representative(it), "G");
}
}
template <typename TIter>
void fmIndexIteratorGoUp(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(goDown(it, "GCAGCA"), true);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "CGACG");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "GACG");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "ACG");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "CG");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "G");
SEQAN_ASSERT_EQ(goUp(it), true);
SEQAN_ASSERT_EQ(representative(it), "");
SEQAN_ASSERT_EQ(goUp(it), false);
SEQAN_ASSERT_EQ(representative(it), "");
}
}
template <typename TIter>
void fmIndexIteratorIsRoot(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(isRoot(it), true);
SEQAN_ASSERT_EQ(goDown(it, "GCAGCA"), true);
SEQAN_ASSERT_EQ(isRoot(it), false);
}
}
template <typename TIter>
void fmIndexIteratorRepresentative(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
TText text = "ACGACG";
TIndex fmIndex(text);
{
TIter it(fmIndex);
SEQAN_ASSERT_EQ(representative(it), "");
SEQAN_ASSERT_EQ(goDown(it, "GCAGCA"), true);
SEQAN_ASSERT_EQ(representative(it), "ACGACG");
}
}
template <typename TIter>
void fmIndexIteratorCountOccurrences(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
typedef Index<TText, IndexEsa<> > TEsaIndex;
typedef typename Iterator<TEsaIndex, TopDown<ParentLinks<> > >::Type TEsaIter;
TText text;
generateText(text);
StringSet<String<typename Value<TIndex>::Type> > pattern;
generatePattern(pattern, text);
TIndex fmIndex(text);
TEsaIndex esaIndex(text);
TIter it(fmIndex);
TEsaIter esaIt(esaIndex);
for (unsigned i = 0; i < length(pattern); ++i)
{
reverse(pattern[i]);
bool _goDown = goDown(it, pattern[i]);
reverse(pattern[i]);
SEQAN_ASSERT_EQ(_goDown, goDown(esaIt, pattern[i]));
if (_goDown)
{
SEQAN_ASSERT_EQ(countOccurrences(it), countOccurrences(esaIt));
}
goRoot(it);
goRoot(esaIt);
}
}
template <typename TIter>
void fmIndexIteratorRange(TIter & /*tag*/)
{
typedef typename Container<TIter>::Type TIndex;
typedef typename Fibre<TIndex, FibreText>::Type TText;
typedef Index<TText, IndexEsa<> > TEsaIndex;
typedef typename Iterator<TEsaIndex, TopDown<ParentLinks<> > >::Type TEsaIter;
TText text;
generateText(text);
StringSet<String<typename Value<TIndex>::Type> > pattern;
generatePattern(pattern, text);
TIndex fmIndex(text);
TEsaIndex esaIndex(text);
TIter it(fmIndex);
TEsaIter esaIt(esaIndex);
for (unsigned i = 0; i < length(pattern); ++i)
{
reverse(pattern[i]);
bool _goDown = goDown(it, pattern[i]);
reverse(pattern[i]);
SEQAN_ASSERT_EQ(_goDown, goDown(esaIt, pattern[i]));
if (_goDown)
{
SEQAN_ASSERT_EQ(range(it).i1 - 1, range(esaIt).i1);
SEQAN_ASSERT_EQ(range(it).i2 - 1, range(esaIt).i2);
}
goRoot(it);
goRoot(esaIt);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_constuctor)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "AAA";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorConstuctor(dnaTag);
}
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorConstuctor(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_go_down)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
{
DnaString genome;
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorGoDown(dnaTag);
}
{
DnaString genome;
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorGoDown(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_is_leaf)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorIsLeaf(dnaTag);
}
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorIsLeaf(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_go_right)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorGoRight(dnaTag);
}
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorGoRight(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_go_up)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorGoUp(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_representative)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorRepresentative(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_is_root)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorIsRoot(dnaTag);
}
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorIsRoot(dnaTag);
}
}
SEQAN_DEFINE_TEST(fm_index_iterator_count_occurrences)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
{
DnaString genome;
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorCountOccurrences(dnaTag);
}
{
DnaString genome;
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorCountOccurrences(dnaTag);
}
// {
// StringSet<DnaString> genome;
// Index<StringSet<DnaString>,TDefaultIndex> index(genome);
// Iterator<Index<StringSet<DnaString>,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag;
// fmIndexIteratorCountOccurrences(dnaTag);
// }
}
SEQAN_DEFINE_TEST(fm_index_iterator_range)
{
using namespace seqan;
typedef FMIndex<WT<>, void> TDefaultIndex;
typedef TopDown<> TIterSpec;
typedef TopDown<ParentLinks<> > TParentLinksIterSpec;
DnaString genome = "A";
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TIterSpec>::Type dnaTag(index);
fmIndexIteratorRange(dnaTag);
}
{
Index<DnaString,TDefaultIndex> index(genome);
Iterator<Index<DnaString,TDefaultIndex>, TParentLinksIterSpec>::Type dnaTag(index);
fmIndexIteratorRange(dnaTag);
}
}
#endif // TESTS_INDEX_TEST_INDEX_FM_ITER_H_
| bsd-3-clause |
sgraham/nope | chrome/browser/sync/test/integration/single_client_bookmarks_sync_test.cc | 12107 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "sync/test/fake_server/bookmark_entity_builder.h"
#include "sync/test/fake_server/entity_builder_factory.h"
#include "sync/test/fake_server/fake_server_verifier.h"
#include "ui/base/layout.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks_helper::AddFolder;
using bookmarks_helper::AddURL;
using bookmarks_helper::CountBookmarksWithTitlesMatching;
using bookmarks_helper::Create1xFaviconFromPNGFile;
using bookmarks_helper::GetBookmarkBarNode;
using bookmarks_helper::GetBookmarkModel;
using bookmarks_helper::GetOtherNode;
using bookmarks_helper::ModelMatchesVerifier;
using bookmarks_helper::Move;
using bookmarks_helper::Remove;
using bookmarks_helper::RemoveAll;
using bookmarks_helper::SetFavicon;
using bookmarks_helper::SetTitle;
using sync_integration_test_util::AwaitCommitActivityCompletion;
class SingleClientBookmarksSyncTest : public SyncTest {
public:
SingleClientBookmarksSyncTest() : SyncTest(SINGLE_CLIENT) {}
~SingleClientBookmarksSyncTest() override {}
// Verify that the local bookmark model (for the Profile corresponding to
// |index|) matches the data on the FakeServer. It is assumed that FakeServer
// is being used and each bookmark has a unique title. Folders are not
// verified.
void VerifyBookmarkModelMatchesFakeServer(int index);
private:
DISALLOW_COPY_AND_ASSIGN(SingleClientBookmarksSyncTest);
};
void SingleClientBookmarksSyncTest::VerifyBookmarkModelMatchesFakeServer(
int index) {
fake_server::FakeServerVerifier fake_server_verifier(GetFakeServer());
std::vector<BookmarkModel::URLAndTitle> local_bookmarks;
GetBookmarkModel(index)->GetBookmarks(&local_bookmarks);
// Verify that the number of local bookmarks matches the number in the
// server.
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByType(
local_bookmarks.size(),
syncer::BOOKMARKS));
// Verify that all local bookmark titles exist once on the server.
std::vector<BookmarkModel::URLAndTitle>::const_iterator it;
for (it = local_bookmarks.begin(); it != local_bookmarks.end(); ++it) {
ASSERT_TRUE(fake_server_verifier.VerifyEntityCountByTypeAndName(
1,
syncer::BOOKMARKS,
base::UTF16ToUTF8(it->title)));
}
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, Sanity) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> top
// -> tier1_a
// -> http://mail.google.com "tier1_a_url0"
// -> http://www.pandora.com "tier1_a_url1"
// -> http://www.facebook.com "tier1_a_url2"
// -> tier1_b
// -> http://www.nhl.com "tier1_b_url0"
const BookmarkNode* top = AddFolder(0, GetOtherNode(0), 0, "top");
const BookmarkNode* tier1_a = AddFolder(0, top, 0, "tier1_a");
const BookmarkNode* tier1_b = AddFolder(0, top, 1, "tier1_b");
const BookmarkNode* tier1_a_url0 = AddURL(
0, tier1_a, 0, "tier1_a_url0", GURL("http://mail.google.com"));
const BookmarkNode* tier1_a_url1 = AddURL(
0, tier1_a, 1, "tier1_a_url1", GURL("http://www.pandora.com"));
const BookmarkNode* tier1_a_url2 = AddURL(
0, tier1_a, 2, "tier1_a_url2", GURL("http://www.facebook.com"));
const BookmarkNode* tier1_b_url0 = AddURL(
0, tier1_b, 0, "tier1_b_url0", GURL("http://www.nhl.com"));
// Setup sync, wait for its completion, and make sure changes were synced.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Ultimately we want to end up with the following model; but this test is
// more about the journey than the destination.
//
// bookmark_bar
// -> CNN (www.cnn.com)
// -> tier1_a
// -> tier1_a_url2 (www.facebook.com)
// -> tier1_a_url1 (www.pandora.com)
// -> Porsche (www.porsche.com)
// -> Bank of America (www.bankofamerica.com)
// -> Seattle Bubble
// other_node
// -> top
// -> tier1_b
// -> Wired News (www.wired.com)
// -> tier2_b
// -> tier1_b_url0
// -> tier3_b
// -> Toronto Maple Leafs (mapleleafs.nhl.com)
// -> Wynn (www.wynnlasvegas.com)
// -> tier1_a_url0
const BookmarkNode* bar = GetBookmarkBarNode(0);
const BookmarkNode* cnn = AddURL(0, bar, 0, "CNN",
GURL("http://www.cnn.com"));
ASSERT_TRUE(cnn != NULL);
Move(0, tier1_a, bar, 1);
// Wait for the bookmark position change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
const BookmarkNode* porsche = AddURL(0, bar, 2, "Porsche",
GURL("http://www.porsche.com"));
// Rearrange stuff in tier1_a.
ASSERT_EQ(tier1_a, tier1_a_url2->parent());
ASSERT_EQ(tier1_a, tier1_a_url1->parent());
Move(0, tier1_a_url2, tier1_a, 0);
Move(0, tier1_a_url1, tier1_a, 2);
// Wait for the rearranged hierarchy to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(1, tier1_a_url0->parent()->GetIndexOf(tier1_a_url0));
Move(0, tier1_a_url0, bar, bar->child_count());
const BookmarkNode* boa = AddURL(0, bar, bar->child_count(),
"Bank of America", GURL("https://www.bankofamerica.com"));
ASSERT_TRUE(boa != NULL);
Move(0, tier1_a_url0, top, top->child_count());
const BookmarkNode* bubble = AddURL(
0, bar, bar->child_count(), "Seattle Bubble",
GURL("http://seattlebubble.com"));
ASSERT_TRUE(bubble != NULL);
const BookmarkNode* wired = AddURL(0, bar, 2, "Wired News",
GURL("http://www.wired.com"));
const BookmarkNode* tier2_b = AddFolder(
0, tier1_b, 0, "tier2_b");
Move(0, tier1_b_url0, tier2_b, 0);
Move(0, porsche, bar, 0);
SetTitle(0, wired, "News Wired");
SetTitle(0, porsche, "ICanHazPorsche?");
// Wait for the title change to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
ASSERT_EQ(tier1_a_url0->id(), top->GetChild(top->child_count() - 1)->id());
Remove(0, top, top->child_count() - 1);
Move(0, wired, tier1_b, 0);
Move(0, porsche, bar, 3);
const BookmarkNode* tier3_b = AddFolder(0, tier2_b, 1, "tier3_b");
const BookmarkNode* leafs = AddURL(
0, tier1_a, 0, "Toronto Maple Leafs", GURL("http://mapleleafs.nhl.com"));
const BookmarkNode* wynn = AddURL(0, bar, 1, "Wynn",
GURL("http://www.wynnlasvegas.com"));
Move(0, wynn, tier3_b, 0);
Move(0, leafs, tier3_b, 0);
// Wait for newly added bookmarks to sync.
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Only verify FakeServer data if FakeServer is being used.
// TODO(pvalenzuela): Use this style of verification in more tests once it is
// proven stable.
if (GetFakeServer())
VerifyBookmarkModelMatchesFakeServer(0);
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, InjectedBookmark) {
std::string title = "Montreal Canadiens";
fake_server::EntityBuilderFactory entity_builder_factory;
scoped_ptr<fake_server::FakeServerEntity> entity =
entity_builder_factory.NewBookmarkEntityBuilder(
title, GURL("http://canadiens.nhl.com")).Build();
fake_server_->InjectEntity(entity.Pass());
DisableVerifier();
ASSERT_TRUE(SetupClients());
ASSERT_TRUE(SetupSync());
ASSERT_EQ(1, CountBookmarksWithTitlesMatching(0, title));
}
// Test that a client doesn't mutate the favicon data in the process
// of storing the favicon data from sync to the database or in the process
// of requesting data from the database for sync.
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
SetFaviconHiDPIDifferentCodec) {
// Set the supported scale factors to 1x and 2x such that
// BookmarkModel::GetFavicon() requests both 1x and 2x.
// 1x -> for sync, 2x -> for the UI.
std::vector<ui::ScaleFactor> supported_scale_factors;
supported_scale_factors.push_back(ui::SCALE_FACTOR_100P);
supported_scale_factors.push_back(ui::SCALE_FACTOR_200P);
ui::SetSupportedScaleFactors(supported_scale_factors);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(ModelMatchesVerifier(0));
const GURL page_url("http://www.google.com");
const GURL icon_url("http://www.google.com/favicon.ico");
const BookmarkNode* bookmark = AddURL(0, "title", page_url);
// Simulate receiving a favicon from sync encoded by a different PNG encoder
// than the one native to the OS. This tests the PNG data is not decoded to
// SkBitmap (or any other image format) then encoded back to PNG on the path
// between sync and the database.
gfx::Image original_favicon = Create1xFaviconFromPNGFile(
"favicon_cocoa_png_codec.png");
ASSERT_FALSE(original_favicon.IsEmpty());
SetFavicon(0, bookmark, icon_url, original_favicon,
bookmarks_helper::FROM_SYNC);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
scoped_refptr<base::RefCountedMemory> original_favicon_bytes =
original_favicon.As1xPNGBytes();
gfx::Image final_favicon = GetBookmarkModel(0)->GetFavicon(bookmark);
scoped_refptr<base::RefCountedMemory> final_favicon_bytes =
final_favicon.As1xPNGBytes();
// Check that the data was not mutated from the original.
EXPECT_TRUE(original_favicon_bytes.get());
EXPECT_TRUE(original_favicon_bytes->Equals(final_favicon_bytes));
}
IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest,
BookmarkAllNodesRemovedEvent) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
// Starting state:
// other_node
// -> folder0
// -> tier1_a
// -> http://mail.google.com
// -> http://www.google.com
// -> http://news.google.com
// -> http://yahoo.com
// -> http://www.cnn.com
// bookmark_bar
// -> empty_folder
// -> folder1
// -> http://yahoo.com
// -> http://gmail.com
const BookmarkNode* folder0 = AddFolder(0, GetOtherNode(0), 0, "folder0");
const BookmarkNode* tier1_a = AddFolder(0, folder0, 0, "tier1_a");
ASSERT_TRUE(AddURL(0, folder0, 1, "News", GURL("http://news.google.com")));
ASSERT_TRUE(AddURL(0, folder0, 2, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 0, "Gmai", GURL("http://mail.google.com")));
ASSERT_TRUE(AddURL(0, tier1_a, 1, "Google", GURL("http://www.google.com")));
ASSERT_TRUE(
AddURL(0, GetOtherNode(0), 1, "CNN", GURL("http://www.cnn.com")));
ASSERT_TRUE(AddFolder(0, GetBookmarkBarNode(0), 0, "empty_folder"));
const BookmarkNode* folder1 =
AddFolder(0, GetBookmarkBarNode(0), 1, "folder1");
ASSERT_TRUE(AddURL(0, folder1, 0, "Yahoo", GURL("http://www.yahoo.com")));
ASSERT_TRUE(
AddURL(0, GetBookmarkBarNode(0), 2, "Gmai", GURL("http://gmail.com")));
// Set up sync, wait for its completion and verify that changes propagated.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
ASSERT_TRUE(ModelMatchesVerifier(0));
// Remove all bookmarks and wait for sync completion.
RemoveAll(0);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((0))));
// Verify other node has no children now.
EXPECT_EQ(0, GetOtherNode(0)->child_count());
EXPECT_EQ(0, GetBookmarkBarNode(0)->child_count());
// Verify model matches verifier.
ASSERT_TRUE(ModelMatchesVerifier(0));
}
| bsd-3-clause |
chromium/chromium | tools/binary_size/libsupersize/zip_util.py | 5188 | # Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utilities to process compresssed files."""
import contextlib
import logging
import os
import pathlib
import re
import shutil
import struct
import tempfile
import zipfile
class _ApkFileManager:
def __init__(self, temp_dir):
self._temp_dir = pathlib.Path(temp_dir)
self._subdir_by_apks_path = {}
self._infolist_by_path = {}
def _MapPath(self, path):
# Use numbered subdirectories for uniqueness.
# Suffix with basename(path) for readability.
default = '-'.join(
[str(len(self._subdir_by_apks_path)),
os.path.basename(path)])
return self._temp_dir / self._subdir_by_apks_path.setdefault(path, default)
def InfoList(self, path):
"""Returns zipfile.ZipFile(path).infolist()."""
ret = self._infolist_by_path.get(path)
if ret is None:
with zipfile.ZipFile(path) as z:
ret = z.infolist()
self._infolist_by_path[path] = ret
return ret
def SplitPath(self, minimal_apks_path, split_name):
"""Returns the path to the apk split extracted by ExtractSplits.
Args:
minimal_apks_path: The .apks file that was passed to ExtractSplits().
split_name: Then name of the split.
Returns:
Path to the extracted .apk file.
"""
subdir = self._subdir_by_apks_path[minimal_apks_path]
return self._temp_dir / subdir / 'splits' / f'{split_name}-master.apk'
def ExtractSplits(self, minimal_apks_path):
"""Extracts the master splits in the given .apks file.
Returns:
List of split names, with "base" always appearing first.
"""
dest = self._MapPath(minimal_apks_path)
split_names = []
logging.debug('Extracting %s', minimal_apks_path)
with zipfile.ZipFile(minimal_apks_path) as z:
for filename in z.namelist():
# E.g.:
# splits/base-master.apk
# splits/base-en.apk
# splits/vr-master.apk
# splits/vr-en.apk
m = re.match(r'splits/(.*)-master\.apk', filename)
if m:
split_names.append(m.group(1))
z.extract(filename, dest)
logging.debug('Extracting %s (done)', minimal_apks_path)
# Make "base" comes first since that's the main chunk of work.
# Also so that --abi-filter detection looks at it first.
return sorted(split_names, key=lambda x: (x != 'base', x))
@contextlib.contextmanager
def ApkFileManager():
"""Context manager that extracts apk splits to a temp dir."""
# Cannot use tempfile.TemporaryDirectory() here because our use of
# multiprocessing results in __del__ methods being called in forked processes.
temp_dir = tempfile.mkdtemp(suffix='-supersize')
zip_files = _ApkFileManager(temp_dir)
yield zip_files
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def UnzipToTemp(zip_path, inner_path):
"""Extract a |inner_path| from a |zip_path| file to an auto-deleted temp file.
Args:
zip_path: Path to the zip file.
inner_path: Path to the file within |zip_path| to extract.
Yields:
The path of the temp created (and auto-deleted when context exits).
"""
try:
logging.debug('Extracting %s', inner_path)
_, suffix = os.path.splitext(inner_path)
# Can't use NamedTemporaryFile() because it deletes via __del__, which will
# trigger in both this and the fork()'ed processes.
fd, temp_file = tempfile.mkstemp(suffix=suffix)
with zipfile.ZipFile(zip_path) as z:
os.write(fd, z.read(inner_path))
os.close(fd)
logging.debug('Extracting %s (done)', inner_path)
yield temp_file
finally:
os.unlink(temp_file)
def ReadZipInfoExtraFieldLength(zip_file, zip_info):
"""Reads the value of |extraLength| from |zip_info|'s local file header.
|zip_info| has an |extra| field, but it's read from the central directory.
Android's zipalign tool sets the extra field only in local file headers.
"""
# Refer to https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
zip_file.fp.seek(zip_info.header_offset + 28)
return struct.unpack('<H', zip_file.fp.read(2))[0]
def MeasureApkSignatureBlock(zip_file):
"""Measures the size of the v2 / v3 signing block.
Refer to: https://source.android.com/security/apksigning/v2
"""
# Seek to "end of central directory" struct.
eocd_offset_from_end = -22 - len(zip_file.comment)
zip_file.fp.seek(eocd_offset_from_end, os.SEEK_END)
assert zip_file.fp.read(4) == b'PK\005\006', (
'failed to find end-of-central-directory')
# Read out the "start of central directory" offset.
zip_file.fp.seek(eocd_offset_from_end + 16, os.SEEK_END)
start_of_central_directory = struct.unpack('<I', zip_file.fp.read(4))[0]
# Compute the offset after the last zip entry.
last_info = max(zip_file.infolist(), key=lambda i: i.header_offset)
last_header_size = (30 + len(last_info.filename) +
ReadZipInfoExtraFieldLength(zip_file, last_info))
end_of_last_file = (last_info.header_offset + last_header_size +
last_info.compress_size)
return start_of_central_directory - end_of_last_file
| bsd-3-clause |
adamkalmus/motech | platform/mds/mds/src/main/resources/db/migration/default/V22__MOTECH-1399.sql | 266 | -- adds crudEvents columns ---
ALTER TABLE "Tracking" ADD "allowCreateEvent" boolean NOT NULL DEFAULT false;
ALTER TABLE "Tracking" ADD "allowDeleteEvent" boolean NOT NULL DEFAULT false;
ALTER TABLE "Tracking" ADD "allowUpdateEvent" boolean NOT NULL DEFAULT false;
| bsd-3-clause |
chromium/chromium | components/translate/core/browser/translate_ui_delegate.h | 7760 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_TRANSLATE_CORE_BROWSER_TRANSLATE_UI_DELEGATE_H_
#define COMPONENTS_TRANSLATE_CORE_BROWSER_TRANSLATE_UI_DELEGATE_H_
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/translate/core/browser/translate_metrics_logger.h"
#include "components/translate/core/common/translate_errors.h"
namespace translate {
class LanguageState;
class TranslateDriver;
class TranslateManager;
class TranslatePrefs;
// The TranslateUIDelegate is a generic delegate for UI which offers Translate
// feature to the user.
// Note that the API offers a way to read/set language values through array
// indices. Such indices are only valid as long as the visual representation
// (infobar, bubble...) is in sync with the underlying language list which
// can actually change at run time (see translate_language_list.h).
// It is recommended that languages are only updated by language code to
// avoid bugs like crbug.com/555124
class TranslateUIDelegate {
public:
static const size_t kNoIndex = static_cast<size_t>(-1);
TranslateUIDelegate(const base::WeakPtr<TranslateManager>& translate_manager,
const std::string& source_language,
const std::string& target_language);
TranslateUIDelegate(const TranslateUIDelegate&) = delete;
TranslateUIDelegate& operator=(const TranslateUIDelegate&) = delete;
virtual ~TranslateUIDelegate();
// Handles when an error message is shown.
void OnErrorShown(TranslateErrors::Type error_type);
// Returns the LanguageState associated with this object.
const LanguageState* GetLanguageState();
// Returns the number of languages supported.
size_t GetNumberOfLanguages() const;
// Returns the source language index.
size_t GetSourceLanguageIndex() const { return source_language_index_; }
// Returns the source language code.
std::string GetSourceLanguageCode() const;
// Updates the source language index.
void UpdateSourceLanguageIndex(size_t language_index);
void UpdateSourceLanguage(const std::string& language_code);
// Returns the target language index.
size_t GetTargetLanguageIndex() const { return target_language_index_; }
// Returns the target language code.
std::string GetTargetLanguageCode() const;
// Updates the target language index.
void UpdateTargetLanguageIndex(size_t language_index);
void UpdateTargetLanguage(const std::string& language_code);
// Returns the ISO code for the language at |index|.
std::string GetLanguageCodeAt(size_t index) const;
// Returns the displayable name for the language at |index|.
std::u16string GetLanguageNameAt(size_t index) const;
// Translatable content languages.
void GetContentLanguagesCodes(
std::vector<std::string>* content_languages_codes) const;
// Starts translating the current page.
void Translate();
// Reverts translation.
void RevertTranslation();
// Processes when the user declines translation.
// The function name is not accurate. It only means the user did not take
// affirmative action after the translation ui show up. The user either
// actively decline the translation or ignore the prompt of translation.
// Pass |explicitly_closed| as true if user explicityly decline the
// translation.
// Pass |explicitly_closed| as false if the translation UI is dismissed
// implicit by some user actions which ignore the translation UI,
// such as switch to a new tab/window or navigate to another page by
// click a link.
void TranslationDeclined(bool explicitly_closed);
// Returns true if the current language is blocked.
bool IsLanguageBlocked() const;
// Sets the value if the current language is blocked.
void SetLanguageBlocked(bool value);
// Returns true if the current webpage should never be prompted for
// translation.
bool IsSiteOnNeverPromptList() const;
// Returns true if the site of the current webpage can be put on the never
// prompt list.
bool CanAddSiteToNeverPromptList() const;
// Sets the never-prompt state for the host of the current page. If
// value is true, the current host will be blocklisted and translation
// prompts will not show for that site.
void SetNeverPromptSite(bool value);
// Returns true if the webpage in the current source language should be
// translated into the current target language automatically.
bool ShouldAlwaysTranslate() const;
// Sets the value if the webpage in the current source language should be
// translated into the current target language automatically.
void SetAlwaysTranslate(bool value);
// Returns true if the Always Translate checkbox should be checked by default.
bool ShouldAlwaysTranslateBeCheckedByDefault() const;
// Returns true if the UI should offer the user a shortcut to always translate
// the language, when we think the user wants that functionality.
bool ShouldShowAlwaysTranslateShortcut() const;
// Returns true if the UI should offer the user a shortcut to never translate
// the language, when we think the user wants that functionality.
bool ShouldShowNeverTranslateShortcut() const;
// Updates metrics when a user's action closes the translate UI. This includes
// when: the user presses the 'x' button, the user selects to never translate
// this site, and the user selects to never translate this language.
void OnUIClosedByUser();
// Records a high level UI interaction.
void ReportUIInteraction(UIInteraction ui_interaction);
// If kContentLanguagesinLanguagePicker is on, build a vector of content
// languages data.
void MaybeSetContentLanguages();
private:
FRIEND_TEST_ALL_PREFIXES(TranslateUIDelegateTest, GetPageHost);
FRIEND_TEST_ALL_PREFIXES(TranslateUIDelegateTest, MaybeSetContentLanguages);
// Gets the host of the page being translated, or an empty string if no URL is
// associated with the current page.
std::string GetPageHost() const;
raw_ptr<TranslateDriver> translate_driver_;
base::WeakPtr<TranslateManager> translate_manager_;
// ISO code (en, fr...) -> displayable name in the current locale
typedef std::pair<std::string, std::u16string> LanguageNamePair;
// The list supported languages for translation.
// The languages are sorted alphabetically based on the displayable name.
std::vector<LanguageNamePair> languages_;
// The list of language codes representing translatable user's setting
// languages. The languages are in order defined by the user.
std::vector<std::string> translatable_content_languages_codes_;
// The index for language the page is in before translation.
size_t source_language_index_;
// The index for language the page is in before translation in that was first
// reported (source_language_index_ changes if the user selects a new
// source language, but this one does not). This is necessary to report
// language detection errors with the right source language even if the user
// changed the source language.
size_t initial_source_language_index_;
// The index for language the page should be translated to.
size_t target_language_index_;
// The translation related preferences.
std::unique_ptr<TranslatePrefs> prefs_;
// Listens to accept languages changes.
PrefChangeRegistrar pref_change_registrar_;
};
} // namespace translate
#endif // COMPONENTS_TRANSLATE_CORE_BROWSER_TRANSLATE_UI_DELEGATE_H_
| bsd-3-clause |
JavieChan/nanshaCity | yejin/templates/adminadd.html | 1593 | ## adminadd.html
<%inherit file="base.html" />
<div class="wrapper">
<input type="hidden" id="location" value="${location}" />
<!--导航-->
<%include file="nav.html" />
<!--右侧功能栏-->
<div class="projects">
<div class="tabbox">
<div class="bread">
<%include file="bread_nav.html" args="location=location,ins=ins,suffix='新增角色',remain=[('帐号管理', '/admin.html?location={}'.format(location)),]"/>
<div class="widget">
<button class="btnBlueSmall" id="roleAdd">确定</button>
<a href="/admin.html?location=${location}" class="btnGraySmall">取消</a>
</div>
</div>
</div>
<div class="tabbox ns_role">
<div class="toolnav">
<h3>角色名称:<input type="text" class="role_ipu" placeholder="请输入角色名称" name="roleName" /></h3>
</div>
<div class="toolnav">
<h3>功能选择:</h3>
</div>
<div class="areabox" id="roleOpra">
% for p in permissions:
<p><label data-resource="${p['resource']}"><i class="headunchk"></i>${p['label']}</label></p>
<div>
% for op in p['operation']:
<label data-operation="${op['name']}"><i class="unchk"></i>${op['label']}</label>
% endfor
</div>
% endfor
</div>
</div>
</div>
</div>
| isc |
pfalcon/micropython | ports/samd/main.c | 3009 | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/compile.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/mperrno.h"
#include "py/stackctrl.h"
#include "lib/utils/gchelper.h"
#include "lib/utils/pyexec.h"
extern uint8_t _sstack, _estack, _sheap, _eheap;
void samd_main(void) {
mp_stack_set_top(&_estack);
mp_stack_set_limit(&_estack - &_sstack - 1024);
for (;;) {
gc_init(&_sheap, &_eheap);
mp_init();
mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_path), 0);
mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_));
mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0);
for (;;) {
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
if (pyexec_raw_repl() != 0) {
break;
}
} else {
if (pyexec_friendly_repl() != 0) {
break;
}
}
}
mp_printf(MP_PYTHON_PRINTER, "MPY: soft reboot\n");
gc_sweep_all();
mp_deinit();
}
}
void gc_collect(void) {
gc_collect_start();
gc_helper_collect_regs_and_stack();
gc_collect_end();
}
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
mp_raise_OSError(MP_ENOENT);
}
mp_import_stat_t mp_import_stat(const char *path) {
return MP_IMPORT_STAT_NO_EXIST;
}
mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) {
for (;;) {
}
}
#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
mp_printf(MP_PYTHON_PRINTER, "Assertion '%s' failed, at file %s:%d\n", expr, file, line);
for (;;) {
}
}
#endif
| mit |
clooket/YouTubeExtractor | YouTubeExtractor/External/gdata-objectivec-client/Source/Clients/WebmasterTools/GDataSitemapNews.h | 1599 | /* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// GDataSitemapNews.h
//
#if !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_WEBMASTERTOOLS_SERVICE
#import "GDataObject.h"
#import "GDataValueConstruct.h"
// News elements, like
//
// <wt:sitemap-news>
// <wt:publication-label>Value1</wt:publication-label>
// <wt:publication-label>Value2</wt:publication-label>
// <wt:publication-label>Value3</wt:publication-label>
// </wt:sitemap-news>
//
// http://code.google.com/apis/webmastertools/docs/reference.html
@interface GDataSitemapPublicationLabel : GDataValueElementConstruct <GDataExtension>
+ (NSString *)extensionElementURI;
+ (NSString *)extensionElementPrefix;
+ (NSString *)extensionElementLocalName;
@end
@interface GDataSitemapNews : GDataObject <GDataExtension>
+ (id)sitemapNews;
- (NSArray *)publicationLabels;
- (void)setPublicationLabels:(NSArray *)arr;
- (void)addPublicationLabel:(GDataSitemapPublicationLabel *)obj;
@end
#endif // !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_WEBMASTERTOOLS_SERVICE
| mit |
YOTOV-LIMITED/Windows-Driver-Frameworks | src/framework/umdf/fxlib/librarycommon/fxlibrarycommon.h | 1287 | //
// Copyright (C) Microsoft. All rights reserved.
//
#ifndef __FX_LIBRARY_COMMON_H__
#define __FX_LIBRARY_COMMON_H__
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
extern ULONG WdfLdrDbgPrintOn;
extern PCHAR WdfLdrType;
extern WDFVERSION WdfVersion;
extern RTL_OSVERSIONINFOW gOsVersion;
#define _LIT_(a) # a
#define LITERAL(a) _LIT_(a)
#define __Print(_x_) \
{ \
if (WdfLdrDbgPrintOn) { \
} \
}
#define WDF_ENHANCED_VERIFIER_OPTIONS_VALUE_NAME L"EnhancedVerifierOptions"
typedef
NTSTATUS
(*PFN_RTL_GET_VERSION)(
OUT PRTL_OSVERSIONINFOW VersionInformation
);
NTSTATUS
FxLibraryCommonCommission(
VOID
);
NTSTATUS
FxLibraryCommonDecommission(
VOID
);
NTSTATUS
FxLibraryCommonRegisterClient(
PWDF_BIND_INFO Info,
PWDF_DRIVER_GLOBALS * WdfDriverGlobals,
PCLIENT_INFO ClientInfo
);
NTSTATUS
FxLibraryCommonUnregisterClient(
PWDF_BIND_INFO Info,
PWDF_DRIVER_GLOBALS WdfDriverGlobals
);
VOID
GetEnhancedVerifierOptions(
PCLIENT_INFO ClientInfo,
PULONG Options
);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // __FX_LIBRARY_COMMON_H__
| mit |
VivaceVivo/cucumber-mod-DI | core/src/main/java/cucumber/runtime/xstream/ListConverter.java | 1391 | package cucumber.runtime.xstream;
import cucumber.deps.com.thoughtworks.xstream.converters.SingleValueConverter;
import java.util.ArrayList;
import java.util.List;
class ListConverter implements SingleValueConverter {
private final String delimiter;
private final SingleValueConverter delegate;
public ListConverter(String delimiter, SingleValueConverter delegate) {
this.delimiter = delimiter;
this.delegate = delegate;
}
@Override
public String toString(Object obj) {
boolean first = true;
if (obj instanceof List) {
StringBuilder sb = new StringBuilder();
for (Object elem : (List) obj) {
if (!first) {
sb.append(delimiter);
}
sb.append(delegate.toString(elem));
first = false;
}
return sb.toString();
} else {
return delegate.toString(obj);
}
}
@Override
public Object fromString(String s) {
final String[] strings = s.split(delimiter);
List<Object> list = new ArrayList<Object>(strings.length);
for (String elem : strings) {
list.add(delegate.fromString(elem));
}
return list;
}
@Override
public boolean canConvert(Class type) {
return List.class.isAssignableFrom(type);
}
}
| mit |
dreamsxin/LuxEngine | external/physx/Include/vs2013/geometry/PxHeightFieldSample.h | 5119 | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_NXHEIGHTFIELDSAMPLE
#define PX_PHYSICS_NXHEIGHTFIELDSAMPLE
/** \addtogroup geomutils
@{ */
#include "common/PxPhysXCommonConfig.h"
#include "foundation/PxBitAndData.h"
#ifndef PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Special material index values for height field samples.
@see PxHeightFieldSample.materialIndex0 PxHeightFieldSample.materialIndex1
*/
struct PxHeightFieldMaterial
{
enum Enum
{
eHOLE = 127 //!< A material indicating that the triangle should be treated as a hole in the mesh.
};
};
/**
\brief Heightfield sample format.
This format corresponds to the #PxHeightFieldFormat member PxHeightFieldFormat::eS16_TM.
An array of heightfield samples are used when creating a PxHeightField to specify
the elevation of the heightfield points. In addition the material and tessellation of the adjacent
triangles are specified.
@see PxHeightField PxHeightFieldDesc PxHeightFieldDesc.samples
*/
struct PxHeightFieldSample
{
//= ATTENTION! =====================================================================================
// Changing the data layout of this class breaks the binary serialization format. See comments for
// PX_BINARY_SERIAL_VERSION. If a modification is required, please adjust the getBinaryMetaData
// function. If the modification is made on a custom branch, please change PX_BINARY_SERIAL_VERSION
// accordingly.
//==================================================================================================
/**
\brief The height of the heightfield sample
This value is scaled by PxHeightFieldGeometry::heightScale.
@see PxHeightFieldGeometry
*/
PxI16 height;
/**
\brief The triangle material index of the quad's lower triangle + tesselation flag
An index pointing into the material table of the shape which instantiates the heightfield.
This index determines the material of the lower of the quad's two triangles (i.e. the quad whose
upper-left corner is this sample, see the Guide for illustrations).
Special values of the 7 data bits are defined by PxHeightFieldMaterial
The tesselation flag specifies which way the quad is split whose upper left corner is this sample.
If the flag is set, the diagonal of the quad will run from this sample to the opposite vertex; if not,
it will run between the other two vertices (see the Guide for illustrations).
@see PxHeightFieldGeometry materialIndex1 PxShape.setmaterials() PxShape.getMaterials()
*/
PxBitAndByte materialIndex0;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU8 tessFlag() const { return PxU8(materialIndex0.isBitSet() ? 1 : 0); } // PT: explicit conversion to make sure we don't break the code
PX_CUDA_CALLABLE PX_FORCE_INLINE void setTessFlag() { materialIndex0.setBit(); }
PX_CUDA_CALLABLE PX_FORCE_INLINE void clearTessFlag() { materialIndex0.clearBit(); }
/**
\brief The triangle material index of the quad's upper triangle + reserved flag
An index pointing into the material table of the shape which instantiates the heightfield.
This index determines the material of the upper of the quad's two triangles (i.e. the quad whose
upper-left corner is this sample, see the Guide for illustrations).
@see PxHeightFieldGeometry materialIndex0 PxShape.setmaterials() PxShape.getMaterials()
*/
PxBitAndByte materialIndex1;
};
#ifndef PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| mit |
darlk/BeeFramework_Android | src/com/external/activeandroid/serializer/UtilDateSerializer.java | 1106 | package com.external.activeandroid.serializer;
/*
* Copyright (C) 2010 Michael Pardo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Date;
public final class UtilDateSerializer extends TypeSerializer {
public Class<?> getDeserializedType() {
return Date.class;
}
public Class<?> getSerializedType() {
return long.class;
}
public Long serialize(Object data) {
if (data == null) {
return null;
}
return ((Date) data).getTime();
}
public Date deserialize(Object data) {
if (data == null) {
return null;
}
return new Date((Long) data);
}
} | mit |
imzcy/JavaScriptExecutable | thirdparty/qt53/include/QtXmlPatterns/5.3.0/QtXmlPatterns/private/qacceltreebuilder_tpl_p.h | 16410 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
/**
* @file
* @short This file is included by qacceltreebuilder_p.h.
* If you need includes in this file, put them in qacceltreebuilder_p.h, outside of the namespace.
*/
template <bool FromDocument>
AccelTreeBuilder<FromDocument>::AccelTreeBuilder(const QUrl &docURI,
const QUrl &baseURI,
const NamePool::Ptr &np,
ReportContext *const context,
Features features) : m_preNumber(-1)
, m_isPreviousAtomic(false)
, m_hasCharacters(false)
, m_isCharactersCompressed(false)
, m_namePool(np)
, m_document(new AccelTree(docURI, baseURI))
, m_skippedDocumentNodes(0)
, m_documentURI(docURI)
, m_context(context)
, m_features(features)
{
Q_ASSERT(m_namePool);
/* TODO Perhaps we can merge m_ancestors and m_size
* into one, and store a struct for the two instead? */
m_ancestors.reserve(DefaultNodeStackSize);
m_ancestors.push(-1);
m_size.reserve(DefaultNodeStackSize);
m_size.push(0);
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::startStructure()
{
if(m_hasCharacters)
{
/* We create a node even if m_characters is empty.
* Remember that `text {""}' creates one text node
* with string value "". */
++m_preNumber;
m_document->basicData.append(AccelTree::BasicNodeData(currentDepth(),
currentParent(),
QXmlNodeModelIndex::Text,
m_isCharactersCompressed ? AccelTree::IsCompressed : 0));
m_document->data.insert(m_preNumber, m_characters);
++m_size.top();
m_characters.clear(); /* We don't want it added twice. */
m_hasCharacters = false;
if(m_isCharactersCompressed)
m_isCharactersCompressed = false;
}
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::item(const Item &it)
{
Q_ASSERT(it);
if(it.isAtomicValue())
{
if(m_isPreviousAtomic)
{
m_characters += QLatin1Char(' ');
m_characters += it.stringValue();
}
else
{
m_isPreviousAtomic = true;
const QString sv(it.stringValue());
if(!sv.isEmpty())
{
m_characters += sv;
m_hasCharacters = true;
}
}
}
else
sendAsNode(it);
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::startElement(const QXmlName &name)
{
startElement(name, 1, 1);
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::startElement(const QXmlName &name, qint64 line, qint64 column)
{
startStructure();
AccelTree::BasicNodeData data(currentDepth(), currentParent(), QXmlNodeModelIndex::Element, -1, name);
m_document->basicData.append(data);
if (m_features & SourceLocationsFeature)
m_document->sourcePositions.insert(m_document->maximumPreNumber(), qMakePair(line, column));
++m_preNumber;
m_ancestors.push(m_preNumber);
++m_size.top();
m_size.push(0);
/* With node constructors, we can receive names for which we have no namespace
* constructors, such as in the query '<xs:space/>'. Since the 'xs' prefix has no
* NamespaceConstructor in this case, we synthesize the namespace.
*
* In case we're constructing from an XML document we avoid the call because
* although it's redundant, it's on extra virtual call for each element. */
if(!FromDocument)
namespaceBinding(QXmlName(name.namespaceURI(), 0, name.prefix()));
m_isPreviousAtomic = false;
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::endElement()
{
startStructure();
const AccelTree::PreNumber index = m_ancestors.pop();
AccelTree::BasicNodeData &data = m_document->basicData[index];
/* Sub trees needs to be included in upper trees, so we add the count of this element
* to our parent. */
m_size[m_size.count() - 2] += m_size.top();
data.setSize(m_size.pop());
m_isPreviousAtomic = false;
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::attribute(const QXmlName &name, const QStringRef &value)
{
/* Attributes adds a namespace binding, so lets synthesize one.
*
* We optimize by checking whether we have a namespace for which a binding would
* be generated. Happens relatively rarely. */
if(name.hasPrefix())
namespaceBinding(QXmlName(name.namespaceURI(), 0, name.prefix()));
m_document->basicData.append(AccelTree::BasicNodeData(currentDepth(), currentParent(), QXmlNodeModelIndex::Attribute, 0, name));
++m_preNumber;
++m_size.top();
m_isPreviousAtomic = false;
if(name.namespaceURI() == StandardNamespaces::xml && name.localName() == StandardLocalNames::id)
{
const QString normalized(value.toString().simplified());
if(QXmlUtils::isNCName(normalized))
{
const QXmlName::LocalNameCode id = m_namePool->allocateLocalName(normalized);
const int oldSize = m_document->m_IDs.count();
m_document->m_IDs.insert(id, currentParent());
/* We don't run the value through m_attributeCompress here, because
* the likelyhood of it deing identical to another attribute is
* very small. */
m_document->data.insert(m_preNumber, normalized);
/**
* In the case that we're called for doc-available(), m_context is
* null, and we need to flag somehow that we failed to load this
* document.
*/
if(oldSize == m_document->m_IDs.count() && m_context) // TODO
{
Q_ASSERT(m_context);
m_context->error(QtXmlPatterns::tr("An %1-attribute with value %2 has already been declared.")
.arg(formatKeyword("xml:id"),
formatData(normalized)),
FromDocument ? ReportContext::FODC0002 : ReportContext::XQDY0091,
this);
}
}
else if(m_context) // TODO
{
Q_ASSERT(m_context);
/* If we're building from an XML Document(e.g, we're fed from QXmlStreamReader, we raise FODC0002,
* otherwise XQDY0091. */
m_context->error(QtXmlPatterns::tr("An %1-attribute must have a "
"valid %2 as value, which %3 isn't.").arg(formatKeyword("xml:id"),
formatType(m_namePool, BuiltinTypes::xsNCName),
formatData(value.toString())),
FromDocument ? ReportContext::FODC0002 : ReportContext::XQDY0091,
this);
}
}
else
m_document->data.insert(m_preNumber, *m_attributeCompress.insert(value.toString()));
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::characters(const QStringRef &ch)
{
/* If a text node constructor appears by itself, a node needs to
* be created. Therefore, we set m_hasCharacters
* if we're the only node.
* However, if the text node appears as a child of a document or element
* node it is discarded if it's empty.
*/
if(m_hasCharacters && m_isCharactersCompressed)
{
m_characters = CompressedWhitespace::decompress(m_characters);
m_isCharactersCompressed = false;
}
m_characters += ch;
m_isPreviousAtomic = false;
m_hasCharacters = !m_characters.isEmpty() || m_preNumber == -1; /* -1 is our start value. */
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::whitespaceOnly(const QStringRef &ch)
{
Q_ASSERT(!ch.isEmpty());
Q_ASSERT(ch.toString().trimmed().isEmpty());
/* This gets problematic due to how QXmlStreamReader works(which
* is the only one we get whitespaceOnly() events from). Namely, text intermingled
* with CDATA gets reported as individual Characters events, and
* QXmlStreamReader::isWhitespace() can return differently for each of those. However,
* it will occur very rarely, so this workaround of 1) mistakenly compressing 2) decompressing 3)
* appending, will happen infrequently.
*/
if(m_hasCharacters)
{
if(m_isCharactersCompressed)
{
m_characters = CompressedWhitespace::decompress(m_characters);
m_isCharactersCompressed = false;
}
m_characters.append(ch.toString());
}
else
{
/* We haven't received a text node previously. */
m_characters = CompressedWhitespace::compress(ch);
m_isCharactersCompressed = true;
m_isPreviousAtomic = false;
m_hasCharacters = true;
}
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::processingInstruction(const QXmlName &target,
const QString &data)
{
startStructure();
++m_preNumber;
m_document->data.insert(m_preNumber, data);
m_document->basicData.append(AccelTree::BasicNodeData(currentDepth(),
currentParent(),
QXmlNodeModelIndex::ProcessingInstruction,
0,
target));
++m_size.top();
m_isPreviousAtomic = false;
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::comment(const QString &content)
{
startStructure();
m_document->basicData.append(AccelTree::BasicNodeData(currentDepth(), currentParent(), QXmlNodeModelIndex::Comment, 0));
++m_preNumber;
m_document->data.insert(m_preNumber, content);
++m_size.top();
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::namespaceBinding(const QXmlName &nb)
{
/* Note, because attribute() sometimes generate namespaceBinding() calls, this function
* can be called after attributes, in contrast to what the class documentation says. This is ok,
* as long as we're not dealing with public API. */
/* If we've received attributes, it means the element's size have changed and m_preNumber have advanced,
* so "reverse back" to the actual element. */
const AccelTree::PreNumber pn = m_preNumber - m_size.top();
QVector<QXmlName> &nss = m_document->namespaces[pn];
/* "xml" hasn't been declared for each node, AccelTree::namespaceBindings() adds it, so avoid it
* such that we don't get duplicates. */
if(nb.prefix() == StandardPrefixes::xml)
return;
/* If we already have the binding, skip it. */
const int len = nss.count();
for(int i = 0; i < len; ++i)
{
if(nss.at(i).prefix() == nb.prefix())
return;
}
nss.append(nb);
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::startDocument()
{
/* If we have already received nodes, we can't add a document node. */
if(m_preNumber == -1) /* -1 is our start value. */
{
m_size.push(0);
m_document->basicData.append(AccelTree::BasicNodeData(0, -1, QXmlNodeModelIndex::Document, -1));
++m_preNumber;
m_ancestors.push(m_preNumber);
}
else
++m_skippedDocumentNodes;
m_isPreviousAtomic = false;
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::endDocument()
{
if(m_skippedDocumentNodes == 0)
{
/* Create text nodes, if we've received any. We do this only if we're the
* top node because if we're getting this event as being a child of an element,
* text nodes or atomic values can appear after us, and which must get
* merged with the previous text.
*
* We call startStructure() before we pop the ancestor, such that the text node becomes
* a child of this document node. */
startStructure();
m_document->basicData.first().setSize(m_size.pop());
m_ancestors.pop();
}
else
--m_skippedDocumentNodes;
m_isPreviousAtomic = false;
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::atomicValue(const QVariant &value)
{
Q_UNUSED(value);
// TODO
}
template <bool FromDocument>
QAbstractXmlNodeModel::Ptr AccelTreeBuilder<FromDocument>::builtDocument()
{
/* Create a text node, if we have received text in some way. */
startStructure();
m_document->printStats(m_namePool);
return m_document;
}
template <bool FromDocument>
NodeBuilder::Ptr AccelTreeBuilder<FromDocument>::create(const QUrl &baseURI) const
{
Q_UNUSED(baseURI);
return NodeBuilder::Ptr(new AccelTreeBuilder(QUrl(), baseURI, m_namePool, m_context));
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::startOfSequence()
{
}
template <bool FromDocument>
void AccelTreeBuilder<FromDocument>::endOfSequence()
{
}
template <bool FromDocument>
const SourceLocationReflection *AccelTreeBuilder<FromDocument>::actualReflection() const
{
return this;
}
template <bool FromDocument>
QSourceLocation AccelTreeBuilder<FromDocument>::sourceLocation() const
{
if(m_documentURI.isEmpty())
return QSourceLocation(QUrl(QLatin1String("AnonymousNodeTree")));
else
return QSourceLocation(m_documentURI);
}
| mit |
northdakota/platform | src/Oro/Bundle/TranslationBundle/Tests/Unit/Command/OroTranslationPackCommandTest.php | 7533 | <?php
namespace Oro\Bundle\TranslationBundle\Tests\Unit\Command;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Oro\Bundle\TranslationBundle\Tests\Unit\Command\Stubs\TestKernel;
use Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand;
class OroTranslationPackCommandTest extends \PHPUnit_Framework_TestCase
{
public function testConfigure()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$app->add($this->getCommandMock());
$command = $app->find('oro:translation:pack');
$this->assertNotEmpty($command->getDescription());
$this->assertNotEmpty($command->getDefinition());
$this->assertNotEmpty($command->getHelp());
}
/**
* Test command execute
*
* @dataProvider executeInputProvider
*
* @param array $input
* @param array $expectedCalls
* @param bool|string $exception
*/
public function testExecute($input, $expectedCalls = array(), $exception = false)
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock(array_keys($expectedCalls));
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
if ($exception) {
$this->setExpectedException($exception);
}
$transServiceMock = $this->getMockBuilder(
'Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider'
)
->disableOriginalConstructor()
->getMock();
foreach ($expectedCalls as $method => $count) {
if ($method == 'getTranslationService') {
$commandMock->expects($this->exactly($count))
->method($method)
->will($this->returnValue($transServiceMock));
}
$commandMock->expects($this->exactly($count))->method($method);
}
$tester = new CommandTester($command);
$input += array('command' => $command->getName());
$tester->execute($input);
}
/**
* @return array
*/
public function executeInputProvider()
{
return array(
'error if action not specified' => array(
array('project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 0
)
),
'error if project not specified' => array(
array('--dump' => true),
array(
'dump' => 0,
'upload' => 0
),
'\RuntimeException'
),
'dump action should perform' => array(
array('--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 0
),
),
'upload action should perform' => array(
array('--upload' => true, 'project' => 'SomeProject'),
array(
'dump' => 0,
'upload' => 1,
'getTranslationService' => 1,
'getLangPackDir' => 1,
),
),
'dump and upload action should perform' => array(
array('--upload' => true, '--dump' => true, 'project' => 'SomeProject'),
array(
'dump' => 1,
'upload' => 1,
'getTranslationService' => 1,
),
)
);
}
public function testUpload()
{
$this->runUploadDownloadTest('upload');
}
public function testUpdate()
{
$this->runUploadDownloadTest('upload', array('-m' => 'update'));
}
public function testDownload()
{
$this->runUploadDownloadTest('download');
}
public function runUploadDownloadTest($commandName, $args = [])
{
$kernel = new TestKernel();
$kernel->boot();
$projectId = 'someproject';
$adapterMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\CrowdinAdapter');
$adapterMock->expects($this->any())
->method('setProjectId')
->with($projectId);
$uploaderMock = $this->getNewMock('Oro\Bundle\TranslationBundle\Provider\TranslationServiceProvider');
$uploaderMock->expects($this->any())
->method('setAdapter')
->with($adapterMock)
->will($this->returnSelf());
$uploaderMock->expects($this->once())
->method('setLogger')
->with($this->isInstanceOf('Psr\Log\LoggerInterface'))
->will($this->returnSelf());
if (isset($args['-m']) && $args['-m'] == 'update') {
$uploaderMock->expects($this->once())
->method('update');
} else {
$uploaderMock->expects($this->once())
->method($commandName);
}
$kernel->getContainer()->set('oro_translation.uploader.crowdin_adapter', $adapterMock);
$kernel->getContainer()->set('oro_translation.service_provider', $uploaderMock);
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), '--' . $commandName => true, 'project' => $projectId);
if (!empty($args)) {
$input = array_merge($input, $args);
}
$tester->execute($input);
}
public function testExecuteWithoutMode()
{
$kernel = new TestKernel();
$kernel->boot();
$app = new Application($kernel);
$commandMock = $this->getCommandMock();
$app->add($commandMock);
$command = $app->find('oro:translation:pack');
$command->setApplication($app);
$tester = new CommandTester($command);
$input = array('command' => $command->getName(), 'project' => 'test123');
$return = $tester->execute($input);
$this->assertEquals(1, $return);
}
/**
* @return array
*/
public function formatProvider()
{
return array(
'format do not specified, yml default' => array('yml', false),
'format specified xml expected ' => array('xml', 'xml')
);
}
/**
* Prepares command mock
* asText mocked by default in case when we don't need to mock anything
*
* @param array $methods
*
* @return \PHPUnit_Framework_MockObject_MockObject|OroTranslationPackCommand
*/
protected function getCommandMock($methods = array('asText'))
{
$commandMock = $this->getMockBuilder('Oro\Bundle\TranslationBundle\Command\OroTranslationPackCommand')
->setMethods($methods);
return $commandMock->getMock();
}
/**
* @param $class
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
protected function getNewMock($class)
{
return $this->getMock($class, [], [], '', false);
}
}
| mit |
lucas-ez/inaturalist | db/migrate/20150319205049_add_some_indices.rb | 233 | class AddSomeIndices < ActiveRecord::Migration
def change
add_index :updates, :created_at
add_index :observations, :created_at
add_index :observations, :observed_on
add_index :identifications, :created_at
end
end
| mit |
pingdomserver/scout-plugins | freeradius_stats/test.rb | 1566 | require File.expand_path('../../test_helper.rb', __FILE__)
require File.expand_path('../freeradius_stats.rb', __FILE__)
class FreeradiusStatsTest < Test::Unit::TestCase
def setup
@options = parse_defaults("freeradius_stats")
end
def teardown
end
def test_clean_run
# Stub the plugin instance where necessary and run
# @plugin=PluginName.new(last_run, memory, options)
# date hash hash
@plugin=FreeradiusStats.new(nil,{},@options)
@plugin.returns(FIXTURES[:stats]).once
res = @plugin.run()
# assertions
assert res[:alerts].empty?
assert res[:errors].empty?
end
def test_alert
@plugin=FreeradiusStats.new(nil,{},@options)
@plugin.returns(FIXTURES[:stats_alert]).once
res = @plugin.run()
# assertions
assert_equal 1, res[:alerts].size
assert res[:errors].empty?
end
FIXTURES=YAML.load(<<-EOS)
:stats: |
Received response ID 230, code 2, length = 140
FreeRADIUS-Total-Access-Requests = 21287
FreeRADIUS-Total-Access-Accepts = 20677
FreeRADIUS-Total-Access-Rejects = 677
FreeRADIUS-Total-Access-Challenges = 0
FreeRADIUS-Total-Auth-Responses = 21354
FreeRADIUS-Total-Auth-Duplicate-Requests = 0
FreeRADIUS-Total-Auth-Malformed-Requests = 0
FreeRADIUS-Total-Auth-Invalid-Requests = 0
FreeRADIUS-Total-Auth-Dropped-Requests = 0
FreeRADIUS-Total-Auth-Unknown-Types = 0
:stats_alert: |
radclient: no response from server for ID 15 socket 3
EOS
end | mit |
Jiayili1/corefx | src/System.IO.Ports/tests/SerialPort/Read_char_int_int_Generic.cs | 18965 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Read_char_int_int_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
//The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
//The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultCharArraySize = 1;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize);
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
char[] actualChars = new char[numRndBytesPairty + 1];
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
com1.Read(actualChars, 0, actualChars.Length);
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != actualChars[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]);
}
}
if (1 < com1.BytesToRead)
{
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
VerifyBytesToRead(1);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
//Warm up read method
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
byte expectedByte;
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
//Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedChars[parityErrorIndex] = (char)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesToRead];
char[] expectedChars;
ASCIIEncoding encoding = new ASCIIEncoding();
//Genrate random characters
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize)
{
char[] rcvBuffer = new char[rcvBufferSize];
char[] buffer = new char[expectedChars.Length];
int totalBytesRead;
int totalCharsRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
totalCharsRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
int charsRead;
try
{
charsRead = com1.Read(rcvBuffer, 0, rcvBufferSize);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead);
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) ||
(bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead);
totalBytesRead += bytesRead;
totalCharsRead += charsRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead,
com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]);
}
}
}
#endregion
}
}
| mit |
johantenbroeke/zoekr | zoekr/Pods/FlickrKit/Classes/Model/Generated/Groups/Discuss/Replies/FKFlickrGroupsDiscussRepliesGetInfo.h | 2510 | //
// FKFlickrGroupsDiscussRepliesGetInfo.h
// FlickrKit
//
// Generated by FKAPIBuilder.
// Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com
//
// DO NOT MODIFY THIS FILE - IT IS MACHINE GENERATED
#import "FKFlickrAPIMethod.h"
typedef NS_ENUM(NSInteger, FKFlickrGroupsDiscussRepliesGetInfoError) {
FKFlickrGroupsDiscussRepliesGetInfoError_TopicNotFound = 1, /* The topic_id is invalid */
FKFlickrGroupsDiscussRepliesGetInfoError_ReplyNotFound = 2, /* The reply_id is invalid */
FKFlickrGroupsDiscussRepliesGetInfoError_InvalidAPIKey = 100, /* The API key passed was not valid or has expired. */
FKFlickrGroupsDiscussRepliesGetInfoError_ServiceCurrentlyUnavailable = 105, /* The requested service is temporarily unavailable. */
FKFlickrGroupsDiscussRepliesGetInfoError_WriteOperationFailed = 106, /* The requested operation failed due to a temporary issue. */
FKFlickrGroupsDiscussRepliesGetInfoError_FormatXXXNotFound = 111, /* The requested response format was not found. */
FKFlickrGroupsDiscussRepliesGetInfoError_MethodXXXNotFound = 112, /* The requested method was not found. */
FKFlickrGroupsDiscussRepliesGetInfoError_InvalidSOAPEnvelope = 114, /* The SOAP envelope send in the request could not be parsed. */
FKFlickrGroupsDiscussRepliesGetInfoError_InvalidXMLRPCMethodCall = 115, /* The XML-RPC request document could not be parsed. */
FKFlickrGroupsDiscussRepliesGetInfoError_BadURLFound = 116, /* One or more arguments contained a URL that has been used for abuse on Flickr. */
};
/*
Get information on a group topic reply.
Response:
<?xml version="1.0" encoding="utf-8" ?>
<rsp stat="ok">
<reply id="72157607082559968" author="30134652@N05" authorname="JAMAL'S ACCOUNT" is_pro="0" role="admin" iconserver="0" iconfarm="0" can_edit="1" can_delete="1" datecreate="1337975921" lastedit="0">
<message>...well, too bad.</message>
</reply>
</rsp>
*/
@interface FKFlickrGroupsDiscussRepliesGetInfo : NSObject <FKFlickrAPIMethod>
/* Pass in the group id to where the topic belongs. Can be NSID or group alias. Making this parameter optional for legacy reasons, but it is highly recommended to pass this in to get faster performance. */
@property (nonatomic, copy) NSString *group_id; /* (Required) */
/* The ID of the topic the post is in. */
@property (nonatomic, copy) NSString *topic_id; /* (Required) */
/* The ID of the reply to fetch. */
@property (nonatomic, copy) NSString *reply_id; /* (Required) */
@end
| mit |
mwoynarski/KunstmaanBundlesCMS | src/Kunstmaan/CacheBundle/Form/Varnish/BanType.php | 844 | <?php
namespace Kunstmaan\CacheBundle\Form\Varnish;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* Class BanType.
*/
class BanType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('path', TextType::class, [
'label' => 'kunstmaan_cache.varnish.ban.path',
]);
$builder->add('allDomains', CheckboxType::class, [
'label' => 'kunstmaan_cache.varnish.ban.all_domains',
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'kunstmaan_cache_varnish_ban';
}
}
| mit |
spotify/robolectric | shadows/framework/src/main/java/org/robolectric/shadows/ShadowArrayAdapter.java | 620 | package org.robolectric.shadows;
import android.widget.ArrayAdapter;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;
@SuppressWarnings("UnusedDeclaration")
@Implements(ArrayAdapter.class)
public class ShadowArrayAdapter<T> extends ShadowBaseAdapter {
@RealObject private ArrayAdapter<T> realArrayAdapter;
public int getTextViewResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mFieldId");
}
public int getResourceId() {
return ReflectionHelpers.getField(realArrayAdapter, "mResource");
}
} | mit |
nischay13144/railscasts | spec/lib/code_formatter_spec.rb | 1988 | require File.dirname(__FILE__) + '/../spec_helper'
describe CodeFormatter do
def format(text)
CodeFormatter.new(text).to_html
end
it "determines language based on file path" do
formatter = CodeFormatter.new("")
formatter.language("unknown").should eq("unknown")
formatter.language("hello.rb").should eq("ruby")
formatter.language("hello.js").should eq("java_script")
formatter.language("hello.css").should eq("css")
formatter.language("hello.html.erb").should eq("rhtml")
formatter.language("hello.yml").should eq("yaml")
formatter.language("Gemfile").should eq("ruby")
formatter.language("app.rake").should eq("ruby")
formatter.language("foo.gemspec").should eq("ruby")
formatter.language("rails console").should eq("ruby")
formatter.language("hello.js.rjs").should eq("rjs")
formatter.language("hello.scss").should eq("css")
formatter.language("rails").should eq("ruby")
formatter.language("foo.bar ").should eq("bar")
formatter.language("foo ").should eq("foo")
formatter.language("").should eq("text")
formatter.language(nil).should eq("text")
formatter.language("0```").should eq("text")
end
it "converts to markdown" do
format("hello **world**").strip.should eq("<p>hello <strong>world</strong></p>")
end
it "hard wraps return statements" do
format("hello\nworld").strip.should eq("<p>hello<br>\nworld</p>")
end
it "autolinks a url" do
format("http://www.example.com/").strip.should eq('<p><a href="http://www.example.com/">http://www.example.com/</a></p>')
end
it "formats code block" do
# This could use some more extensive tests
format("```\nfoo\n```").strip.should include("<div class=\"code_block\">")
end
it "handle back-slashes in code block" do
# This could use some more extensive tests
format("```\nf\\'oo\n```").strip.should include("f\\'oo")
end
it "does not allow html" do
format("<img>").strip.should eq("")
end
end
| mit |
YOTOV-LIMITED/Windows-Driver-Frameworks | src/framework/shared/inc/primitives/um/mxpagedlockum.h | 2118 | /*++
Copyright (c) Microsoft Corporation
ModuleName:
MxPagedLockUm.h
Abstract:
User mode implementation of paged lock defined in
MxPagedLock.h
Author:
Revision History:
--*/
#pragma once
typedef struct {
CRITICAL_SECTION Lock;
bool Initialized;
DWORD OwnerThreadId;
} MdPagedLock;
#include "MxPagedLock.h"
FORCEINLINE
MxPagedLock::MxPagedLock(
)
{
m_Lock.Initialized = false;
m_Lock.OwnerThreadId = 0;
}
_Must_inspect_result_
FORCEINLINE
NTSTATUS
MxPagedLockNoDynam::Initialize(
)
{
if (InitializeCriticalSectionAndSpinCount(&m_Lock.Lock, 0)) {
m_Lock.Initialized = true;
return S_OK;
}
else {
DWORD err = GetLastError();
return WinErrorToNtStatus(err);
}
}
FORCEINLINE
VOID
#pragma prefast(suppress:__WARNING_UNMATCHED_DEFN, "Can't apply kernel mode annotations.");
MxPagedLockNoDynam::Acquire(
)
{
EnterCriticalSection(&m_Lock.Lock);
DWORD threadId = GetCurrentThreadId();
if (threadId == m_Lock.OwnerThreadId) {
Mx::MxAssertMsg("Recursive acquision of the lock is not allowed", FALSE);
}
m_Lock.OwnerThreadId = GetCurrentThreadId();
}
FORCEINLINE
VOID
MxPagedLockNoDynam::AcquireUnsafe(
)
{
MxPagedLockNoDynam::Acquire();
}
FORCEINLINE
BOOLEAN
#pragma prefast(suppress:__WARNING_UNMATCHED_DEFN, "Can't apply kernel mode annotations.");
MxPagedLockNoDynam::TryToAcquire(
)
{
return TryEnterCriticalSection(&m_Lock.Lock) == TRUE ? TRUE : FALSE;
}
FORCEINLINE
VOID
#pragma prefast(suppress:__WARNING_UNMATCHED_DEFN, "Can't apply kernel mode annotations.");
MxPagedLockNoDynam::Release(
)
{
m_Lock.OwnerThreadId = 0;
LeaveCriticalSection(&m_Lock.Lock);
}
FORCEINLINE
VOID
MxPagedLockNoDynam::ReleaseUnsafe(
)
{
MxPagedLockNoDynam::Release();
}
FORCEINLINE
VOID
MxPagedLockNoDynam::Uninitialize(
)
{
DeleteCriticalSection(&m_Lock.Lock);
m_Lock.Initialized = false;
}
FORCEINLINE
MxPagedLock::~MxPagedLock(
)
{
if (m_Lock.Initialized) {
this->Uninitialize();
}
}
| mit |
TelerikAcademy/JavaScript-UI-and-DOM | Practical Exams/28-March-2017/Task-3_Tabs/task/css/tabs.css | 751 | .list {
margin: 0;
padding: 0;
list-style-type: none;
font-size: 0;
}
.list .list-item {
margin: 0;
padding: 0;
font-size: 1rem
}
.tabs-control {
height: 600px;
width: 600px;
display: inline-block;
border: 1px solid black;
}
.list-titles {
background: #eee
}
.list-titles .list-item {
display: inline-block;
background: #aaa;
border-right: 1px solid black;
}
.title {
display: inline-block;
padding: 10px 25px;
font-size: 1.1em
}
.title:hover {
background-color: #777;
color: white;
cursor: pointer
}
.tab-content-toggle {
display: none
}
.content {
display: none;
padding: 5px 15px;
}
.tab-content-toggle:checked+.content {
display: block;
} | mit |
egoitzro/poedit | deps/db/docs/java/com/sleepycat/util/package-frame.html | 2168 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_03) on Fri Dec 18 17:26:35 EST 2009 -->
<TITLE>
com.sleepycat.util (Oracle - Berkeley DB Java API)
</TITLE>
<META NAME="date" CONTENT="2009-12-18">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../style.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../com/sleepycat/util/package-summary.html" target="classFrame">com.sleepycat.util</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Interfaces</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="ExceptionWrapper.html" title="interface in com.sleepycat.util" target="classFrame"><I>ExceptionWrapper</I></A></FONT></TD>
</TR>
</TABLE>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="ErrorBuffer.html" title="class in com.sleepycat.util" target="classFrame">ErrorBuffer</A>
<BR>
<A HREF="ExceptionUnwrapper.html" title="class in com.sleepycat.util" target="classFrame">ExceptionUnwrapper</A>
<BR>
<A HREF="FastInputStream.html" title="class in com.sleepycat.util" target="classFrame">FastInputStream</A>
<BR>
<A HREF="FastOutputStream.html" title="class in com.sleepycat.util" target="classFrame">FastOutputStream</A>
<BR>
<A HREF="PackedInteger.html" title="class in com.sleepycat.util" target="classFrame">PackedInteger</A>
<BR>
<A HREF="UtfOps.html" title="class in com.sleepycat.util" target="classFrame">UtfOps</A></FONT></TD>
</TR>
</TABLE>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Exceptions</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="IOExceptionWrapper.html" title="class in com.sleepycat.util" target="classFrame">IOExceptionWrapper</A>
<BR>
<A HREF="RuntimeExceptionWrapper.html" title="class in com.sleepycat.util" target="classFrame">RuntimeExceptionWrapper</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| mit |
arjes/rails | activesupport/lib/active_support/xml_mini/libxmlsax.rb | 2092 | require "libxml"
require "active_support/core_ext/object/blank"
require "stringio"
module ActiveSupport
module XmlMini_LibXMLSAX #:nodoc:
extend self
# Class that will build the hash while the XML document
# is being parsed using SAX events.
class HashBuilder
include LibXML::XML::SaxParser::Callbacks
CONTENT_KEY = "__content__".freeze
HASH_SIZE_KEY = "__hash_size__".freeze
attr_reader :hash
def current_hash
@hash_stack.last
end
def on_start_document
@hash = { CONTENT_KEY => "" }
@hash_stack = [@hash]
end
def on_end_document
@hash = @hash_stack.pop
@hash.delete(CONTENT_KEY)
end
def on_start_element(name, attrs = {})
new_hash = { CONTENT_KEY => "" }.merge!(attrs)
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
case current_hash[name]
when Array then current_hash[name] << new_hash
when Hash then current_hash[name] = [current_hash[name], new_hash]
when nil then current_hash[name] = new_hash
end
@hash_stack.push(new_hash)
end
def on_end_element(name)
if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ""
current_hash.delete(CONTENT_KEY)
end
@hash_stack.pop
end
def on_characters(string)
current_hash[CONTENT_KEY] << string
end
alias_method :on_cdata_block, :on_characters
end
attr_accessor :document_class
self.document_class = HashBuilder
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
char = data.getc
if char.nil?
{}
else
data.ungetc(char)
LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER)
parser = LibXML::XML::SaxParser.io(data)
document = self.document_class.new
parser.callbacks = document
parser.parse
document.hash
end
end
end
end
| mit |
scstauf/ajax-docs | controls/spell/changes-and-backward-compatibility/overview.md | 1728 | ---
title: Overview
page_title: Changes and Backward Compatibility Overview | RadSpell for ASP.NET AJAX Documentation
description: Overview
slug: spell/changes-and-backward-compatibility/overview
tags: overview
published: True
position: 0
---
# Changes and Backward Compatibility Overview
## Telerik RadSpell for ASP.NET AJAX
A complete list of all changes can be found on Release History page:
[http://www.telerik.com/products/aspnet-ajax/whats-new/release-history.aspx](http://www.telerik.com/products/aspnet-ajax/whats-new/release-history.aspx)
## Telerik RadSpell for ASP.NET AJAX Q3 2009
RadSpell for ASP.NET AJAX which is part of the Q3 2009 release is fully backwards compatible with its previous version (Q2 2009).
## Telerik RadSpell for ASP.NET AJAX Q2 2009
RadSpell for ASP.NET AJAX which is part of the Q2 2009 release is fully backwards compatible with its previous version (Q1 2009).
## Telerik RadSpell for ASP.NET AJAX Q1 2009
* Total redesign of the skins, which aims for a uniformity of the appearance of all controls in the suite in the cases they are used to build RIAs
* Refactoring of the CSS code to achieve better understanding, easier maintenance and handle problems with global styles
* Changes to the CSS classes, so now all controls for ASP.NET AJAX comply with a common naming convention
## Telerik RadSpell for ASP.NET AJAX Q3 2008
RadSpell for ASP.NET AJAX which is part of the Q3 2008 release is fully backwards compatible with its previous version (Q2 2008).
## Telerik RadSpell for ASP.NET AJAX Q2 2008
RadSpell for ASP.NET AJAX which is part of the Q2 2008 release is fully backwards compatible with its previous version (Q1 2008).
| mit |
scen/ionlib | src/sdk/hl2_ob/public/mathlib/vmatrix.h | 29234 | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//
// VMatrix always postmultiply vectors as in Ax = b.
// Given a set of basis vectors ((F)orward, (L)eft, (U)p), and a (T)ranslation,
// a matrix to transform a vector into that space looks like this:
// Fx Lx Ux Tx
// Fy Ly Uy Ty
// Fz Lz Uz Tz
// 0 0 0 1
// Note that concatenating matrices needs to multiply them in reverse order.
// ie: if I want to apply matrix A, B, then C, the equation needs to look like this:
// C * B * A * v
// ie:
// v = A * v;
// v = B * v;
// v = C * v;
//=============================================================================
#ifndef VMATRIX_H
#define VMATRIX_H
#ifdef _WIN32
#pragma once
#endif
#include <string.h>
#include "mathlib/vector.h"
#include "mathlib/vplane.h"
#include "mathlib/vector4d.h"
#include "mathlib/mathlib.h"
struct cplane_t;
class VMatrix
{
public:
VMatrix();
VMatrix(
vec_t m00, vec_t m01, vec_t m02, vec_t m03,
vec_t m10, vec_t m11, vec_t m12, vec_t m13,
vec_t m20, vec_t m21, vec_t m22, vec_t m23,
vec_t m30, vec_t m31, vec_t m32, vec_t m33
);
// Creates a matrix where the X axis = forward
// the Y axis = left, and the Z axis = up
VMatrix( const Vector& forward, const Vector& left, const Vector& up );
// Construct from a 3x4 matrix
VMatrix( const matrix3x4_t& matrix3x4 );
// Set the values in the matrix.
void Init(
vec_t m00, vec_t m01, vec_t m02, vec_t m03,
vec_t m10, vec_t m11, vec_t m12, vec_t m13,
vec_t m20, vec_t m21, vec_t m22, vec_t m23,
vec_t m30, vec_t m31, vec_t m32, vec_t m33
);
// Initialize from a 3x4
void Init( const matrix3x4_t& matrix3x4 );
// array access
inline float* operator[](int i)
{
return m[i];
}
inline const float* operator[](int i) const
{
return m[i];
}
// Get a pointer to m[0][0]
inline float *Base()
{
return &m[0][0];
}
inline const float *Base() const
{
return &m[0][0];
}
void SetLeft(const Vector &vLeft);
void SetUp(const Vector &vUp);
void SetForward(const Vector &vForward);
void GetBasisVectors(Vector &vForward, Vector &vLeft, Vector &vUp) const;
void SetBasisVectors(const Vector &vForward, const Vector &vLeft, const Vector &vUp);
// Get/set the translation.
Vector & GetTranslation( Vector &vTrans ) const;
void SetTranslation(const Vector &vTrans);
void PreTranslate(const Vector &vTrans);
void PostTranslate(const Vector &vTrans);
matrix3x4_t& As3x4();
const matrix3x4_t& As3x4() const;
void CopyFrom3x4( const matrix3x4_t &m3x4 );
void Set3x4( matrix3x4_t& matrix3x4 ) const;
bool operator==( const VMatrix& src ) const;
bool operator!=( const VMatrix& src ) const { return !( *this == src ); }
#ifndef VECTOR_NO_SLOW_OPERATIONS
// Access the basis vectors.
Vector GetLeft() const;
Vector GetUp() const;
Vector GetForward() const;
Vector GetTranslation() const;
#endif
// Matrix->vector operations.
public:
// Multiply by a 3D vector (same as operator*).
void V3Mul(const Vector &vIn, Vector &vOut) const;
// Multiply by a 4D vector.
void V4Mul(const Vector4D &vIn, Vector4D &vOut) const;
#ifndef VECTOR_NO_SLOW_OPERATIONS
// Applies the rotation (ignores translation in the matrix). (This just calls VMul3x3).
Vector ApplyRotation(const Vector &vVec) const;
// Multiply by a vector (divides by w, assumes input w is 1).
Vector operator*(const Vector &vVec) const;
// Multiply by the upper 3x3 part of the matrix (ie: only apply rotation).
Vector VMul3x3(const Vector &vVec) const;
// Apply the inverse (transposed) rotation (only works on pure rotation matrix)
Vector VMul3x3Transpose(const Vector &vVec) const;
// Multiply by the upper 3 rows.
Vector VMul4x3(const Vector &vVec) const;
// Apply the inverse (transposed) transformation (only works on pure rotation/translation)
Vector VMul4x3Transpose(const Vector &vVec) const;
#endif
// Matrix->plane operations.
public:
// Transform the plane. The matrix can only contain translation and rotation.
void TransformPlane( const VPlane &inPlane, VPlane &outPlane ) const;
#ifndef VECTOR_NO_SLOW_OPERATIONS
// Just calls TransformPlane and returns the result.
VPlane operator*(const VPlane &thePlane) const;
#endif
// Matrix->matrix operations.
public:
VMatrix& operator=(const VMatrix &mOther);
// Multiply two matrices (out = this * vm).
void MatrixMul( const VMatrix &vm, VMatrix &out ) const;
// Add two matrices.
const VMatrix& operator+=(const VMatrix &other);
#ifndef VECTOR_NO_SLOW_OPERATIONS
// Just calls MatrixMul and returns the result.
VMatrix operator*(const VMatrix &mOther) const;
// Add/Subtract two matrices.
VMatrix operator+(const VMatrix &other) const;
VMatrix operator-(const VMatrix &other) const;
// Negation.
VMatrix operator-() const;
// Return inverse matrix. Be careful because the results are undefined
// if the matrix doesn't have an inverse (ie: InverseGeneral returns false).
VMatrix operator~() const;
#endif
// Matrix operations.
public:
// Set to identity.
void Identity();
bool IsIdentity() const;
// Setup a matrix for origin and angles.
void SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles );
// General inverse. This may fail so check the return!
bool InverseGeneral(VMatrix &vInverse) const;
// Does a fast inverse, assuming the matrix only contains translation and rotation.
void InverseTR( VMatrix &mRet ) const;
// Usually used for debug checks. Returns true if the upper 3x3 contains
// unit vectors and they are all orthogonal.
bool IsRotationMatrix() const;
#ifndef VECTOR_NO_SLOW_OPERATIONS
// This calls the other InverseTR and returns the result.
VMatrix InverseTR() const;
// Get the scale of the matrix's basis vectors.
Vector GetScale() const;
// (Fast) multiply by a scaling matrix setup from vScale.
VMatrix Scale(const Vector &vScale);
// Normalize the basis vectors.
VMatrix NormalizeBasisVectors() const;
// Transpose.
VMatrix Transpose() const;
// Transpose upper-left 3x3.
VMatrix Transpose3x3() const;
#endif
public:
// The matrix.
vec_t m[4][4];
};
//-----------------------------------------------------------------------------
// Helper functions.
//-----------------------------------------------------------------------------
#ifndef VECTOR_NO_SLOW_OPERATIONS
// Setup an identity matrix.
VMatrix SetupMatrixIdentity();
// Setup as a scaling matrix.
VMatrix SetupMatrixScale(const Vector &vScale);
// Setup a translation matrix.
VMatrix SetupMatrixTranslation(const Vector &vTranslation);
// Setup a matrix to reflect around the plane.
VMatrix SetupMatrixReflection(const VPlane &thePlane);
// Setup a matrix to project from vOrigin onto thePlane.
VMatrix SetupMatrixProjection(const Vector &vOrigin, const VPlane &thePlane);
// Setup a matrix to rotate the specified amount around the specified axis.
VMatrix SetupMatrixAxisRot(const Vector &vAxis, vec_t fDegrees);
// Setup a matrix from euler angles. Just sets identity and calls MatrixAngles.
VMatrix SetupMatrixAngles(const QAngle &vAngles);
// Setup a matrix for origin and angles.
VMatrix SetupMatrixOrgAngles(const Vector &origin, const QAngle &vAngles);
#endif
#define VMatToString(mat) (static_cast<const char *>(CFmtStr("[ (%f, %f, %f), (%f, %f, %f), (%f, %f, %f), (%f, %f, %f) ]", mat.m[0][0], mat.m[0][1], mat.m[0][2], mat.m[0][3], mat.m[1][0], mat.m[1][1], mat.m[1][2], mat.m[1][3], mat.m[2][0], mat.m[2][1], mat.m[2][2], mat.m[2][3], mat.m[3][0], mat.m[3][1], mat.m[3][2], mat.m[3][3] ))) // ** Note: this generates a temporary, don't hold reference!
//-----------------------------------------------------------------------------
// Returns the point at the intersection on the 3 planes.
// Returns false if it can't be solved (2 or more planes are parallel).
//-----------------------------------------------------------------------------
bool PlaneIntersection( const VPlane &vp1, const VPlane &vp2, const VPlane &vp3, Vector &vOut );
//-----------------------------------------------------------------------------
// These methods are faster. Use them if you want faster code
//-----------------------------------------------------------------------------
void MatrixSetIdentity( VMatrix &dst );
void MatrixTranspose( const VMatrix& src, VMatrix& dst );
void MatrixCopy( const VMatrix& src, VMatrix& dst );
void MatrixMultiply( const VMatrix& src1, const VMatrix& src2, VMatrix& dst );
// Accessors
void MatrixGetColumn( const VMatrix &src, int nCol, Vector *pColumn );
void MatrixSetColumn( VMatrix &src, int nCol, const Vector &column );
void MatrixGetRow( const VMatrix &src, int nCol, Vector *pColumn );
void MatrixSetRow( VMatrix &src, int nCol, const Vector &column );
// Vector3DMultiply treats src2 as if it's a direction vector
void Vector3DMultiply( const VMatrix& src1, const Vector& src2, Vector& dst );
// Vector3DMultiplyPosition treats src2 as if it's a point (adds the translation)
inline void Vector3DMultiplyPosition( const VMatrix& src1, const VectorByValue src2, Vector& dst );
// Vector3DMultiplyPositionProjective treats src2 as if it's a point
// and does the perspective divide at the end
void Vector3DMultiplyPositionProjective( const VMatrix& src1, const Vector &src2, Vector& dst );
// Vector3DMultiplyPosition treats src2 as if it's a direction
// and does the perspective divide at the end
// NOTE: src1 had better be an inverse transpose to use this correctly
void Vector3DMultiplyProjective( const VMatrix& src1, const Vector &src2, Vector& dst );
void Vector4DMultiply( const VMatrix& src1, const Vector4D& src2, Vector4D& dst );
// Same as Vector4DMultiply except that src2 has an implicit W of 1
void Vector4DMultiplyPosition( const VMatrix& src1, const Vector &src2, Vector4D& dst );
// Multiplies the vector by the transpose of the matrix
void Vector3DMultiplyTranspose( const VMatrix& src1, const Vector& src2, Vector& dst );
void Vector4DMultiplyTranspose( const VMatrix& src1, const Vector4D& src2, Vector4D& dst );
// Transform a plane
void MatrixTransformPlane( const VMatrix &src, const cplane_t &inPlane, cplane_t &outPlane );
// Transform a plane that has an axis-aligned normal
void MatrixTransformAxisAlignedPlane( const VMatrix &src, int nDim, float flSign, float flDist, cplane_t &outPlane );
void MatrixBuildTranslation( VMatrix& dst, float x, float y, float z );
void MatrixBuildTranslation( VMatrix& dst, const Vector &translation );
inline void MatrixTranslate( VMatrix& dst, const Vector &translation )
{
VMatrix matTranslation, temp;
MatrixBuildTranslation( matTranslation, translation );
MatrixMultiply( dst, matTranslation, temp );
dst = temp;
}
void MatrixBuildRotationAboutAxis( VMatrix& dst, const Vector& vAxisOfRot, float angleDegrees );
void MatrixBuildRotateZ( VMatrix& dst, float angleDegrees );
inline void MatrixRotate( VMatrix& dst, const Vector& vAxisOfRot, float angleDegrees )
{
VMatrix rotation, temp;
MatrixBuildRotationAboutAxis( rotation, vAxisOfRot, angleDegrees );
MatrixMultiply( dst, rotation, temp );
dst = temp;
}
// Builds a rotation matrix that rotates one direction vector into another
void MatrixBuildRotation( VMatrix &dst, const Vector& initialDirection, const Vector& finalDirection );
// Builds a scale matrix
void MatrixBuildScale( VMatrix &dst, float x, float y, float z );
void MatrixBuildScale( VMatrix &dst, const Vector& scale );
// Build a perspective matrix.
// zNear and zFar are assumed to be positive.
// You end up looking down positive Z, X is to the right, Y is up.
// X range: [0..1]
// Y range: [0..1]
// Z range: [0..1]
void MatrixBuildPerspective( VMatrix &dst, float fovX, float fovY, float zNear, float zFar );
//-----------------------------------------------------------------------------
// Given a projection matrix, take the extremes of the space in transformed into world space and
// get a bounding box.
//-----------------------------------------------------------------------------
void CalculateAABBFromProjectionMatrix( const VMatrix &worldToVolume, Vector *pMins, Vector *pMaxs );
//-----------------------------------------------------------------------------
// Given a projection matrix, take the extremes of the space in transformed into world space and
// get a bounding sphere.
//-----------------------------------------------------------------------------
void CalculateSphereFromProjectionMatrix( const VMatrix &worldToVolume, Vector *pCenter, float *pflRadius );
//-----------------------------------------------------------------------------
// Given an inverse projection matrix, take the extremes of the space in transformed into world space and
// get a bounding box.
//-----------------------------------------------------------------------------
void CalculateAABBFromProjectionMatrixInverse( const VMatrix &volumeToWorld, Vector *pMins, Vector *pMaxs );
//-----------------------------------------------------------------------------
// Given an inverse projection matrix, take the extremes of the space in transformed into world space and
// get a bounding sphere.
//-----------------------------------------------------------------------------
void CalculateSphereFromProjectionMatrixInverse( const VMatrix &volumeToWorld, Vector *pCenter, float *pflRadius );
//-----------------------------------------------------------------------------
// Calculate frustum planes given a clip->world space transform.
//-----------------------------------------------------------------------------
void FrustumPlanesFromMatrix( const VMatrix &clipToWorld, Frustum_t &frustum );
//-----------------------------------------------------------------------------
// Setup a matrix from euler angles.
//-----------------------------------------------------------------------------
void MatrixFromAngles( const QAngle& vAngles, VMatrix& dst );
//-----------------------------------------------------------------------------
// Creates euler angles from a matrix
//-----------------------------------------------------------------------------
void MatrixToAngles( const VMatrix& src, QAngle& vAngles );
//-----------------------------------------------------------------------------
// Does a fast inverse, assuming the matrix only contains translation and rotation.
//-----------------------------------------------------------------------------
void MatrixInverseTR( const VMatrix& src, VMatrix &dst );
//-----------------------------------------------------------------------------
// Inverts any matrix at all
//-----------------------------------------------------------------------------
bool MatrixInverseGeneral(const VMatrix& src, VMatrix& dst);
//-----------------------------------------------------------------------------
// Computes the inverse transpose
//-----------------------------------------------------------------------------
void MatrixInverseTranspose( const VMatrix& src, VMatrix& dst );
//-----------------------------------------------------------------------------
// VMatrix inlines.
//-----------------------------------------------------------------------------
inline VMatrix::VMatrix()
{
}
inline VMatrix::VMatrix(
vec_t m00, vec_t m01, vec_t m02, vec_t m03,
vec_t m10, vec_t m11, vec_t m12, vec_t m13,
vec_t m20, vec_t m21, vec_t m22, vec_t m23,
vec_t m30, vec_t m31, vec_t m32, vec_t m33)
{
Init(
m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33
);
}
inline VMatrix::VMatrix( const matrix3x4_t& matrix3x4 )
{
Init( matrix3x4 );
}
//-----------------------------------------------------------------------------
// Creates a matrix where the X axis = forward
// the Y axis = left, and the Z axis = up
//-----------------------------------------------------------------------------
inline VMatrix::VMatrix( const Vector& xAxis, const Vector& yAxis, const Vector& zAxis )
{
Init(
xAxis.x, yAxis.x, zAxis.x, 0.0f,
xAxis.y, yAxis.y, zAxis.y, 0.0f,
xAxis.z, yAxis.z, zAxis.z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
);
}
inline void VMatrix::Init(
vec_t m00, vec_t m01, vec_t m02, vec_t m03,
vec_t m10, vec_t m11, vec_t m12, vec_t m13,
vec_t m20, vec_t m21, vec_t m22, vec_t m23,
vec_t m30, vec_t m31, vec_t m32, vec_t m33
)
{
m[0][0] = m00;
m[0][1] = m01;
m[0][2] = m02;
m[0][3] = m03;
m[1][0] = m10;
m[1][1] = m11;
m[1][2] = m12;
m[1][3] = m13;
m[2][0] = m20;
m[2][1] = m21;
m[2][2] = m22;
m[2][3] = m23;
m[3][0] = m30;
m[3][1] = m31;
m[3][2] = m32;
m[3][3] = m33;
}
//-----------------------------------------------------------------------------
// Initialize from a 3x4
//-----------------------------------------------------------------------------
inline void VMatrix::Init( const matrix3x4_t& matrix3x4 )
{
memcpy(m, matrix3x4.Base(), sizeof( matrix3x4_t ) );
m[3][0] = 0.0f;
m[3][1] = 0.0f;
m[3][2] = 0.0f;
m[3][3] = 1.0f;
}
//-----------------------------------------------------------------------------
// Methods related to the basis vectors of the matrix
//-----------------------------------------------------------------------------
#ifndef VECTOR_NO_SLOW_OPERATIONS
inline Vector VMatrix::GetForward() const
{
return Vector(m[0][0], m[1][0], m[2][0]);
}
inline Vector VMatrix::GetLeft() const
{
return Vector(m[0][1], m[1][1], m[2][1]);
}
inline Vector VMatrix::GetUp() const
{
return Vector(m[0][2], m[1][2], m[2][2]);
}
#endif
inline void VMatrix::SetForward(const Vector &vForward)
{
m[0][0] = vForward.x;
m[1][0] = vForward.y;
m[2][0] = vForward.z;
}
inline void VMatrix::SetLeft(const Vector &vLeft)
{
m[0][1] = vLeft.x;
m[1][1] = vLeft.y;
m[2][1] = vLeft.z;
}
inline void VMatrix::SetUp(const Vector &vUp)
{
m[0][2] = vUp.x;
m[1][2] = vUp.y;
m[2][2] = vUp.z;
}
inline void VMatrix::GetBasisVectors(Vector &vForward, Vector &vLeft, Vector &vUp) const
{
vForward.Init( m[0][0], m[1][0], m[2][0] );
vLeft.Init( m[0][1], m[1][1], m[2][1] );
vUp.Init( m[0][2], m[1][2], m[2][2] );
}
inline void VMatrix::SetBasisVectors(const Vector &vForward, const Vector &vLeft, const Vector &vUp)
{
SetForward(vForward);
SetLeft(vLeft);
SetUp(vUp);
}
//-----------------------------------------------------------------------------
// Methods related to the translation component of the matrix
//-----------------------------------------------------------------------------
#ifndef VECTOR_NO_SLOW_OPERATIONS
inline Vector VMatrix::GetTranslation() const
{
return Vector(m[0][3], m[1][3], m[2][3]);
}
#endif
inline Vector& VMatrix::GetTranslation( Vector &vTrans ) const
{
vTrans.x = m[0][3];
vTrans.y = m[1][3];
vTrans.z = m[2][3];
return vTrans;
}
inline void VMatrix::SetTranslation(const Vector &vTrans)
{
m[0][3] = vTrans.x;
m[1][3] = vTrans.y;
m[2][3] = vTrans.z;
}
//-----------------------------------------------------------------------------
// appply translation to this matrix in the input space
//-----------------------------------------------------------------------------
inline void VMatrix::PreTranslate(const Vector &vTrans)
{
Vector tmp;
Vector3DMultiplyPosition( *this, vTrans, tmp );
m[0][3] = tmp.x;
m[1][3] = tmp.y;
m[2][3] = tmp.z;
}
//-----------------------------------------------------------------------------
// appply translation to this matrix in the output space
//-----------------------------------------------------------------------------
inline void VMatrix::PostTranslate(const Vector &vTrans)
{
m[0][3] += vTrans.x;
m[1][3] += vTrans.y;
m[2][3] += vTrans.z;
}
inline const matrix3x4_t& VMatrix::As3x4() const
{
return *((const matrix3x4_t*)this);
}
inline matrix3x4_t& VMatrix::As3x4()
{
return *((matrix3x4_t*)this);
}
inline void VMatrix::CopyFrom3x4( const matrix3x4_t &m3x4 )
{
memcpy( m, m3x4.Base(), sizeof( matrix3x4_t ) );
m[3][0] = m[3][1] = m[3][2] = 0;
m[3][3] = 1;
}
inline void VMatrix::Set3x4( matrix3x4_t& matrix3x4 ) const
{
memcpy(matrix3x4.Base(), m, sizeof( matrix3x4_t ) );
}
//-----------------------------------------------------------------------------
// Matrix math operations
//-----------------------------------------------------------------------------
inline const VMatrix& VMatrix::operator+=(const VMatrix &other)
{
for(int i=0; i < 4; i++)
{
for(int j=0; j < 4; j++)
{
m[i][j] += other.m[i][j];
}
}
return *this;
}
#ifndef VECTOR_NO_SLOW_OPERATIONS
inline VMatrix VMatrix::operator+(const VMatrix &other) const
{
VMatrix ret;
for(int i=0; i < 16; i++)
{
((float*)ret.m)[i] = ((float*)m)[i] + ((float*)other.m)[i];
}
return ret;
}
inline VMatrix VMatrix::operator-(const VMatrix &other) const
{
VMatrix ret;
for(int i=0; i < 4; i++)
{
for(int j=0; j < 4; j++)
{
ret.m[i][j] = m[i][j] - other.m[i][j];
}
}
return ret;
}
inline VMatrix VMatrix::operator-() const
{
VMatrix ret;
for( int i=0; i < 16; i++ )
{
((float*)ret.m)[i] = ((float*)m)[i];
}
return ret;
}
#endif // VECTOR_NO_SLOW_OPERATIONS
//-----------------------------------------------------------------------------
// Vector transformation
//-----------------------------------------------------------------------------
#ifndef VECTOR_NO_SLOW_OPERATIONS
inline Vector VMatrix::operator*(const Vector &vVec) const
{
Vector vRet;
vRet.x = m[0][0]*vVec.x + m[0][1]*vVec.y + m[0][2]*vVec.z + m[0][3];
vRet.y = m[1][0]*vVec.x + m[1][1]*vVec.y + m[1][2]*vVec.z + m[1][3];
vRet.z = m[2][0]*vVec.x + m[2][1]*vVec.y + m[2][2]*vVec.z + m[2][3];
return vRet;
}
inline Vector VMatrix::VMul4x3(const Vector &vVec) const
{
Vector vResult;
Vector3DMultiplyPosition( *this, vVec, vResult );
return vResult;
}
inline Vector VMatrix::VMul4x3Transpose(const Vector &vVec) const
{
Vector tmp = vVec;
tmp.x -= m[0][3];
tmp.y -= m[1][3];
tmp.z -= m[2][3];
return Vector(
m[0][0]*tmp.x + m[1][0]*tmp.y + m[2][0]*tmp.z,
m[0][1]*tmp.x + m[1][1]*tmp.y + m[2][1]*tmp.z,
m[0][2]*tmp.x + m[1][2]*tmp.y + m[2][2]*tmp.z
);
}
inline Vector VMatrix::VMul3x3(const Vector &vVec) const
{
return Vector(
m[0][0]*vVec.x + m[0][1]*vVec.y + m[0][2]*vVec.z,
m[1][0]*vVec.x + m[1][1]*vVec.y + m[1][2]*vVec.z,
m[2][0]*vVec.x + m[2][1]*vVec.y + m[2][2]*vVec.z
);
}
inline Vector VMatrix::VMul3x3Transpose(const Vector &vVec) const
{
return Vector(
m[0][0]*vVec.x + m[1][0]*vVec.y + m[2][0]*vVec.z,
m[0][1]*vVec.x + m[1][1]*vVec.y + m[2][1]*vVec.z,
m[0][2]*vVec.x + m[1][2]*vVec.y + m[2][2]*vVec.z
);
}
#endif // VECTOR_NO_SLOW_OPERATIONS
inline void VMatrix::V3Mul(const Vector &vIn, Vector &vOut) const
{
vec_t rw;
rw = 1.0f / (m[3][0]*vIn.x + m[3][1]*vIn.y + m[3][2]*vIn.z + m[3][3]);
vOut.x = (m[0][0]*vIn.x + m[0][1]*vIn.y + m[0][2]*vIn.z + m[0][3]) * rw;
vOut.y = (m[1][0]*vIn.x + m[1][1]*vIn.y + m[1][2]*vIn.z + m[1][3]) * rw;
vOut.z = (m[2][0]*vIn.x + m[2][1]*vIn.y + m[2][2]*vIn.z + m[2][3]) * rw;
}
inline void VMatrix::V4Mul(const Vector4D &vIn, Vector4D &vOut) const
{
vOut[0] = m[0][0]*vIn[0] + m[0][1]*vIn[1] + m[0][2]*vIn[2] + m[0][3]*vIn[3];
vOut[1] = m[1][0]*vIn[0] + m[1][1]*vIn[1] + m[1][2]*vIn[2] + m[1][3]*vIn[3];
vOut[2] = m[2][0]*vIn[0] + m[2][1]*vIn[1] + m[2][2]*vIn[2] + m[2][3]*vIn[3];
vOut[3] = m[3][0]*vIn[0] + m[3][1]*vIn[1] + m[3][2]*vIn[2] + m[3][3]*vIn[3];
}
//-----------------------------------------------------------------------------
// Plane transformation
//-----------------------------------------------------------------------------
inline void VMatrix::TransformPlane( const VPlane &inPlane, VPlane &outPlane ) const
{
Vector vTrans;
Vector3DMultiply( *this, inPlane.m_Normal, outPlane.m_Normal );
outPlane.m_Dist = inPlane.m_Dist * DotProduct( outPlane.m_Normal, outPlane.m_Normal );
outPlane.m_Dist += DotProduct( outPlane.m_Normal, GetTranslation( vTrans ) );
}
//-----------------------------------------------------------------------------
// Other random stuff
//-----------------------------------------------------------------------------
inline void VMatrix::Identity()
{
MatrixSetIdentity( *this );
}
inline bool VMatrix::IsIdentity() const
{
return
m[0][0] == 1.0f && m[0][1] == 0.0f && m[0][2] == 0.0f && m[0][3] == 0.0f &&
m[1][0] == 0.0f && m[1][1] == 1.0f && m[1][2] == 0.0f && m[1][3] == 0.0f &&
m[2][0] == 0.0f && m[2][1] == 0.0f && m[2][2] == 1.0f && m[2][3] == 0.0f &&
m[3][0] == 0.0f && m[3][1] == 0.0f && m[3][2] == 0.0f && m[3][3] == 1.0f;
}
#ifndef VECTOR_NO_SLOW_OPERATIONS
inline Vector VMatrix::ApplyRotation(const Vector &vVec) const
{
return VMul3x3(vVec);
}
inline VMatrix VMatrix::operator~() const
{
VMatrix mRet;
InverseGeneral(mRet);
return mRet;
}
#endif
//-----------------------------------------------------------------------------
// Accessors
//-----------------------------------------------------------------------------
inline void MatrixGetColumn( const VMatrix &src, int nCol, Vector *pColumn )
{
Assert( (nCol >= 0) && (nCol <= 3) );
pColumn->x = src[0][nCol];
pColumn->y = src[1][nCol];
pColumn->z = src[2][nCol];
}
inline void MatrixSetColumn( VMatrix &src, int nCol, const Vector &column )
{
Assert( (nCol >= 0) && (nCol <= 3) );
src.m[0][nCol] = column.x;
src.m[1][nCol] = column.y;
src.m[2][nCol] = column.z;
}
inline void MatrixGetRow( const VMatrix &src, int nRow, Vector *pRow )
{
Assert( (nRow >= 0) && (nRow <= 3) );
*pRow = *(Vector*)src[nRow];
}
inline void MatrixSetRow( VMatrix &dst, int nRow, const Vector &row )
{
Assert( (nRow >= 0) && (nRow <= 3) );
*(Vector*)dst[nRow] = row;
}
//-----------------------------------------------------------------------------
// Vector3DMultiplyPosition treats src2 as if it's a point (adds the translation)
//-----------------------------------------------------------------------------
// NJS: src2 is passed in as a full vector rather than a reference to prevent the need
// for 2 branches and a potential copy in the body. (ie, handling the case when the src2
// reference is the same as the dst reference ).
inline void Vector3DMultiplyPosition( const VMatrix& src1, const VectorByValue src2, Vector& dst )
{
dst[0] = src1[0][0] * src2.x + src1[0][1] * src2.y + src1[0][2] * src2.z + src1[0][3];
dst[1] = src1[1][0] * src2.x + src1[1][1] * src2.y + src1[1][2] * src2.z + src1[1][3];
dst[2] = src1[2][0] * src2.x + src1[2][1] * src2.y + src1[2][2] * src2.z + src1[2][3];
}
//-----------------------------------------------------------------------------
// Transform a plane that has an axis-aligned normal
//-----------------------------------------------------------------------------
inline void MatrixTransformAxisAlignedPlane( const VMatrix &src, int nDim, float flSign, float flDist, cplane_t &outPlane )
{
// See MatrixTransformPlane in the .cpp file for an explanation of the algorithm.
MatrixGetColumn( src, nDim, &outPlane.normal );
outPlane.normal *= flSign;
outPlane.dist = flDist * DotProduct( outPlane.normal, outPlane.normal );
// NOTE: Writing this out by hand because it doesn't inline (inline depth isn't large enough)
// This should read outPlane.dist += DotProduct( outPlane.normal, src.GetTranslation );
outPlane.dist += outPlane.normal.x * src.m[0][3] + outPlane.normal.y * src.m[1][3] + outPlane.normal.z * src.m[2][3];
}
//-----------------------------------------------------------------------------
// Matrix equality test
//-----------------------------------------------------------------------------
inline bool MatricesAreEqual( const VMatrix &src1, const VMatrix &src2, float flTolerance )
{
for ( int i = 0; i < 3; ++i )
{
for ( int j = 0; j < 3; ++j )
{
if ( fabs( src1[i][j] - src2[i][j] ) > flTolerance )
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void MatrixBuildOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar );
void MatrixBuildPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar );
void MatrixBuildPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right );
inline void MatrixOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar )
{
VMatrix mat;
MatrixBuildOrtho( mat, left, top, right, bottom, zNear, zFar );
VMatrix temp;
MatrixMultiply( dst, mat, temp );
dst = temp;
}
inline void MatrixPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar )
{
VMatrix mat;
MatrixBuildPerspectiveX( mat, flFovX, flAspect, flZNear, flZFar );
VMatrix temp;
MatrixMultiply( dst, mat, temp );
dst = temp;
}
inline void MatrixPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right )
{
VMatrix mat;
MatrixBuildPerspectiveOffCenterX( mat, flFovX, flAspect, flZNear, flZFar, bottom, top, left, right );
VMatrix temp;
MatrixMultiply( dst, mat, temp );
dst = temp;
}
#endif
| mit |
dwaynebailey/poedit | deps/db/docs/java/com/sleepycat/persist/class-use/DatabaseNamer.html | 10075 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_03) on Fri Dec 18 17:26:37 EST 2009 -->
<TITLE>
Uses of Interface com.sleepycat.persist.DatabaseNamer (Oracle - Berkeley DB Java API)
</TITLE>
<META NAME="date" CONTENT="2009-12-18">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../style.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.sleepycat.persist.DatabaseNamer (Oracle - Berkeley DB Java API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB</b><br><font size="-1"> version 4.8.26</font></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sleepycat/persist//class-useDatabaseNamer.html" target="_top"><B>FRAMES</B></A>
<A HREF="DatabaseNamer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>com.sleepycat.persist.DatabaseNamer</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.sleepycat.persist"><B>com.sleepycat.persist</B></A></TD>
<TD>The Direct Persistence Layer (DPL) adds a persistent object model to the
Berkeley DB transactional engine. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.sleepycat.persist"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A> in <A HREF="../../../../com/sleepycat/persist/package-summary.html">com.sleepycat.persist</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../com/sleepycat/persist/package-summary.html">com.sleepycat.persist</A> declared as <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></CODE></FONT></TD>
<TD><CODE><B>DatabaseNamer.</B><B><A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html#DEFAULT">DEFAULT</A></B></CODE>
<BR>
The default database namer.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../com/sleepycat/persist/package-summary.html">com.sleepycat.persist</A> that return <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></CODE></FONT></TD>
<TD><CODE><B>StoreConfig.</B><B><A HREF="../../../../com/sleepycat/persist/StoreConfig.html#getDatabaseNamer()">getDatabaseNamer</A></B>()</CODE>
<BR>
Returns the object reponsible for naming of files and databases.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../com/sleepycat/persist/package-summary.html">com.sleepycat.persist</A> with parameters of type <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>StoreConfig.</B><B><A HREF="../../../../com/sleepycat/persist/StoreConfig.html#setDatabaseNamer(com.sleepycat.persist.DatabaseNamer)">setDatabaseNamer</A></B>(<A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist">DatabaseNamer</A> databaseNamer)</CODE>
<BR>
Specifies the object reponsible for naming of files and databases.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../com/sleepycat/persist/DatabaseNamer.html" title="interface in com.sleepycat.persist"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB</b><br><font size="-1"> version 4.8.26</font></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?com/sleepycat/persist//class-useDatabaseNamer.html" target="_top"><B>FRAMES</B></A>
<A HREF="DatabaseNamer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<font size=1>Copyright (c) 1996-2009 Oracle. All rights reserved.</font>
</BODY>
</HTML>
| mit |
vijayanandau/KnowledgeShare | makahiki/apps/widgets/prizes/tests/individual_prize_tests.py | 5225 | """Individual test"""
import datetime
from django.test import TransactionTestCase
from django.contrib.auth.models import User
from apps.managers.player_mgr.models import Profile
from apps.utils import test_utils
from apps.managers.challenge_mgr.models import RoundSetting
class OverallPrizeTest(TransactionTestCase):
"""
Tests awarding a prize to the individual overall points winner.
"""
def setUp(self):
"""
Sets up a test individual prize for the rest of the tests.
This prize is not saved, as the round field is not yet set.
"""
self.prize = test_utils.setup_prize(award_to="individual_overall",
competition_type="points")
self.current_round = "Round 1"
test_utils.set_competition_round()
# Create test users.
self.users = [User.objects.create_user("test%d" % i, "test@test.com") for i in range(0, 3)]
def testNumAwarded(self):
"""
Simple test to check that the number of prizes to be awarded is one.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
self.assertEqual(self.prize.num_awarded(), 1,
"This prize should not be awarded to more than one user.")
def testRoundLeader(self):
"""
Tests that we can retrieve the overall individual points leader for a round prize.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
# Test one user
profile = self.users[0].get_profile()
top_points = Profile.objects.all()[0].points()
profile.add_points(top_points + 1,
datetime.datetime.today() - datetime.timedelta(minutes=1),
"test")
profile.save()
self.assertEqual(self.prize.leader(), profile,
"Current prize leader is not the leading user.")
# Have another user move ahead in points
profile2 = self.users[1].get_profile()
profile2.add_points(profile.points() + 1, datetime.datetime.today(), "test")
profile2.save()
self.assertEqual(self.prize.leader(), profile2, "User 2 should be the leading profile.")
# Have this user get the same amount of points, but an earlier award date.
profile3 = self.users[2].get_profile()
profile3.add_points(profile2.points(),
datetime.datetime.today() - datetime.timedelta(minutes=1), "test")
profile3.save()
self.assertEqual(self.prize.leader(), profile2,
"User 2 should still be the leading profile.")
def tearDown(self):
"""
Deletes the created image file in prizes.
"""
self.prize.image.delete()
self.prize.delete()
class TeamPrizeTest(TransactionTestCase):
"""
Tests awarding a prize to the individual on each team with the most points.
"""
def setUp(self):
"""
Sets up a test individual prize for the rest of the tests.
This prize is not saved, as the round field is not yet set.
"""
self.prize = test_utils.setup_prize(award_to="individual_team", competition_type="points")
self.current_round = "Round 1"
test_utils.set_competition_round()
test_utils.create_teams(self)
def testNumAwarded(self):
"""
Tests that the number of prizes awarded corresponds to the number of teams.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
self.assertEqual(self.prize.num_awarded(), len(self.teams),
"This should correspond to the number of teams.")
def testRoundLeader(self):
"""
Tests that we can retrieve the overall individual points leader for a round prize.
"""
self.prize.round = RoundSetting.objects.get(name="Round 1")
self.prize.save()
# Test one user
profile = self.users[0].get_profile()
profile.add_points(10, datetime.datetime.today(), "test")
profile.save()
self.assertEqual(self.prize.leader(team=profile.team), profile,
"Current prize leader is not the leading user.")
# Have a user on the same team move ahead in points.
profile3 = self.users[2].get_profile()
profile3.add_points(11, datetime.datetime.today(), "test")
profile3.save()
self.assertEqual(self.prize.leader(team=profile.team), profile3,
"User 3 should be the the leader.")
# Try a user on a different team.
profile2 = self.users[1].get_profile()
profile2.add_points(20, datetime.datetime.today(), "test")
profile2.save()
self.assertEqual(self.prize.leader(team=profile.team), profile3,
"User 3 should be the leading profile on user 1's team.")
self.assertEqual(self.prize.leader(team=profile2.team), profile2,
"User 2 should be the leading profile on user 2's team.")
def tearDown(self):
"""
Deletes the created image file in prizes.
"""
self.prize.image.delete()
self.prize.delete()
| mit |
ornicar/mithril.js | archive/v0.1.2/mithril.redraw.html | 4726 | <!doctype html>
<html>
<head>
<title>Mithril</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic" rel="stylesheet" />
<link href="lib/prism/prism.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<header>
<nav class="container">
<a href="index.html" class="logo"><span>○</span> Mithril</a>
<a href="getting-started.html">Guide</a>
<a href="mithril.html">API</a>
<a href="community.html">Community</a>
<a href="mithril.min.zip">Download</a>
<a href="http://github.com/lhorie/mithril.js" target="_blank">Github</a>
</nav>
</header>
<main>
<section class="content">
<div class="container">
<div class="row">
<div class="col(3,3,12)">
<h2 id="api">API (v0.1.2)</h2>
<h3 id="core">Core</h3>
<ul>
<li><a href="mithril.html">m</a></li>
<li><a href="mithril.prop.html">m.prop</a></li>
<li><a href="mithril.withAttr.html">m.withAttr</a></li>
<li><a href="mithril.module.html">m.module</a></li>
<li><a href="mithril.trust.html">m.trust</a></li>
<li><a href="mithril.render.html">m.render</a></li>
<li><a href="mithril.redraw.html">m.redraw</a></li>
</ul>
<h3 id="routing">Routing</h3>
<ul>
<li><a href="mithril.route.html">m.route</a>
<ul>
<li><a href="mithril.route.html#defining-routes">m.route(rootElement, defaultRoute, routes)</a></li>
<li><a href="mithril.route.html#redirecting">m.route(path)</a></li>
<li><a href="mithril.route.html#mode-abstraction">m.route(element)</a></li>
<li><a href="mithril.route.html#mode">m.route.mode</a></li>
<li><a href="mithril.route.html#param">m.route.param</a></li>
</ul>
</li>
</ul>
<h3 id="data">Data</h3>
<ul>
<li><a href="mithril.request.html">m.request</a></li>
<li><a href="mithril.deferred.html">m.deferred</a></li>
<li><a href="mithril.sync.html">m.sync</a></li>
<li><a href="mithril.computation.html">m.startComputation / m.endComputation</a></li>
</ul>
<h2 id="archive">History</h2>
<ul>
<li><a href="roadmap.html">Roadmap</a></li>
<li><a href="change-log.html">Change log</a></li>
</ul>
</div>
<div class="col(9,9,12)">
<h2 id="m-redraw">m.redraw</h2>
<p>Redraws the view for the currently active module. Use <a href="mithril.module.html"><code>m.module()</code></a> to activate a module.</p>
<p>This method is called internally by Mithril's auto-redrawing system and is only documented for completeness; you should avoid calling it manually unless you explicitly want a multi-pass redraw cycle.</p>
<p>A multi-pass redraw cycle is usually only useful if you need non-trivial UI metrics measurements. A multi-pass cycle may span multiple browser repaints and therefore could cause flash of unbehaviored content (FOUC) and performance degradation.</p>
<p>By default, if you're using either <a href="mithril.route.html"><code>m.route</code></a> or <a href="mithril.module.html"><code>m.module</code></a>, <code>m.redraw()</code> is called automatically by Mithril's auto-redrawing system once the controller finishes executing.</p>
<p><code>m.redraw</code> is also called automatically on event handlers defined in virtual elements.</p>
<p>If there are pending <a href="mithril.request.html"><code>m.request</code></a> calls in either a controller constructor or event handler, the auto-redrawing system waits for all the AJAX requests to complete before calling <code>m.redraw</code>.</p>
<p>This method may also be called manually from within a controller if more granular updates to the view are needed, however doing so is generally not recommended, as it may degrade performance. Model classes should never call this method.</p>
<p>If you are developing an asynchronous model-level service and finding that Mithril is not redrawing the view after your code runs, you should use <a href="mithril.computation.html"><code>m.startComputation</code> and <code>m.endComputation</code></a> to integrate with Mithril's auto-redrawing system instead.</p>
<hr>
<h3 id="signature">Signature</h3>
<p><a href="how-to-read-signatures.html">How to read signatures</a></p>
<pre><code class="lang-clike">void redraw()</code></pre>
</div>
</div>
</div>
</section>
</main>
<footer>
<div class="container">
Released under the <a href="http://opensource.org/licenses/MIT" target="_blank">MIT license</a>
<br />© 2014 Leo Horie
</div>
</footer>
<script src="lib/prism/prism.js"></script>
</body>
</html> | mit |
PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/bitwise-xor/S11.10.2_A3_T2.3.js | 802 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x ^ y returns ToNumber(x) ^ ToNumber(y)
es5id: 11.10.2_A3_T2.3
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Null
---*/
//CHECK#1
if ((1 ^ null) !== 1) {
$ERROR('#1: (1 ^ null) === 1. Actual: ' + ((1 ^ null)));
}
//CHECK#2
if ((null ^ 1) !== 1) {
$ERROR('#2: (null ^ 1) === 1. Actual: ' + ((null ^ 1)));
}
//CHECK#3
if ((new Number(1) ^ null) !== 1) {
$ERROR('#3: (new Number(1) ^ null) === 1. Actual: ' + ((new Number(1) ^ null)));
}
//CHECK#4
if ((null ^ new Number(1)) !== 1) {
$ERROR('#4: (null ^ new Number(1)) === 1. Actual: ' + ((null ^ new Number(1))));
}
| mit |
petebacondarwin/angular | packages/bazel/test/protractor-utils/index_test.ts | 557 | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {runServer} from '../../src/protractor/utils';
describe('Bazel protractor utils', () => {
it('should be able to start devserver', async() => {
// Test will automatically time out if the server couldn't be launched as expected.
await runServer('angular', 'packages/bazel/test/protractor-utils/fake-devserver', '--port', []);
});
});
| mit |
jack0331/peddler | lib/mws/feeds.rb | 27 | require 'mws/feeds/client'
| mit |
genlu/roslyn | src/VisualStudio/Core/Test.Next/Services/PerformanceTrackerServiceTests.cs | 7698 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Remote.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
public class PerformanceTrackerServiceTests
{
[Fact]
public void TestTooFewSamples()
{
// minimum sample is 100
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 80);
Assert.Empty(badAnalyzers);
}
[Fact]
public void TestTracking()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 200);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 101.244432561581, 54.48, 21.8163001442628);
VerifyBadAnalyzer(badAnalyzers[1], "CSharpInlineDeclarationDiagnosticAnalyzer", 49.9389715502954, 26.6686092715232, 9.2987133054884);
VerifyBadAnalyzer(badAnalyzers[2], "VisualBasicRemoveUnnecessaryCastDiagnosticAnalyzer", 42.0967360557792, 23.277619047619, 7.25464266261805);
}
[Fact]
public void TestTrackingMaxSample()
{
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 300);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 85.6039521236341, 58.4542358078603, 18.4245217226717);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 45.0918385052674, 29.0622535211268, 9.13728667060397);
VerifyBadAnalyzer(badAnalyzers[2], "CSharpInlineDeclarationDiagnosticAnalyzer", 42.2014208750466, 28.7935371179039, 7.99261581900397);
}
[Fact]
public void TestTrackingRolling()
{
// data starting to rolling at 300 data points
var badAnalyzers = GetBadAnalyzers(@"TestFiles\analyzer_input.csv", to: 400);
VerifyBadAnalyzer(badAnalyzers[0], "CSharpRemoveUnnecessaryCastDiagnosticAnalyzer", 76.2748443491852, 51.1698695652174, 17.3819563479479);
VerifyBadAnalyzer(badAnalyzers[1], "VisualBasic.UseAutoProperty.UseAutoPropertyAnalyzer", 43.5700167914005, 29.2597857142857, 9.21213873850298);
VerifyBadAnalyzer(badAnalyzers[2], "InlineDeclaration.CSharpInlineDeclarationDiagnosticAnalyzer", 36.4336594793033, 23.9764782608696, 7.43956680199015);
}
[Fact]
public void TestBadAnalyzerInfoPII()
{
var badAnalyzer1 = new ExpensiveAnalyzerInfo(true, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == badAnalyzer1.AnalyzerId);
Assert.True(badAnalyzer1.PIISafeAnalyzerId == "test");
var badAnalyzer2 = new ExpensiveAnalyzerInfo(false, "test", 0.1, 0.1, 0.1);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == badAnalyzer2.AnalyzerIdHash);
Assert.True(badAnalyzer2.PIISafeAnalyzerId == "test".GetHashCode().ToString());
}
private void VerifyBadAnalyzer(ExpensiveAnalyzerInfo analyzer, string analyzerId, double lof, double mean, double stddev)
{
Assert.True(analyzer.PIISafeAnalyzerId.IndexOf(analyzerId, StringComparison.OrdinalIgnoreCase) >= 0);
Assert.Equal(lof, analyzer.LocalOutlierFactor, precision: 4);
Assert.Equal(mean, analyzer.Average, precision: 4);
Assert.Equal(stddev, analyzer.AdjustedStandardDeviation, precision: 4);
}
private List<ExpensiveAnalyzerInfo> GetBadAnalyzers(string testFileName, int to)
{
var testFile = ReadTestFile(testFileName);
var (matrix, dataCount) = CreateMatrix(testFile);
to = Math.Min(to, dataCount);
var service = new PerformanceTrackerService(minLOFValue: 0, averageThreshold: 0, stddevThreshold: 0);
for (var i = 0; i < to; i++)
{
service.AddSnapshot(CreateSnapshots(matrix, i), unitCount: 100);
}
var badAnalyzerInfo = new List<ExpensiveAnalyzerInfo>();
service.GenerateReport(badAnalyzerInfo);
return badAnalyzerInfo;
}
private IEnumerable<AnalyzerPerformanceInfo> CreateSnapshots(Dictionary<string, double[]> matrix, int index)
{
foreach (var kv in matrix)
{
var timeSpan = kv.Value[index];
if (double.IsNaN(timeSpan))
{
continue;
}
yield return new AnalyzerPerformanceInfo(kv.Key, true, TimeSpan.FromMilliseconds(timeSpan));
}
}
private (Dictionary<string, double[]> matrix, int dataCount) CreateMatrix(string testFile)
{
var matrix = new Dictionary<string, double[]>();
var lines = testFile.Split('\n');
var expectedDataCount = GetExpectedDataCount(lines[0]);
for (var i = 1; i < lines.Length; i++)
{
if (lines[i].Trim().Length == 0)
{
continue;
}
var data = SkipAnalyzerId(lines[i]).Split(',');
Assert.Equal(data.Length, expectedDataCount);
var analyzerId = GetAnalyzerId(lines[i]);
var timeSpans = new double[expectedDataCount];
for (var j = 0; j < data.Length; j++)
{
double result;
if (!double.TryParse(data[j], NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result))
{
// no data for this analyzer for this particular run
result = double.NaN;
}
timeSpans[j] = result;
}
matrix[analyzerId] = timeSpans;
}
return (matrix, expectedDataCount);
}
private string GetAnalyzerId(string line)
{
return line.Substring(1, line.LastIndexOf('"') - 1);
}
private int GetExpectedDataCount(string header)
{
var data = header.Split(',');
return data.Length - 1;
}
private string SkipAnalyzerId(string line)
{
return line.Substring(line.LastIndexOf('"') + 2);
}
private string ReadTestFile(string name)
{
var assembly = typeof(PerformanceTrackerServiceTests).Assembly;
var resourceName = GetResourceName(assembly, name);
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
throw new InvalidOperationException($"Resource '{resourceName}' not found in {assembly.FullName}.");
}
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
private static string GetResourceName(Assembly assembly, string name)
{
var convert = name.Replace(@"\", ".");
return assembly.GetManifestResourceNames().Where(n => n.EndsWith(convert, StringComparison.OrdinalIgnoreCase)).First();
}
}
}
| mit |
ramonornela/Zebra | library/Zend/Gdata/YouTube/Extension/ReleaseDate.php | 1444 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* Represents the yt:releaseDate element
*
* @category Zend
* @package Zend_Gdata
* @subpackage YouTube
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_YouTube_Extension_ReleaseDate extends Zend_Gdata_Extension
{
protected $_rootElement = 'releaseDate';
protected $_rootNamespace = 'yt';
public function __construct($text = null)
{
$this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces);
parent::__construct();
$this->_text = $text;
}
}
| mit |
ocombe/angular | packages/core/test/acceptance/inherit_definition_feature_spec.ts | 155194 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {state, style, trigger} from '@angular/animations';
import {Component, ContentChildren, Directive, EventEmitter, HostBinding, HostListener, Input, OnChanges, Output, QueryList, ViewChildren} from '@angular/core';
import {getDirectiveDef} from '@angular/core/src/render3/definition';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
describe('inheritance', () => {
it('should throw when trying to inherit a component from a directive', () => {
@Component({
selector: 'my-comp',
template: '<div></div>',
})
class MyComponent {
}
@Directive({
selector: '[my-dir]',
})
class MyDirective extends MyComponent {
}
@Component({
template: `<div my-dir></div>`,
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, MyDirective],
});
expect(() => {
TestBed.createComponent(App);
}).toThrowError('NG0903: Directives cannot inherit Components');
});
describe('multiple children', () => {
it('should ensure that multiple child classes don\'t cause multiple parent execution', () => {
// Assume this inheritance:
// Base
// |
// Super
// / \
// Sub1 Sub2
//
// In the above case:
// 1. Sub1 as will walk the inheritance Sub1, Super, Base
// 2. Sub2 as will walk the inheritance Sub2, Super, Base
//
// Notice that Super, Base will get walked twice. Because inheritance works by wrapping parent
// hostBindings function in a delegate which calls the hostBindings of the directive as well
// as super, we need to ensure that we don't double wrap the hostBindings function. Doing so
// would result in calling the hostBindings multiple times (unnecessarily). This would be
// especially an issue if we have a lot of sub-classes (as is common in component libraries)
const log: string[] = [];
@Directive({selector: '[superDir]'})
class BaseDirective {
@HostBinding('style.background-color')
get backgroundColor() {
log.push('Base.backgroundColor');
return 'white';
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends BaseDirective {
@HostBinding('style.color')
get color() {
log.push('Super.color');
return 'blue';
}
}
@Directive({selector: '[subDir1]'})
class Sub1Directive extends SuperDirective {
@HostBinding('style.height')
get height() {
log.push('Sub1.height');
return '200px';
}
}
@Directive({selector: '[subDir2]'})
class Sub2Directive extends SuperDirective {
@HostBinding('style.width')
get width() {
log.push('Sub2.width');
return '100px';
}
}
@Component({template: `<div subDir1 subDir2></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, Sub1Directive, Sub2Directive, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges(false); // Don't check for no changes (so that assertion does not need
// to worry about it.)
expect(log).toEqual([
'Base.backgroundColor', 'Super.color', 'Sub1.height', //
'Base.backgroundColor', 'Super.color', 'Sub2.width', //
]);
expect(getDirectiveDef(BaseDirective)!.hostVars).toEqual(2);
expect(getDirectiveDef(SuperDirective)!.hostVars).toEqual(4);
expect(getDirectiveDef(Sub1Directive)!.hostVars).toEqual(6);
expect(getDirectiveDef(Sub2Directive)!.hostVars).toEqual(6);
});
});
describe('ngOnChanges', () => {
it('should be inherited when super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[superDir]'})
class SuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class', () => {
const log: string[] = [];
class SuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[grandSuperDir]'})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends GrandSuperDirective {
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a directive and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
@Directive({selector: '[superDir]'})
class SuperDirective extends GrandSuperClass {
@Input() someInput = '';
}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperDirective {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a directive', () => {
const log: string[] = [];
@Directive({selector: '[grandSuperDir]'})
class GrandSuperDirective implements OnChanges {
@Input() someInput = '';
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperDirective {}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, GrandSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited when super is a simple class and grand-super is a simple class', () => {
const log: string[] = [];
class GrandSuperClass {
ngOnChanges() {
log.push('on changes!');
}
}
class SuperClass extends GrandSuperClass {}
@Directive({selector: '[subDir]'})
class SubDirective extends SuperClass {
@Input() someInput = '';
}
@Component({template: `<div subDir [someInput]="1"></div>`})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(log).toEqual(['on changes!']);
});
it('should be inherited from undecorated super class which inherits from decorated one', () => {
let changes = 0;
abstract class Base {
// Add an Input so that we have at least one Angular decorator on a class field.
@Input() inputBase: any;
abstract input: any;
}
abstract class UndecoratedBase extends Base {
abstract override input: any;
ngOnChanges() {
changes++;
}
}
@Component({selector: 'my-comp', template: ''})
class MyComp extends UndecoratedBase {
@Input() override input: any;
}
@Component({template: '<my-comp [input]="value"></my-comp>'})
class App {
value = 'hello';
}
TestBed.configureTestingModule({declarations: [MyComp, App]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(changes).toBe(1);
});
});
describe('of bare super class by a directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
describe('ContentChildren', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive by another directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({selector: '[super-dir]'})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)"></div>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir>one</li>
<li child-dir>two</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive by a bare class then by another directive', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperDirective extends SuperSuperDirective {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Directive({
selector: '[subDir]',
})
class SubDirective extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<p *ngIf="showing" subDir></p>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [SubDirective, App, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({selector: '[super-dir]'})
class SuperSuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class SuperDirective extends SuperSuperDirective {
@Input() bar = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({
selector: 'my-app',
template: `<p sub-dir [foo]="a" [bar]="b" [baz]="c" [qux]="d"></p>`,
})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir =
fixture.debugElement.query(By.directive(SubDirective)).injector.get(SubDirective);
expect(subDir.foo).toBe('a');
expect(subDir.bar).toBe('b');
expect(subDir.baz).toBe('c');
expect(subDir.qux).toBe('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@Output() foo = new EventEmitter<string>();
}
class SuperDirective extends SuperSuperDirective {
@Output() bar = new EventEmitter<string>();
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<div sub-dir (foo)="handleFoo($event)" (bar)="handleBar($event)"></div>
`
})
class App {
foo = '';
bar = '';
handleFoo(event: string) {
this.foo = event;
}
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@HostBinding('style.color') color = 'red';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir>test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(SubDirective));
expect(queryResult.nativeElement.tagName).toBe('P');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperDirective extends SuperSuperDirective {
@HostBinding('accessKey')
get boundAltKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
}
@Component({
template: `
<p sub-dir superTitle="test1" superAccessKey="test2">test</p>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, SuperDirective, SuperSuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const p: HTMLParagraphElement =
fixture.debugElement.query(By.directive(SubDirective)).nativeElement;
expect(p.title).toBe('test1!!!');
expect(p.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundChildDir1s: QueryList<ChildDir1>;
let foundChildDir2s: QueryList<ChildDir2>;
@Directive({selector: '[child-dir-one]'})
class ChildDir1 {
}
@Directive({selector: '[child-dir-two]'})
class ChildDir2 {
}
@Directive({
selector: '[super-dir]',
})
class SuperSuperDirective {
@ContentChildren(ChildDir1) childDir1s!: QueryList<ChildDir1>;
}
class SuperDirective extends SuperSuperDirective {
@ContentChildren(ChildDir1) childDir2s!: QueryList<ChildDir2>;
}
@Directive({
selector: '[sub-dir]',
})
class SubDirective extends SuperDirective {
ngAfterViewInit() {
foundChildDir1s = this.childDir1s;
foundChildDir2s = this.childDir2s;
}
}
@Component({
template: `
<ul sub-dir>
<li child-dir-one child-dir-two>one</li>
<li child-dir-one>two</li>
<li child-dir-two>three</li>
</ul>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SubDirective, ChildDir1, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundChildDir1s!.length).toBe(2);
expect(foundChildDir2s!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of bare super class by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({selector: 'my-comp', template: `<ul><ng-content></ng-content></ul>`})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperDirective {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperDirective {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperDirective {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({selector: 'my-comp', template: `<ul><ng-content></ng-content></ul>`})
class MyComponent extends SuperDirective {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperDirective {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a directive inherited by a bare class and then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class BareClass extends SuperDirective {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Directive({
selector: 'my-comp',
})
class MyComponent extends BareClass {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperDirective {
@Input() bar = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, BareClass, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@Output() foo = new EventEmitter<string>();
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class BareClass extends SuperDirective {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends BareClass {
}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, SuperDirective, BareClass, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends BareClass {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Directive({
selector: '[super-dir]',
})
class SuperDirective {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
class BareClass extends SuperDirective {}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends BareClass {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperDirective],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a component inherited by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@Input() foo = '';
@Input() bar = '';
@Input() baz = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends SuperComponent {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const subDir: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(subDir.foo).toEqual('a');
expect(subDir.bar).toEqual('b');
expect(subDir.baz).toEqual('c');
expect(subDir.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@Output() foo = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test');
});
});
describe('animations', () => {
it('should work with inherited host bindings and animations', () => {
@Component({
selector: 'super-comp',
template: '<div>super-comp</div>',
host: {
'[@animation]': 'colorExp',
},
animations: [
trigger('animation', [state('color', style({color: 'red'}))]),
],
})
class SuperComponent {
colorExp = 'color';
}
@Component({
selector: 'my-comp',
template: `<div>my-comp</div>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('red');
});
it('should compose animations (from super class)', () => {
@Component({
selector: 'super-comp',
template: '...',
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
})
class SuperComponent {
}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
})
class MyComponent extends SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@HostBinding('style.color') color = 'red';
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.title).toBe('test!!!');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
it('should inherit host listeners from base class once', () => {
const events: string[] = [];
@Component({
selector: 'app-base',
template: 'base',
})
class BaseComponent {
@HostListener('click')
clicked() {
events.push('BaseComponent.clicked');
}
}
@Component({
selector: 'app-child',
template: 'child',
})
class ChildComponent extends BaseComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging Child and Base host binding functions)
@HostListener('focus')
focused() {
}
override clicked() {
events.push('ChildComponent.clicked');
}
}
@Component({
selector: 'app-grand-child',
template: 'grand-child',
})
class GrandChildComponent extends ChildComponent {
// additional host listeners are defined here to have `hostBindings` function generated on
// component def, which would trigger `hostBindings` functions merge operation in
// InheritDefinitionFeature logic (merging GrandChild and Child host binding functions)
@HostListener('blur')
blurred() {
}
override clicked() {
events.push('GrandChildComponent.clicked');
}
}
@Component({
selector: 'root-app',
template: `
<app-base></app-base>
<app-child></app-child>
<app-grand-child></app-grand-child>
`,
})
class RootApp {
}
const components = [BaseComponent, ChildComponent, GrandChildComponent];
TestBed.configureTestingModule({
declarations: [RootApp, ...components],
});
const fixture = TestBed.createComponent(RootApp);
fixture.detectChanges();
components.forEach(component => {
fixture.debugElement.query(By.directive(component)).nativeElement.click();
});
expect(events).toEqual(
['BaseComponent.clicked', 'ChildComponent.clicked', 'GrandChildComponent.clicked']);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
describe('of a component inherited by a bare class then by a component', () => {
// TODO: Add tests for ContentChild
// TODO: Add tests for ViewChild
describe('lifecycle hooks', () => {
const fired: string[] = [];
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
ngOnInit() {
fired.push('super init');
}
ngOnDestroy() {
fired.push('super destroy');
}
ngAfterContentInit() {
fired.push('super after content init');
}
ngAfterContentChecked() {
fired.push('super after content checked');
}
ngAfterViewInit() {
fired.push('super after view init');
}
ngAfterViewChecked() {
fired.push('super after view checked');
}
ngDoCheck() {
fired.push('super do check');
}
}
class SuperComponent extends SuperSuperComponent {}
beforeEach(() => fired.length = 0);
it('ngOnInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnInit() {
fired.push('sub init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'sub init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngDoCheck', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngDoCheck() {
fired.push('sub do check');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'sub do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentInit() {
fired.push('sub after content init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'sub after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterContentChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterContentChecked() {
fired.push('sub after content checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'sub after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewInit', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewInit() {
fired.push('sub after view init');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'sub after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngAfterViewChecked', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngAfterViewChecked() {
fired.push('sub after view checked');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'sub after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'super destroy',
]);
});
it('ngOnDestroy', () => {
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
override ngOnDestroy() {
fired.push('sub destroy');
}
}
@Component({
template: `<my-comp *ngIf="showing"></my-comp>`,
})
class App {
showing = true;
}
TestBed.configureTestingModule({
declarations: [MyComponent, App, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fired).toEqual([
'super init',
'super do check',
'super after content init',
'super after content checked',
'super after view init',
'super after view checked',
]);
fired.length = 0;
fixture.componentInstance.showing = false;
fixture.detectChanges();
expect(fired).toEqual([
'sub destroy',
]);
});
});
describe('inputs', () => {
// TODO: add test where the two inputs have a different alias
// TODO: add test where super has an @Input() on the property, and sub does not
// TODO: add test where super has an @Input('alias') on the property and sub has no alias
it('should inherit inputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@Input() foo = '';
@Input() baz = '';
}
class BareClass extends SuperSuperComponent {
@Input() bar = '';
}
@Component({selector: 'my-comp', template: `<p>test</p>`})
class MyComponent extends BareClass {
@Input() override baz = '';
@Input() qux = '';
}
@Component({template: `<my-comp [foo]="a" [bar]="b" [baz]="c" [qux]="d"></my-comp>`})
class App {
a = 'a';
b = 'b';
c = 'c';
d = 'd';
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperSuperComponent, BareClass],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const myComp: MyComponent =
fixture.debugElement.query(By.directive(MyComponent)).componentInstance;
expect(myComp.foo).toEqual('a');
expect(myComp.bar).toEqual('b');
expect(myComp.baz).toEqual('c');
expect(myComp.qux).toEqual('d');
});
});
describe('outputs', () => {
// TODO: add tests where both sub and super have Output on same property with different
// aliases
// TODO: add test where super has property with alias and sub has property with no alias
// TODO: add test where super has an @Input() on the property, and sub does not
it('should inherit outputs', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@Output() foo = new EventEmitter<string>();
}
class SuperComponent extends SuperSuperComponent {
@Output() bar = new EventEmitter<string>();
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
ngOnInit() {
this.foo.emit('test1');
this.bar.emit('test2');
}
}
@Component({
template: `
<my-comp (foo)="handleFoo($event)" (bar)="handleBar($event)"></my-comp>
`
})
class App {
foo = '';
handleFoo(event: string) {
this.foo = event;
}
bar = '';
handleBar(event: string) {
this.bar = event;
}
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const app = fixture.componentInstance;
expect(app.foo).toBe('test1');
expect(app.bar).toBe('test2');
});
});
describe('animations', () => {
it('should compose animations across multiple inheritance levels', () => {
@Component({
selector: 'super-comp',
template: '...',
host: {
'[@animation1]': 'colorExp',
'[@animation2]': 'opacityExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'red'}))]),
trigger('animation2', [state('opacity', style({opacity: '0.5'}))]),
],
})
class SuperComponent {
colorExp = 'color';
opacityExp = 'opacity';
}
@Component({
selector: 'intermediate-comp',
template: '...',
})
class IntermediateComponent extends SuperComponent {
}
@Component({
selector: 'my-comp',
template: '<div>my-comp</div>',
host: {
'[@animation1]': 'colorExp',
'[@animation3]': 'bgExp',
},
animations: [
trigger('animation1', [state('color', style({color: 'blue'}))]),
trigger('animation3', [state('bg', style({backgroundColor: 'green'}))]),
],
})
class MyComponent extends IntermediateComponent {
override colorExp = 'color';
override opacityExp = 'opacity';
bgExp = 'bg';
}
@Component({
template: '<my-comp>app</my-comp>',
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, IntermediateComponent, SuperComponent],
imports: [NoopAnimationsModule],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.css('my-comp'));
expect(queryResult.nativeElement.style.color).toBe('blue');
expect(queryResult.nativeElement.style.opacity).toBe('0.5');
expect(queryResult.nativeElement.style.backgroundColor).toBe('green');
});
});
describe('host bindings (style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings for styles', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@HostBinding('style.color') color = 'red';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('style.backgroundColor') bg = 'black';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp>test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.style.color).toBe('red');
expect(queryResult.nativeElement.style.backgroundColor).toBe('black');
});
});
describe('host bindings (non-style related)', () => {
// TODO: sub and super HostBinding same property but different bindings
// TODO: sub and super HostBinding same binding on two different properties
it('should compose host bindings (non-style related)', () => {
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperSuperComponent {
@HostBinding('title')
get boundTitle() {
return this.superTitle + '!!!';
}
@Input() superTitle = '';
}
class SuperComponent extends SuperSuperComponent {
@HostBinding('accessKey')
get boundAccessKey() {
return this.superAccessKey + '???';
}
@Input() superAccessKey = '';
}
@Component({
selector: 'my-comp',
template: `<p>test</p>`,
})
class MyComponent extends SuperComponent {
}
@Component({
template: `
<my-comp superTitle="test1" superAccessKey="test2">test</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, SuperSuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const queryResult = fixture.debugElement.query(By.directive(MyComponent));
expect(queryResult.nativeElement.tagName).toBe('MY-COMP');
expect(queryResult.nativeElement.title).toBe('test1!!!');
expect(queryResult.nativeElement.accessKey).toBe('test2???');
});
});
it('should inherit ContentChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ContentChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `<ul><ng-content></ng-content></ul>`,
})
class MyComponent extends SuperComponent {
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp>
<li child-dir>one</li>
<li child-dir>two</li>
</my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, SuperComponent, ChildDir],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(2);
});
it('should inherit ViewChildren queries', () => {
let foundQueryList: QueryList<ChildDir>;
@Directive({selector: '[child-dir]'})
class ChildDir {
}
@Component({
selector: 'super-comp',
template: `<p>super</p>`,
})
class SuperComponent {
@ViewChildren(ChildDir) customDirs!: QueryList<ChildDir>;
}
@Component({
selector: 'my-comp',
template: `
<ul>
<li child-dir *ngFor="let item of items">{{item}}</li>
</ul>
`,
})
class MyComponent extends SuperComponent {
items = [1, 2, 3, 4, 5];
ngAfterViewInit() {
foundQueryList = this.customDirs;
}
}
@Component({
template: `
<my-comp></my-comp>
`
})
class App {
}
TestBed.configureTestingModule({
declarations: [App, MyComponent, ChildDir, SuperComponent],
});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(foundQueryList!.length).toBe(5);
});
xdescribe(
'what happens when...',
() => {
// TODO: sub has Input and super has Output on same property
// TODO: sub has Input and super has HostBinding on same property
// TODO: sub has Input and super has ViewChild on same property
// TODO: sub has Input and super has ViewChildren on same property
// TODO: sub has Input and super has ContentChild on same property
// TODO: sub has Input and super has ContentChildren on same property
// TODO: sub has Output and super has HostBinding on same property
// TODO: sub has Output and super has ViewChild on same property
// TODO: sub has Output and super has ViewChildren on same property
// TODO: sub has Output and super has ContentChild on same property
// TODO: sub has Output and super has ContentChildren on same property
// TODO: sub has HostBinding and super has ViewChild on same property
// TODO: sub has HostBinding and super has ViewChildren on same property
// TODO: sub has HostBinding and super has ContentChild on same property
// TODO: sub has HostBinding and super has ContentChildren on same property
// TODO: sub has ViewChild and super has ViewChildren on same property
// TODO: sub has ViewChild and super has ContentChild on same property
// TODO: sub has ViewChild and super has ContentChildren on same property
// TODO: sub has ViewChildren and super has ContentChild on same property
// TODO: sub has ViewChildren and super has ContentChildren on same property
// TODO: sub has ContentChild and super has ContentChildren on same property
});
});
});
| mit |
maocubillos/pnt2015 | src/bower_components/bootstrap/node_modules/npm-shrinkwrap/node_modules/npm/html/doc/cli/npm-dist-tag.html | 5801 | <!doctype html>
<html>
<title>npm-dist-tag</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-dist-tag.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-dist-tag.html">npm-dist-tag</a></h1> <p>Modify package distribution tags</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm dist-tag add <pkg>@<version> [<tag>]
npm dist-tag rm <pkg> <tag>
npm dist-tag ls [<pkg>]
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>Add, remove, and enumerate distribution tags on a package:</p>
<ul>
<li><p>add:
Tags the specified version of the package with the specified tag, or the
<code>--tag</code> config if not specified.</p>
</li>
<li><p>rm:
Clear a tag that is no longer in use from the package.</p>
</li>
<li><p>ls:
Show all of the dist-tags for a package, defaulting to the package in
the current prefix.</p>
</li>
</ul>
<p>A tag can be used when installing packages as a reference to a version instead
of using a specific version number:</p>
<pre><code>npm install <name>@<tag>
</code></pre><p>When installing dependencies, a preferred tagged version may be specified:</p>
<pre><code>npm install --tag <tag>
</code></pre><p>This also applies to <code>npm dedupe</code>.</p>
<p>Publishing a package always sets the "latest" tag to the published version.</p>
<h2 id="purpose">PURPOSE</h2>
<p>Tags can be used to provide an alias instead of version numbers. For
example, <code>npm</code> currently uses the tag "next" to identify the upcoming
version, and the tag "latest" to identify the current version.</p>
<p>A project might choose to have multiple streams of development, e.g.,
"stable", "canary".</p>
<h2 id="caveats">CAVEATS</h2>
<p>This command used to be known as <code>npm tag</code>, which only created new tags, and so
had a different syntax.</p>
<p>Tags must share a namespace with version numbers, because they are specified in
the same slot: <code>npm install <pkg>@<version></code> vs <code>npm install <pkg>@<tag></code>.</p>
<p>Tags that can be interpreted as valid semver ranges will be rejected. For
example, <code>v1.4</code> cannot be used as a tag, because it is interpreted by semver as
<code>>=1.4.0 <1.5.0</code>. See <a href="https://github.com/npm/npm/issues/6082">https://github.com/npm/npm/issues/6082</a>.</p>
<p>The simplest way to avoid semver problems with tags is to use tags that do not
begin with a number or the letter <code>v</code>.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-tag.html"><a href="../cli/npm-tag.html">npm-tag(1)</a></a></li>
<li><a href="../cli/npm-publish.html"><a href="../cli/npm-publish.html">npm-publish(1)</a></a></li>
<li><a href="../cli/npm-install.html"><a href="../cli/npm-install.html">npm-install(1)</a></a></li>
<li><a href="../cli/npm-dedupe.html"><a href="../cli/npm-dedupe.html">npm-dedupe(1)</a></a></li>
<li><a href="../misc/npm-registry.html"><a href="../misc/npm-registry.html">npm-registry(7)</a></a></li>
<li><a href="../cli/npm-config.html"><a href="../cli/npm-config.html">npm-config(1)</a></a></li>
<li><a href="../misc/npm-config.html"><a href="../misc/npm-config.html">npm-config(7)</a></a></li>
<li><a href="../api/npm-tag.html"><a href="../api/npm-tag.html">npm-tag(3)</a></a></li>
<li><a href="../files/npmrc.html"><a href="../files/npmrc.html">npmrc(5)</a></a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-dist-tag — npm@2.7.3</p>
| mit |
liuderchi/atom | packages/one-light-ui/README.md | 1321 | ## One Light UI theme
A light UI theme that adapts to most syntax themes.

> The font used in the screenshot is [Fira Mono](https://github.com/mozilla/Fira).
### Install
This theme comes bundled with Atom and can be activated by going to the __Settings > Themes__ section and selecting "One Light" from the __UI Themes__ drop-down menu.
### Settings
In the theme settings you can:
- Change the __Font Size__ to scale the whole UI up or down.
- Choose between 3 __Tab Sizing__ modes.
- Hide the __dock buttons__.
To make changes, go to `Settings > Themes > One Light UI > Settings` or the cog icon next to the theme picker.
### Customize
It's also possible to resize only certain areas by adding the following to your `styles.less` (Use DevTools to find the right selectors):
```css
.theme-one-light-ui {
.tab-bar { font-size: 18px; }
.tree-view { font-size: 14px; }
.status-bar { font-size: 12px; }
}
```
### FAQ
__Why do the colors change when I switch Syntax themes.__
This UI theme uses the same background color as the chosen syntax theme. If that syntax theme has a dark background color, it only uses its hue, but otherwise stays light. This lets you use light-dark combos.
| mit |
AxelSparkster/axelsparkster.github.io | node_modules/tsutils/typeguard/type.js | 357 | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
tslib_1.__exportStar(require("./2.9/type"), exports);
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInR5cGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEscURBQTJCIn0= | mit |
shines77/jemalloc-win32-3.6.0 | include/jemalloc/jemalloc_defs.h | 859 | /* include/jemalloc/jemalloc_defs.h. Generated from jemalloc_defs.h.in by configure. */
/* Defined if __attribute__((...)) syntax is supported. */
#ifndef _MSC_VER
#define JEMALLOC_HAVE_ATTR
#endif
/* Support the experimental API. */
#define JEMALLOC_EXPERIMENTAL
/*
* Define overrides for non-standard allocator-related functions if they are
* present on the system.
*/
#define JEMALLOC_OVERRIDE_MEMALIGN
#define JEMALLOC_OVERRIDE_VALLOC
/*
* At least Linux omits the "const" in:
*
* size_t malloc_usable_size(const void *ptr);
*
* Match the operating system's prototype.
*/
#define JEMALLOC_USABLE_SIZE_CONST const
/* sizeof(void *) == 2^LG_SIZEOF_PTR. */
#if defined(_WIN32) || defined(_M_IX86)
#define LG_SIZEOF_PTR 2
#elif defined(_WIN64) || defined(_M_X64)
#define LG_SIZEOF_PTR 3
#else
#define LG_SIZEOF_PTR 3
#endif
| mit |
okwow123/djangol2 | example/env/lib/python2.7/site-packages/allauth/socialaccount/providers/douban/views.py | 1354 | import requests
from django.utils.translation import ugettext as _
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from ..base import ProviderException
from .provider import DoubanProvider
class DoubanOAuth2Adapter(OAuth2Adapter):
provider_id = DoubanProvider.id
access_token_url = 'https://www.douban.com/service/auth2/token'
authorize_url = 'https://www.douban.com/service/auth2/auth'
profile_url = 'https://api.douban.com/v2/user/~me'
def complete_login(self, request, app, token, **kwargs):
headers = {'Authorization': 'Bearer %s' % token.token}
resp = requests.get(self.profile_url, headers=headers)
extra_data = resp.json()
"""
Douban may return data like this:
{
'code': 128,
'request': 'GET /v2/user/~me',
'msg': 'user_is_locked:53358092'
}
"""
if 'id' not in extra_data:
msg = extra_data.get('msg', _('Invalid profile data'))
raise ProviderException(msg)
return self.get_provider().sociallogin_from_response(
request, extra_data)
oauth2_login = OAuth2LoginView.adapter_view(DoubanOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DoubanOAuth2Adapter)
| mit |
LanceMcCarthy/ajax-docs | controls/ajax/client-side-programming/how-to/forcing-a-postback.md | 1413 | ---
title: Forcing a Postback
page_title: Forcing a Postback | RadAjax for ASP.NET AJAX Documentation
description: Forcing a Postback
slug: ajax/client-side-programming/how-to/forcing-a-postback
tags: forcing,a,postback
published: True
position: 3
---
# Forcing a Postback
##
If you want to perform a single postback instead of an AJAX request, **arguments.EnableAjax** should be **false** .
In the code-behind:
````C#
if (!RadAjaxManager1.EnableAJAX)
{
RadAjaxManager1.ClientEvents.OnRequestStart = "OnRequestStart";
}
````
````VB
If Not RadAjaxManager1.EnableAJAX Then
RadAjaxManager1.ClientEvents.OnRequestStart = "OnRequestStart"
End If
````
On the client:
````JavaScript
function OnRequestStart(sender, args) {
args.set_enableAjax(false);
}
````
This approach is useful only when you want to perform a single postback. If you want to disable AJAX because of unsupported browsers or old versions of supported ones, we suggest you to do this on the server:
````C#
RadAjaxManager1.EnableAJAX = Page.Request.Browser.SupportsXmlHttp;
````
````VB
RadAjaxManager1.EnableAJAX = Page.Request.Browser.SupportsXmlHttp
````
## See Also
* [Cancel AJAX Request]({%slug ajax/client-side-programming/how-to/cancel-ajax--request%})
* [OnRequestStart]({%slug ajax/client-side-programming/events/onrequeststart%})
| mit |
clanplaid/wow.clanplaid.net | vendor/plugins/authentication/app/models/role.rb | 313 | class Role < ActiveRecord::Base
has_and_belongs_to_many :users
before_validation :camelize_title
validates_uniqueness_of :title
def camelize_title(role_title = self.title)
self.title = role_title.to_s.camelize
end
def self.[](title)
find_or_create_by_title(title.to_s.camelize)
end
end
| mit |
abock/roslyn | src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferencePropertiesTests.cs | 4674 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| mit |
tchoulihan/frostwire-jlibtorrent | src/com/frostwire/jlibtorrent/SessionStatus.java | 9844 | package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.dht_lookup_vector;
import com.frostwire.jlibtorrent.swig.dht_routing_bucket_vector;
import com.frostwire.jlibtorrent.swig.session_status;
import java.util.ArrayList;
import java.util.List;
/**
* Contains session wide state and counters.
*
* @author gubatron
* @author aldenml
*/
public final class SessionStatus {
private final session_status s;
public SessionStatus(session_status s) {
this.s = s;
}
public session_status getSwig() {
return s;
}
/**
* false as long as no incoming connections have been
* established on the listening socket. Every time you change the listen port, this will
* be reset to false.
*
* @return
*/
public boolean hasIncomingConnections() {
return s.getHas_incoming_connections();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getUploadRate() {
return s.getUpload_rate();
}
/**
* the total download and upload rates accumulated
* from all torrents. This includes bittorrent protocol, DHT and an estimated TCP/IP
* protocol overhead.
*
* @return
*/
public int getDownloadRate() {
return s.getDownload_rate();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalDownload() {
return s.getTotal_download();
}
/**
* the total number of bytes downloaded and
* uploaded to and from all torrents. This also includes all the protocol overhead.
*
* @return
*/
public long getTotalUpload() {
return s.getTotal_upload();
}
/**
* the rate of the payload
* down- and upload only.
*
* @return
*/
public int getPayloadUploadRate() {
return s.getPayload_upload_rate();
}
/**
* the rate of the payload down- and upload only.
*
* @return
*/
public int getPayloadDownloadRate() {
return s.getPayload_download_rate();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadDownload() {
return s.getTotal_payload_download();
}
/**
* the total transfers of payload
* only. The payload does not include the bittorrent protocol overhead, but only parts of the
* actual files to be downloaded.
*
* @return
*/
public long getTotalPayloadUpload() {
return s.getTotal_payload_upload();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadUploadRate() {
return s.getIp_overhead_upload_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public int getIPOverheadDownloadRate() {
return s.getIp_overhead_download_rate();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadDownload() {
return s.getTotal_ip_overhead_download();
}
/**
* The estimated TCP/IP overhead.
*
* @return
*/
public long getTotalIPOverheadUpload() {
return s.getTotal_ip_overhead_upload();
}
/**
* The upload rate used by DHT traffic.
*
* @return
*/
public int getDHTUploadRate() {
return s.getDht_upload_rate();
}
/**
* The download rate used by DHT traffic.
*
* @return
*/
public int getDHTDownloadRate() {
return s.getDht_download_rate();
}
/**
* The total number of bytes received from the DHT.
*
* @return
*/
public long getTotalDHTDownload() {
return s.getTotal_dht_download();
}
/**
* The total number of bytes sent to the DHT.
*
* @return
*/
public long getTotalDHTUpload() {
return s.getTotal_dht_upload();
}
/*
// the upload and download rate used by tracker traffic. Also the total number
// of bytes sent and received to and from trackers.
int tracker_upload_rate;
int tracker_download_rate;
size_type total_tracker_download;
size_type total_tracker_upload;
// the number of bytes that has been received more than once.
// This can happen if a request from a peer times out and is requested from a different
// peer, and then received again from the first one. To make this lower, increase the
// ``request_timeout`` and the ``piece_timeout`` in the session settings.
size_type total_redundant_bytes;
// the number of bytes that was downloaded which later failed
// the hash-check.
size_type total_failed_bytes;
// the total number of peer connections this session has. This includes
// incoming connections that still hasn't sent their handshake or outgoing connections
// that still hasn't completed the TCP connection. This number may be slightly higher
// than the sum of all peers of all torrents because the incoming connections may not
// be assigned a torrent yet.
int num_peers;
// the current number of unchoked peers.
int num_unchoked;
// the current allowed number of unchoked peers.
int allowed_upload_slots;
// the number of peers that are
// waiting for more bandwidth quota from the torrent rate limiter.
int up_bandwidth_queue;
int down_bandwidth_queue;
// count the number of
// bytes the connections are waiting for to be able to send and receive.
int up_bandwidth_bytes_queue;
int down_bandwidth_bytes_queue;
// tells the number of
// seconds until the next optimistic unchoke change and the start of the next
// unchoke interval. These numbers may be reset prematurely if a peer that is
// unchoked disconnects or becomes notinterested.
int optimistic_unchoke_counter;
int unchoke_counter;
// the number of peers currently
// waiting on a disk write or disk read to complete before it receives or sends
// any more data on the socket. It'a a metric of how disk bound you are.
int disk_write_queue;
int disk_read_queue;
*/
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_nodes`` is set to the number of nodes in the routing
* table. This number only includes *active* nodes, not cache nodes.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodes() {
return s.getDht_nodes();
}
/**
* Only available when built with DHT support. It is set to 0 if the DHT isn't running.
* <p/>
* When the DHT is running, ``dht_node_cache`` is set to the number of nodes in the node cache.
* <p/>
* These nodes are used to replace the regular nodes in the routing table in case any of them
* becomes unresponsive.
*
* @return
*/
public int getDHTNodeCache() {
return s.getDht_node_cache();
}
/**
* the number of torrents tracked by the DHT at the moment.
*
* @return
*/
public int getDHTTorrents() {
return s.getDht_torrents();
}
/**
* An estimation of the total number of nodes in the DHT network.
*
* @return
*/
public long getDHTGlobalNodes() {
return s.getDht_global_nodes();
}
/**
* a vector of the currently running DHT lookups.
*
* @return
*/
public List<DHTLookup> getActiveRequests() {
dht_lookup_vector v = s.getActive_requests();
int size = (int) v.size();
List<DHTLookup> l = new ArrayList<DHTLookup>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTLookup(v.get(i)));
}
return l;
}
/**
* contains information about every bucket in the DHT routing table.
*
* @return
*/
public List<DHTRoutingBucket> getDHTRoutingTable() {
dht_routing_bucket_vector v = s.getDht_routing_table();
int size = (int) v.size();
List<DHTRoutingBucket> l = new ArrayList<DHTRoutingBucket>(size);
for (int i = 0; i < size; i++) {
l.add(new DHTRoutingBucket(v.get(i)));
}
return l;
}
/**
* the number of nodes allocated dynamically for a
* particular DHT lookup. This represents roughly the amount of memory used
* by the DHT.
*
* @return
*/
public int getDHTTotalAllocations() {
return s.getDht_total_allocations();
}
/**
* statistics on the uTP sockets.
*
* @return
*/
public UTPStatus getUTPStats() {
return new UTPStatus(s.getUtp_stats());
}
/**
* the number of known peers across all torrents. These are not necessarily
* connected peers, just peers we know of.
*
* @return
*/
public int getPeerlistSize() {
return s.getPeerlist_size();
}
}
| mit |
angeloocana/ramda | test/compose.js | 1837 | var assert = require('assert');
var jsv = require('jsverify');
var R = require('..');
var eq = require('./shared/eq');
describe('compose', function() {
it('is a variadic function', function() {
eq(typeof R.compose, 'function');
eq(R.compose.length, 0);
});
it('performs right-to-left function composition', function() {
// f :: (String, Number?) -> ([Number] -> [Number])
var f = R.compose(R.map, R.multiply, parseInt);
eq(f.length, 2);
eq(f('10')([1, 2, 3]), [10, 20, 30]);
eq(f('10', 2)([1, 2, 3]), [2, 4, 6]);
});
it('passes context to functions', function() {
function x(val) {
return this.x * val;
}
function y(val) {
return this.y * val;
}
function z(val) {
return this.z * val;
}
var context = {
a: R.compose(x, y, z),
x: 4,
y: 2,
z: 1
};
eq(context.a(5), 40);
});
it('throws if given no arguments', function() {
assert.throws(
function() { R.compose(); },
function(err) {
return err.constructor === Error &&
err.message === 'compose requires at least one argument';
}
);
});
it('can be applied to one argument', function() {
var f = function(a, b, c) { return [a, b, c]; };
var g = R.compose(f);
eq(g.length, 3);
eq(g(1, 2, 3), [1, 2, 3]);
});
});
describe('compose properties', function() {
jsv.property('composes two functions', jsv.fn(), jsv.fn(), jsv.nat, function(f, g, x) {
return R.equals(R.compose(f, g)(x), f(g(x)));
});
jsv.property('associative', jsv.fn(), jsv.fn(), jsv.fn(), jsv.nat, function(f, g, h, x) {
var result = f(g(h(x)));
return R.all(R.equals(result), [
R.compose(f, g, h)(x),
R.compose(f, R.compose(g, h))(x),
R.compose(R.compose(f, g), h)(x)
]);
});
});
| mit |
Vlatombe/jenkins | core/src/main/java/hudson/cli/Connection.java | 9707 | /*
* The MIT License
*
* Copyright (c) 2011, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import hudson.remoting.ClassFilter;
import hudson.remoting.ObjectInputStreamEx;
import hudson.remoting.SocketChannelStream;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.AlgorithmParameterGenerator;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import org.jenkinsci.remoting.util.AnonymousClassWarnings;
/**
* @deprecated No longer used.
*/
@Deprecated
public class Connection {
public final InputStream in;
public final OutputStream out;
public final DataInputStream din;
public final DataOutputStream dout;
public Connection(Socket socket) throws IOException {
this(SocketChannelStream.in(socket),SocketChannelStream.out(socket));
}
public Connection(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
this.din = new DataInputStream(in);
this.dout = new DataOutputStream(out);
}
//
//
// Convenience methods
//
//
public void writeUTF(String msg) throws IOException {
dout.writeUTF(msg);
}
public String readUTF() throws IOException {
return din.readUTF();
}
public void writeBoolean(boolean b) throws IOException {
dout.writeBoolean(b);
}
public boolean readBoolean() throws IOException {
return din.readBoolean();
}
/**
* Sends a serializable object.
*/
public void writeObject(Object o) throws IOException {
ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(out);
oos.writeObject(o);
// don't close oss, which will close the underlying stream
// no need to flush either, given the way oos is implemented
}
/**
* Receives an object sent by {@link #writeObject(Object)}
*/
public <T> T readObject() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStreamEx(in,
getClass().getClassLoader(), ClassFilter.DEFAULT);
return (T)ois.readObject();
}
public void writeKey(Key key) throws IOException {
writeUTF(new String(Base64.encodeBase64(key.getEncoded())));
}
public X509EncodedKeySpec readKey() throws IOException {
byte[] otherHalf = Base64.decodeBase64(readUTF()); // for historical reasons, we don't use readByteArray()
return new X509EncodedKeySpec(otherHalf);
}
public void writeByteArray(byte[] data) throws IOException {
dout.writeInt(data.length);
dout.write(data);
}
public byte[] readByteArray() throws IOException {
int bufSize = din.readInt();
if (bufSize < 0) {
throw new IOException("DataInputStream unexpectedly returned negative integer");
}
byte[] buf = new byte[bufSize];
din.readFully(buf);
return buf;
}
/**
* Performs a Diffie-Hellman key exchange and produce a common secret between two ends of the connection.
*
* <p>
* DH is also useful as a coin-toss algorithm. Two parties get the same random number without trusting
* each other.
*/
public KeyAgreement diffieHellman(boolean side) throws IOException, GeneralSecurityException {
return diffieHellman(side,512);
}
public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
KeyPair keyPair;
PublicKey otherHalf;
if (side) {
AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(keySize);
KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
keyPair = dh.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
} else {
otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
keyPair = keyPairGen.generateKeyPair();
// send a half and get a half
writeKey(keyPair.getPublic());
}
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(keyPair.getPrivate());
ka.doPhase(otherHalf, true);
return ka;
}
/**
* Upgrades a connection with transport encryption by the specified symmetric cipher.
*
* @return
* A new {@link Connection} object that includes the transport encryption.
*/
public Connection encryptConnection(SecretKey sessionKey, String algorithm) throws IOException, GeneralSecurityException {
Cipher cout = Cipher.getInstance(algorithm);
cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherOutputStream o = new CipherOutputStream(out, cout);
Cipher cin = Cipher.getInstance(algorithm);
cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
CipherInputStream i = new CipherInputStream(in, cin);
return new Connection(i,o);
}
/**
* Given a byte array that contains arbitrary number of bytes, digests or expands those bits into the specified
* number of bytes without loss of entropy.
*
* Cryptographic utility code.
*/
public static byte[] fold(byte[] bytes, int size) {
byte[] r = new byte[size];
for (int i=Math.max(bytes.length,size)-1; i>=0; i-- ) {
r[i%r.length] ^= bytes[i%bytes.length];
}
return r;
}
private String detectKeyAlgorithm(KeyPair kp) {
return detectKeyAlgorithm(kp.getPublic());
}
private String detectKeyAlgorithm(PublicKey kp) {
if (kp instanceof RSAPublicKey) return "RSA";
if (kp instanceof DSAPublicKey) return "DSA";
throw new IllegalArgumentException("Unknown public key type: "+kp);
}
/**
* Used in conjunction with {@link #verifyIdentity(byte[])} to prove
* that we actually own the private key of the given key pair.
*/
public void proveIdentity(byte[] sharedSecret, KeyPair key) throws IOException, GeneralSecurityException {
String algorithm = detectKeyAlgorithm(key);
writeUTF(algorithm);
writeKey(key.getPublic());
Signature sig = Signature.getInstance("SHA1with"+algorithm);
sig.initSign(key.getPrivate());
sig.update(key.getPublic().getEncoded());
sig.update(sharedSecret);
writeObject(sig.sign());
}
/**
* Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get.
*/
public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException {
try {
String serverKeyAlgorithm = readUTF();
PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey());
// verify the identity of the server
Signature sig = Signature.getInstance("SHA1with"+serverKeyAlgorithm);
sig.initVerify(spk);
sig.update(spk.getEncoded());
sig.update(sharedSecret);
sig.verify((byte[]) readObject());
return spk;
} catch (ClassNotFoundException e) {
throw new Error(e); // impossible
}
}
public void close() throws IOException {
in.close();
out.close();
}
}
| mit |
velocic/opengl-tutorial-solutions | 22-loading-3d-models/src/utilities.cpp | 909 | #include <utilities.h>
#include <fstream>
namespace Utilities
{
namespace Math
{
double degreesToRadians(double angle)
{
return (angle * PI) / 180;
}
double radiansToDegrees(double angle)
{
return angle * (180/PI);
}
}
namespace File
{
bool getFileContents(std::vector<uint8_t> &fileBuffer, const std::string &filePath)
{
std::ifstream inFileStream(filePath, std::ios::binary);
if (!inFileStream) {
return false;
}
inFileStream.seekg(0, std::ios::end);
auto fileLength = inFileStream.tellg();
inFileStream.seekg(0, std::ios::beg);
fileBuffer.resize(fileLength);
inFileStream.read(reinterpret_cast<char *>(fileBuffer.data()), fileLength);
return true;
}
}
}
| mit |
manorius/printing_with_node | node_modules/johnny-five/lib/evshield.js | 6044 | var Emitter = require("events").EventEmitter;
var shared;
function Bank(options) {
this.address = options.address;
this.io = options.io;
this.io.i2cConfig();
}
Bank.prototype.read = function(register, numBytes, callback) {
if (register) {
this.io.i2cRead(this.address, register, numBytes, callback);
} else {
this.io.i2cRead(this.address, numBytes, callback);
}
};
Bank.prototype.write = function(register, bytes) {
if (!Array.isArray(bytes)) {
bytes = [bytes];
}
this.io.i2cWrite(this.address, register, bytes);
};
// http://www.nr.edu/csc200/labs-ev3/ev3-user-guide-EN.pdf
function EVS(options) {
if (shared) {
return shared;
}
this.bank = {
a: new Bank({
address: EVS.BANK_A,
io: options.io,
}),
b: new Bank({
address: EVS.BANK_B,
io: options.io,
})
};
shared = this;
}
EVS.shieldPort = function(pin) {
var port = EVS[pin];
if (port === undefined) {
throw new Error("Invalid EVShield pin name");
}
var address, analog, bank, motor, mode, offset, sensor;
var endsWithS1 = false;
if (pin.startsWith("BA")) {
address = EVS.BANK_A;
bank = "a";
} else {
address = EVS.BANK_B;
bank = "b";
}
if (pin.includes("M")) {
motor = pin.endsWith("M1") ? EVS.S1 : EVS.S2;
}
if (pin.includes("S")) {
endsWithS1 = pin.endsWith("S1");
// Used for reading 2 byte integer values from raw sensors
analog = endsWithS1 ? EVS.S1_ANALOG : EVS.S2_ANALOG;
// Sensor Mode (1 or 2?)
mode = endsWithS1 ? EVS.S1_MODE : EVS.S2_MODE;
// Used for read registers
offset = endsWithS1 ? EVS.S1_OFFSET : EVS.S2_OFFSET;
// Used to address "sensor type"
sensor = endsWithS1 ? EVS.S1 : EVS.S2;
}
return {
address: address,
analog: analog,
bank: bank,
mode: mode,
motor: motor,
offset: offset,
port: port,
sensor: sensor,
};
};
EVS.isRawSensor = function(port) {
return port.analog === EVS.S1_ANALOG || port.analog === EVS.S2_ANALOG;
};
EVS.prototype = Object.create(Emitter.prototype, {
constructor: {
value: EVS
}
});
EVS.prototype.setup = function(port, type) {
this.bank[port.bank].write(port.mode, [type]);
};
EVS.prototype.read = function(port, register, numBytes, callback) {
if (port.sensor && port.offset && !EVS.isRawSensor(port)) {
register += port.offset;
}
this.bank[port.bank].read(register, numBytes, callback);
};
EVS.prototype.write = function(port, register, data) {
this.bank[port.bank].write(register, data);
};
/*
* Shield Registers
*/
EVS.BAS1 = 0x01;
EVS.BAS2 = 0x02;
EVS.BBS1 = 0x03;
EVS.BBS2 = 0x04;
EVS.BAM1 = 0x05;
EVS.BAM2 = 0x06;
EVS.BBM1 = 0x07;
EVS.BBM2 = 0x08;
EVS.BANK_A = 0x1A;
EVS.BANK_B = 0x1B;
EVS.S1 = 0x01;
EVS.S2 = 0x02;
EVS.M1 = 0x01;
EVS.M2 = 0x02;
EVS.MM = 0x03;
EVS.Type_NONE = 0x00;
EVS.Type_SWITCH = 0x01;
EVS.Type_ANALOG = 0x02;
EVS.Type_I2C = 0x09;
/*
* Sensor Mode NXT
*/
EVS.Type_NXT_LIGHT_REFLECTED = 0x03;
EVS.Type_NXT_LIGHT = 0x04;
EVS.Type_NXT_COLOR = 0x0D;
EVS.Type_NXT_COLOR_RGBRAW = 0x04;
EVS.Type_NXT_COLORRED = 0x0E;
EVS.Type_NXT_COLORGREEN = 0x0F;
EVS.Type_NXT_COLORBLUE = 0x10;
EVS.Type_NXT_COLORNONE = 0x11;
EVS.Type_DATABIT0_HIGH = 0x40;
/*
* Sensor Port Controls
*/
EVS.S1_MODE = 0x6F;
// EVS.S1_EV3_MODE = 0x6F;
EVS.S1_ANALOG = 0x70;
EVS.S1_OFFSET = 0;
EVS.S2_MODE = 0xA3;
// EVS.S2_EV3_MODE = 0x6F;
EVS.S2_ANALOG = 0xA4;
EVS.S2_OFFSET = 52;
/*
* Sensor Mode EV3
*/
EVS.Type_EV3_LIGHT_REFLECTED = 0x00;
EVS.Type_EV3_LIGHT = 0x01;
EVS.Type_EV3_COLOR = 0x02;
EVS.Type_EV3_COLOR_REFRAW = 0x03;
EVS.Type_EV3_COLOR_RGBRAW = 0x04;
EVS.Type_EV3_TOUCH = 0x12;
EVS.Type_EV3 = 0x13;
/*
* Sensor Read Registers
*/
EVS.Light = 0x83;
EVS.Bump = 0x84;
EVS.ColorMeasure = 0x83;
EVS.Proximity = 0x83;
EVS.Touch = 0x83;
EVS.Ultrasonic = 0x81;
EVS.Mode = 0x81;
/*
* Sensor Read Byte Counts
*/
EVS.Light_Bytes = 2;
EVS.Analog_Bytes = 2;
EVS.Bump_Bytes = 1;
EVS.ColorMeasure_Bytes = 2;
EVS.Proximity_Bytes = 2;
EVS.Touch_Bytes = 1;
/*
* Motor selection
*/
EVS.Motor_1 = 0x01;
EVS.Motor_2 = 0x02;
EVS.Motor_Both = 0x03;
/*
* Motor next action
*/
// stop and let the motor coast.
EVS.Motor_Next_Action_Float = 0x00;
// apply brakes, and resist change to tachometer, but if tach position is forcibly changed, do not restore position
EVS.Motor_Next_Action_Brake = 0x01;
// apply brakes, and restore externally forced change to tachometer
EVS.Motor_Next_Action_BrakeHold = 0x02;
EVS.Motor_Stop = 0x60;
EVS.Motor_Reset = 0x52;
/*
* Motor direction
*/
EVS.Motor_Reverse = 0x00;
EVS.Motor_Forward = 0x01;
/*
* Motor Tachometer movement
*/
// Move the tach to absolute value provided
EVS.Motor_Move_Absolute = 0x00;
// Move the tach relative to previous position
EVS.Motor_Move_Relative = 0x01;
/*
* Motor completion
*/
EVS.Motor_Completion_Dont_Wait = 0x00;
EVS.Motor_Completion_Wait_For = 0x01;
/*
* 0-100
*/
EVS.Speed_Full = 90;
EVS.Speed_Medium = 60;
EVS.Speed_Slow = 25;
/*
* Motor Port Controls
*/
EVS.CONTROL_SPEED = 0x01;
EVS.CONTROL_RAMP = 0x02;
EVS.CONTROL_RELATIVE = 0x04;
EVS.CONTROL_TACHO = 0x08;
EVS.CONTROL_BRK = 0x10;
EVS.CONTROL_ON = 0x20;
EVS.CONTROL_TIME = 0x40;
EVS.CONTROL_GO = 0x80;
EVS.STATUS_SPEED = 0x01;
EVS.STATUS_RAMP = 0x02;
EVS.STATUS_MOVING = 0x04;
EVS.STATUS_TACHO = 0x08;
EVS.STATUS_BREAK = 0x10;
EVS.STATUS_OVERLOAD = 0x20;
EVS.STATUS_TIME = 0x40;
EVS.STATUS_STALL = 0x80;
EVS.COMMAND = 0x41;
EVS.VOLTAGE = 0x6E;
EVS.SETPT_M1 = 0x42;
EVS.SPEED_M1 = 0x46;
EVS.TIME_M1 = 0x47;
EVS.CMD_B_M1 = 0x48;
EVS.CMD_A_M1 = 0x49;
EVS.SETPT_M2 = 0x4A;
EVS.SPEED_M2 = 0x4E;
EVS.TIME_M2 = 0x4F;
EVS.CMD_B_M2 = 0x50;
EVS.CMD_A_M2 = 0x51;
/*
* Motor Read registers.
*/
EVS.POSITION_M1 = 0x52;
EVS.POSITION_M2 = 0x56;
EVS.STATUS_M1 = 0x5A;
EVS.STATUS_M2 = 0x5B;
EVS.TASKS_M1 = 0x5C;
EVS.TASKS_M2 = 0x5D;
EVS.ENCODER_PID = 0x5E;
EVS.SPEED_PID = 0x64;
EVS.PASS_COUNT = 0x6A;
EVS.TOLERANCE = 0x6B;
/*
* Built-in components
*/
EVS.BTN_PRESS = 0xDA;
EVS.RGB_LED = 0xD7;
EVS.CENTER_RGB_LED = 0xDE;
module.exports = EVS;
| mit |
gazarenkov/che-sketch | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/gutter/Gutters.java | 1006 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.api.editor.gutter;
public final class Gutters {
private Gutters() {
}
/** Logical identifer for the breakpoints gutter. */
public static final String BREAKPOINTS_GUTTER = "breakpoints";
/** Logical identifer for the line number gutter. */
public static final String LINE_NUMBERS_GUTTER = "lineNumbers";
/** Logical identifer for the annotations gutter. */
public static final String ANNOTATION_GUTTER = "annotation";
}
| epl-1.0 |
gazarenkov/che-sketch | wsmaster/che-core-api-ssh-shared/src/main/java/org/eclipse/che/api/ssh/shared/Constants.java | 1038 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.ssh.shared;
/**
* Constants for ssh API
*
* @author Sergii Leschenko
*/
public final class Constants {
public static final String LINK_REL_GENERATE_PAIR = "create pair";
public static final String LINK_REL_CREATE_PAIR = "create pair";
public static final String LINK_REL_GET_PAIRS = "get pairs";
public static final String LINK_REL_GET_PAIR = "get pair";
public static final String LINK_REL_REMOVE_PAIR = "remove pair";
private Constants() {}
}
| epl-1.0 |
mnmn111/ec-cube-global | tests/class/util/SC_Utils/SC_Utils_getRealURLTest.php | 2732 | <?php
$HOME = realpath(dirname(__FILE__)) . "/../../../..";
require_once($HOME . "/tests/class/Common_TestCase.php");
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**
* SC_Utils::getRealURL()のテストクラス.
*
*
* @author Hiroko Tamagawa
* @version $Id: SC_Utils_getRealURLTest.php 22144 2012-12-17 05:25:58Z h_yoshimoto $
*/
class SC_Utils_getRealURLTest extends Common_TestCase {
protected function setUp() {
parent::setUp();
}
protected function tearDown() {
parent::tearDown();
}
/////////////////////////////////////////
// TODO ポート番号のためのコロンが必ず入ってしまうのはOK?
public function testGetRealURL_親ディレクトリへの参照を含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/../index.php';
$this->expected = 'http://www.example.jp:/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_親ディレクトリへの参照を複数回含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/bbb/../../ccc/ddd/../index.php';
$this->expected = 'http://www.example.jp:/ccc/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_カレントディレクトリへの参照を含む場合_正しくパースできる() {
$input = 'http://www.example.jp/aaa/./index.php';
$this->expected = 'http://www.example.jp:/aaa/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
public function testGetRealURL_httpsの場合_正しくパースできる() {
$input = 'https://www.example.jp/aaa/./index.php';
$this->expected = 'https://www.example.jp:/aaa/index.php';
$this->actual = SC_Utils::getRealURL($input);
$this->verify();
}
//////////////////////////////////////////
}
| gpl-2.0 |
T0MM0R/magento | web/lib/Zend/Validate/Barcode/Gtin14.php | 1429 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Validate_Barcode_AdapterAbstract
*/
#require_once 'Zend/Validate/Barcode/AdapterAbstract.php';
/**
* @category Zend
* @package Zend_Validate
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Validate_Barcode_Gtin14 extends Zend_Validate_Barcode_AdapterAbstract
{
/**
* Allowed barcode lengths
* @var integer
*/
protected $_length = 14;
/**
* Allowed barcode characters
* @var string
*/
protected $_characters = '0123456789';
/**
* Checksum function
* @var string
*/
protected $_checksum = '_gtin';
}
| gpl-2.0 |
eric-shell/badcamp-d8 | modules/devel/devel_generate/src/Plugin/DevelGenerate/ContentDevelGenerate.php | 16625 | <?php
/**
* @file
* Contains \Drupal\devel_generate\Plugin\DevelGenerate\ContentDevelGenerate.
*/
namespace Drupal\devel_generate\Plugin\DevelGenerate;
use Drupal\comment\CommentManagerInterface;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\devel_generate\DevelGenerateBase;
use Drupal\field\Entity\FieldConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a ContentDevelGenerate plugin.
*
* @DevelGenerate(
* id = "content",
* label = @Translation("content"),
* description = @Translation("Generate a given number of content. Optionally delete current content."),
* url = "content",
* permission = "administer devel_generate",
* settings = {
* "num" = 50,
* "kill" = FALSE,
* "max_comments" = 0,
* "title_length" = 4
* }
* )
*/
class ContentDevelGenerate extends DevelGenerateBase implements ContainerFactoryPluginInterface {
/**
* The node storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeStorage;
/**
* The node type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $nodeTypeStorage;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The comment manager service.
*
* @var \Drupal\comment\CommentManagerInterface
*/
protected $commentManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The url generator service.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param array $plugin_definition
* @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
* The node storage.
* @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
* The node type storage.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
* The url generator service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
*/
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityStorageInterface $node_storage, EntityStorageInterface $node_type_storage, ModuleHandlerInterface $module_handler, CommentManagerInterface $comment_manager = NULL, LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator, DateFormatterInterface $date_formatter) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $module_handler;
$this->nodeStorage = $node_storage;
$this->nodeTypeStorage = $node_type_storage;
$this->commentManager = $comment_manager;
$this->languageManager = $language_manager;
$this->urlGenerator = $url_generator;
$this->dateFormatter = $date_formatter;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$entity_manager = $container->get('entity.manager');
return new static(
$configuration, $plugin_id, $plugin_definition,
$entity_manager->getStorage('node'),
$entity_manager->getStorage('node_type'),
$container->get('module_handler'),
$container->has('comment.manager') ? $container->get('comment.manager') : NULL,
$container->get('language_manager'),
$container->get('url_generator'),
$container->get('date.formatter')
);
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$types = $this->nodeTypeStorage->loadMultiple();
if (empty($types)) {
$create_url = $this->urlGenerator->generateFromRoute('node.type_add');
$this->setMessage($this->t('You do not have any content types that can be generated. <a href="@create-type">Go create a new content type</a>', array('@create-type' => $create_url)), 'error', FALSE);
return;
}
$options = array();
foreach ($types as $type) {
$options[$type->id()] = array(
'type' => array('#markup' => $type->label()),
);
if ($this->commentManager) {
$comment_fields = $this->commentManager->getFields('node');
$map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open'));
$fields = array();
foreach ($comment_fields as $field_name => $info) {
// Find all comment fields for the bundle.
if (in_array($type->id(), $info['bundles'])) {
$instance = FieldConfig::loadByName('node', $type->id(), $field_name);
$default_value = $instance->getDefaultValueLiteral();
$default_mode = reset($default_value);
$fields[] = SafeMarkup::format('@field: !state', array(
'@field' => $instance->label(),
'!state' => $map[$default_mode['status']],
));
}
}
// @todo Refactor display of comment fields.
if (!empty($fields)) {
$options[$type->id()]['comments'] = array(
'data' => array(
'#theme' => 'item_list',
'#items' => $fields,
),
);
}
else {
$options[$type->id()]['comments'] = $this->t('No comment fields');
}
}
}
$header = array(
'type' => $this->t('Content type'),
);
if ($this->commentManager) {
$header['comments'] = array(
'data' => $this->t('Comments'),
'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
);
}
$form['node_types'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
);
$form['kill'] = array(
'#type' => 'checkbox',
'#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'),
'#default_value' => $this->getSetting('kill'),
);
$form['num'] = array(
'#type' => 'number',
'#title' => $this->t('How many nodes would you like to generate?'),
'#default_value' => $this->getSetting('num'),
'#required' => TRUE,
'#min' => 0,
);
$options = array(1 => $this->t('Now'));
foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
$options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
}
$form['time_range'] = array(
'#type' => 'select',
'#title' => $this->t('How far back in time should the nodes be dated?'),
'#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'),
'#options' => $options,
'#default_value' => 604800,
);
$form['max_comments'] = array(
'#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value',
'#title' => $this->t('Maximum number of comments per node.'),
'#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'),
'#default_value' => $this->getSetting('max_comments'),
'#min' => 0,
'#access' => $this->moduleHandler->moduleExists('comment'),
);
$form['title_length'] = array(
'#type' => 'number',
'#title' => $this->t('Maximum number of words in titles'),
'#default_value' => $this->getSetting('title_length'),
'#required' => TRUE,
'#min' => 1,
'#max' => 255,
);
$form['add_alias'] = array(
'#type' => 'checkbox',
'#disabled' => !$this->moduleHandler->moduleExists('path'),
'#description' => $this->t('Requires path.module'),
'#title' => $this->t('Add an url alias for each node.'),
'#default_value' => FALSE,
);
$form['add_statistics'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Add statistics for each node (node_counter table).'),
'#default_value' => TRUE,
'#access' => $this->moduleHandler->moduleExists('statistics'),
);
$options = array();
// We always need a language.
$languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
foreach ($languages as $langcode => $language) {
$options[$langcode] = $language->getName();
}
$form['add_language'] = array(
'#type' => 'select',
'#title' => $this->t('Set language on nodes'),
'#multiple' => TRUE,
'#description' => $this->t('Requires locale.module'),
'#options' => $options,
'#default_value' => array(
$this->languageManager->getDefaultLanguage()->getId(),
),
);
$form['#redirect'] = FALSE;
return $form;
}
/**
* {@inheritdoc}
*/
protected function generateElements(array $values) {
if ($values['num'] <= 50 && $values['max_comments'] <= 10) {
$this->generateContent($values);
}
else {
$this->generateBatchContent($values);
}
}
/**
* Method responsible for creating content when
* the number of elements is less than 50.
*/
private function generateContent($values) {
$values['node_types'] = array_filter($values['node_types']);
if (!empty($values['kill']) && $values['node_types']) {
$this->contentKill($values);
}
if (!empty($values['node_types'])) {
// Generate nodes.
$this->develGenerateContentPreNode($values);
$start = time();
for ($i = 1; $i <= $values['num']; $i++) {
$this->develGenerateContentAddNode($values);
if (function_exists('drush_log') && $i % drush_get_option('feedback', 1000) == 0) {
$now = time();
drush_log(dt('Completed !feedback nodes (!rate nodes/min)', array('!feedback' => drush_get_option('feedback', 1000), '!rate' => (drush_get_option('feedback', 1000) * 60) / ($now - $start))), 'ok');
$start = $now;
}
}
}
$this->setMessage($this->formatPlural($values['num'], '1 node created.', 'Finished creating @count nodes'));
}
/**
* Method responsible for creating content when
* the number of elements is greater than 50.
*/
private function generateBatchContent($values) {
// Setup the batch operations and save the variables.
$operations[] = array('devel_generate_operation', array($this, 'batchContentPreNode', $values));
// Add the kill operation.
if ($values['kill']) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentKill', $values));
}
// Add the operations to create the nodes.
for ($num = 0; $num < $values['num']; $num ++) {
$operations[] = array('devel_generate_operation', array($this, 'batchContentAddNode', $values));
}
// Start the batch.
$batch = array(
'title' => $this->t('Generating Content'),
'operations' => $operations,
'finished' => 'devel_generate_batch_finished',
'file' => drupal_get_path('module', 'devel_generate') . '/devel_generate.batch.inc',
);
batch_set($batch);
}
public function batchContentPreNode($vars, &$context) {
$context['results'] = $vars;
$context['results']['num'] = 0;
$this->develGenerateContentPreNode($context['results']);
}
public function batchContentAddNode($vars, &$context) {
$this->develGenerateContentAddNode($context['results']);
$context['results']['num']++;
}
public function batchContentKill($vars, &$context) {
$this->contentKill($context['results']);
}
/**
* {@inheritdoc}
*/
public function validateDrushParams($args) {
$add_language = drush_get_option('languages');
if (!empty($add_language)) {
$add_language = explode(',', str_replace(' ', '', $add_language));
// Intersect with the enabled languages to make sure the language args
// passed are actually enabled.
$values['values']['add_language'] = array_intersect($add_language, array_keys($this->languageManager->getLanguages(LanguageInterface::STATE_ALL)));
}
$values['kill'] = drush_get_option('kill');
$values['title_length'] = 6;
$values['num'] = array_shift($args);
$values['max_comments'] = array_shift($args);
$all_types = array_keys(node_type_get_names());
$default_types = array_intersect(array('page', 'article'), $all_types);
$selected_types = _convert_csv_to_array(drush_get_option('types', $default_types));
if (empty($selected_types)) {
return drush_set_error('DEVEL_GENERATE_NO_CONTENT_TYPES', dt('No content types available'));
}
$values['node_types'] = array_combine($selected_types, $selected_types);
$node_types = array_filter($values['node_types']);
if (!empty($values['kill']) && empty($node_types)) {
return drush_set_error('DEVEL_GENERATE_INVALID_INPUT', dt('Please provide content type (--types) in which you want to delete the content.'));
}
return $values;
}
/**
* Deletes all nodes of given node types.
*
* @param array $values
* The input values from the settings form.
*/
protected function contentKill($values) {
$nids = $this->nodeStorage->getQuery()
->condition('type', $values['node_types'], 'IN')
->execute();
if (!empty($nids)) {
$nodes = $this->nodeStorage->loadMultiple($nids);
$this->nodeStorage->delete($nodes);
$this->setMessage($this->t('Deleted %count nodes.', array('%count' => count($nids))));
}
}
/**
* Return the same array passed as parameter
* but with an array of uids for the key 'users'.
*/
protected function develGenerateContentPreNode(&$results) {
// Get user id.
$users = $this->getUsers();
$users = array_merge($users, array('0'));
$results['users'] = $users;
}
/**
* Create one node. Used by both batch and non-batch code branches.
*/
protected function develGenerateContentAddNode(&$results) {
if (!isset($results['time_range'])) {
$results['time_range'] = 0;
}
$users = $results['users'];
$node_type = array_rand(array_filter($results['node_types']));
$uid = $users[array_rand($users)];
$node = $this->nodeStorage->create(array(
'nid' => NULL,
'type' => $node_type,
'title' => $this->getRandom()->sentences(mt_rand(1, $results['title_length']), TRUE),
'uid' => $uid,
'revision' => mt_rand(0, 1),
'status' => TRUE,
'promote' => mt_rand(0, 1),
'created' => REQUEST_TIME - mt_rand(0, $results['time_range']),
'langcode' => $this->getLangcode($results),
));
// A flag to let hook_node_insert() implementations know that this is a
// generated node.
$node->devel_generate = $results;
// Populate all fields with sample values.
$this->populateFields($node);
// See devel_generate_node_insert() for actions that happen before and after
// this save.
$node->save();
}
/**
* Determine language based on $results.
*/
protected function getLangcode($results) {
if (isset($results['add_language'])) {
$langcodes = $results['add_language'];
$langcode = $langcodes[array_rand($langcodes)];
}
else {
$langcode = $this->languageManager->getDefaultLanguage()->getId();
}
return $langcode;
}
/**
* Retrive 50 uids from the database.
*/
protected function getUsers() {
$users = array();
$result = db_query_range("SELECT uid FROM {users}", 0, 50);
foreach ($result as $record) {
$users[] = $record->uid;
}
return $users;
}
}
| gpl-2.0 |
TaymourReda/-https-github.com-adempiere-adempiere | base/src/org/compiere/model/X_AD_ImpFormat.java | 6439 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for AD_ImpFormat
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_AD_ImpFormat extends PO implements I_AD_ImpFormat, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20150223L;
/** Standard Constructor */
public X_AD_ImpFormat (Properties ctx, int AD_ImpFormat_ID, String trxName)
{
super (ctx, AD_ImpFormat_ID, trxName);
/** if (AD_ImpFormat_ID == 0)
{
setAD_ImpFormat_ID (0);
setAD_Table_ID (0);
setFormatType (null);
setName (null);
setProcessing (false);
} */
}
/** Load Constructor */
public X_AD_ImpFormat (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_ImpFormat[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Import Format.
@param AD_ImpFormat_ID Import Format */
public void setAD_ImpFormat_ID (int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_ImpFormat_ID, Integer.valueOf(AD_ImpFormat_ID));
}
/** Get Import Format.
@return Import Format */
public int getAD_ImpFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ImpFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** FormatType AD_Reference_ID=209 */
public static final int FORMATTYPE_AD_Reference_ID=209;
/** Fixed Position = F */
public static final String FORMATTYPE_FixedPosition = "F";
/** Comma Separated = C */
public static final String FORMATTYPE_CommaSeparated = "C";
/** Tab Separated = T */
public static final String FORMATTYPE_TabSeparated = "T";
/** XML = X */
public static final String FORMATTYPE_XML = "X";
/** Custom Separator Char = U */
public static final String FORMATTYPE_CustomSeparatorChar = "U";
/** Set Format.
@param FormatType
Format of the data
*/
public void setFormatType (String FormatType)
{
set_Value (COLUMNNAME_FormatType, FormatType);
}
/** Get Format.
@return Format of the data
*/
public String getFormatType ()
{
return (String)get_Value(COLUMNNAME_FormatType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Separator Character.
@param SeparatorChar Separator Character */
public void setSeparatorChar (String SeparatorChar)
{
set_Value (COLUMNNAME_SeparatorChar, SeparatorChar);
}
/** Get Separator Character.
@return Separator Character */
public String getSeparatorChar ()
{
return (String)get_Value(COLUMNNAME_SeparatorChar);
}
} | gpl-2.0 |
shakalaca/ASUS_ZenFone_A450CG | external/proguard/src/proguard/obfuscate/MappingPrinter.java | 4505 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.obfuscate;
import proguard.classfile.*;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import java.io.PrintStream;
/**
* This ClassVisitor prints out the renamed classes and class members with
* their old names and new names.
*
* @see ClassRenamer
*
* @author Eric Lafortune
*/
public class MappingPrinter
extends SimplifiedVisitor
implements ClassVisitor,
MemberVisitor
{
private final PrintStream ps;
/**
* Creates a new MappingPrinter that prints to <code>System.out</code>.
*/
public MappingPrinter()
{
this(System.out);
}
/**
* Creates a new MappingPrinter that prints to the given stream.
* @param printStream the stream to which to print
*/
public MappingPrinter(PrintStream printStream)
{
this.ps = printStream;
}
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
String name = programClass.getName();
String newName = ClassObfuscator.newClassName(programClass);
ps.println(ClassUtil.externalClassName(name) +
" -> " +
ClassUtil.externalClassName(newName) +
":");
// Print out the class members.
programClass.fieldsAccept(this);
programClass.methodsAccept(this);
}
public void visitLibraryClass(LibraryClass libraryClass)
{
}
// Implementations for MemberVisitor.
public void visitProgramField(ProgramClass programClass, ProgramField programField)
{
String newName = MemberObfuscator.newMemberName(programField);
if (newName != null)
{
ps.println(" " +
//lineNumberRange(programClass, programField) +
ClassUtil.externalFullFieldDescription(
0,
programField.getName(programClass),
programField.getDescriptor(programClass)) +
" -> " +
newName);
}
}
public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
{
// Special cases: <clinit> and <init> are always kept unchanged.
// We can ignore them here.
String name = programMethod.getName(programClass);
if (name.equals(ClassConstants.INTERNAL_METHOD_NAME_CLINIT) ||
name.equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))
{
return;
}
String newName = MemberObfuscator.newMemberName(programMethod);
if (newName != null)
{
ps.println(" " +
lineNumberRange(programClass, programMethod) +
ClassUtil.externalFullMethodDescription(
programClass.getName(),
0,
programMethod.getName(programClass),
programMethod.getDescriptor(programClass)) +
" -> " +
newName);
}
}
// Small utility methods.
/**
* Returns the line number range of the given class member, followed by a
* colon, or just an empty String if no range is available.
*/
private static String lineNumberRange(ProgramClass programClass, ProgramMember programMember)
{
String range = programMember.getLineNumberRange(programClass);
return range != null ?
(range + ":") :
"";
}
}
| gpl-2.0 |
vk-com/kphp-kdb | drinkless/dl-utils.c | 13193 | /*
This file is part of VK/KittenPHP-DB-Engine Library.
VK/KittenPHP-DB-Engine Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
VK/KittenPHP-DB-Engine Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with VK/KittenPHP-DB-Engine Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010-2013 Vkontakte Ltd
2010-2013 Arseny Smirnov
2010-2013 Aliaksei Levin
*/
#define _FILE_OFFSET_BITS 64
#include <assert.h>
#include <execinfo.h>
#include <fcntl.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "crc32.h"
#include "dl-utils.h"
//TODO very-very bad
extern int now;
extern int verbosity;
extern char *progname;
char *fnames[MAX_FN];
int fd[MAX_FN];
long long fsize[MAX_FN];
off_t fpos[MAX_FN];
char fread_only[MAX_FN];
int dl_open_file (int x, const char *fname, int creat) {
if (x < 0 || x >= MAX_FN) {
fprintf (stderr, "%s: cannot open %s, bad local fid %d: %m\n", progname, fname, x);
return -1;
}
fnames[x] = dl_strdup (fname);
int options;
if (creat > 0) {
options = O_RDWR | O_CREAT;
if (creat == 2) {
options |= O_TRUNC;
}
} else {
fread_only[x] = 1;
options = O_RDONLY;
}
fd[x] = open (fname, options, 0600);
if (creat < 0 && fd[x] < 0) {
fprintf (stderr, "%s: cannot open %s: %m\n", progname, fname);
return -1;
}
if (fd[x] < 0) {
fprintf (stderr, "%s: cannot open %s: %m\n", progname, fname);
exit (1);
}
fsize[x] = lseek (fd[x], 0, SEEK_END);
if (fsize[x] < 0) {
fprintf (stderr, "%s: cannot seek %s: %m\n", progname, fname);
exit (2);
}
lseek (fd[x], 0, SEEK_SET);
if (verbosity) {
fprintf (stderr, "opened file %s, fd=%d, size=%lld\n", fname, fd[x], fsize[x]);
}
fpos[x] = 0;
return fd[x];
}
off_t dl_file_seek (int x, off_t offset, int whence) {
assert (0 <= x && x < MAX_FN);
assert (fd[x] != -1);
off_t res = lseek (fd[x], offset, whence);
if (res != (off_t)-1) {
fpos[x] = res;
}
return res;
}
void dl_close_file (int x) {
assert (0 <= x && x < MAX_FN);
assert (fd[x] != -1);
if (!fread_only[x]) {
assert (fsync (fd[x]) >= 0);
} else {
fread_only[x] = 0;
}
assert (close (fd[x]) >= 0);
fd[x] = -1;
fsize[x] = 0;
fpos[x] = 0;
dl_free (fnames[x], strlen (fnames[x]) + 1);
fnames[x] = NULL;
}
void dl_zout_raw_init (dl_zout *f) {
memset (f, 0, sizeof (dl_zout));
}
void dl_zout_free_buffer (dl_zout *f) {
if (f->buf != NULL) {
dl_free (f->buf, f->buf_len);
f->buf = NULL;
f->buf_len = 0;
}
}
void dl_zout_set_buffer_len (dl_zout *f, int len) {
assert (f->ptr == f->buf);
if (f->buf_len != len) {
dl_zout_free_buffer (f);
f->buf_len = len;
assert ("Too small buffer for output" && f->buf_len > 8);
f->buf = dl_malloc ((size_t)f->buf_len);
}
f->ptr = f->buf;
f->left = f->buf_len;
}
void dl_zout_set_crc32_flag (dl_zout *f, int flag) {
f->use_crc32 = flag;
f->crc32_complement = 0xFFFFFFFF;
}
void dl_zout_reset_crc32 (dl_zout *f) {
//TODO: make it with f->crc32_ptr
dl_zout_flush (f);
f->crc32_complement = 0xFFFFFFFF;
}
unsigned int dl_zout_get_crc32 (dl_zout *f) {
//TODO: make it with f->crc32_ptr
dl_zout_flush (f);
return ~f->crc32_complement;
}
void dl_zout_set_file_id (dl_zout *f, int fid) {
f->id = fid;
f->written = 0;
}
void dl_zout_init (dl_zout *f, int id, int len) {
dl_zout_raw_init (f);
dl_zout_set_file_id (f, id);
dl_zout_set_buffer_len (f, len);
dl_zout_set_crc32_flag (f, 1);
}
static int dl_zout_write_impl (dl_zout *f, const void *src, int len) {
assert (write (fd[f->id], src, (size_t)len) == len);
fpos[f->id] += len;
if (f->use_crc32) {
f->crc32_complement = crc32_partial (src, len, f->crc32_complement);
}
f->written += len;
return len;
}
void dl_zout_flush (dl_zout *f) {
ssize_t d = f->ptr - f->buf;
if (d) {
dl_zout_write_impl (f, f->buf, d);
f->ptr = f->buf;
f->left = f->buf_len;
}
}
void *dl_zout_alloc_log_event (dl_zout *f, int type, int bytes) {
int adj_bytes = -bytes & 3;
bytes = (bytes + 3) & -4;
if (bytes > f->left) {
dl_zout_flush (f);
}
assert (bytes >= 4 && bytes <= f->left);
void *EV = f->ptr;
f->ptr += bytes;
f->left -= bytes;
*(unsigned int *)EV = (unsigned int)type;
if (adj_bytes) {
memset (f->ptr - adj_bytes, adj_bytes, (size_t)adj_bytes);
}
return EV;
}
struct lev_crc32 *dl_zout_write_lev_crc32 (dl_zout *f) {
dl_zout_flush (f);
struct lev_crc32 *E = dl_zout_alloc_log_event (f, LEV_CRC32, sizeof (struct lev_crc32));
E->timestamp = now;
E->pos = f->written;
E->crc32 = ~f->crc32_complement;
return E;
}
int dl_zout_log_event_write (dl_zout *f, const void *src, int len) {
int adj_bytes = -len & 3;
while (len) {
int cur = len;
if (f->left < len) {
cur = f->left;
}
memcpy (f->ptr, src, (size_t)cur);
f->ptr += cur;
f->left -= cur;
if ((len -= cur)) {
dl_zout_flush (f);
src += cur;
}
}
if (f->left < adj_bytes) {
dl_zout_flush (f);
}
memset (f->ptr, adj_bytes, (size_t)adj_bytes);
f->ptr += adj_bytes;
f->left -= adj_bytes;
return len;
}
int dl_zout_write (dl_zout *f, const void *src, int len) {
if (unlikely (len > f->buf_len)) {
dl_zout_flush (f);
return dl_zout_write_impl (f, src, len);
}
int save_len = len;
while (len) {
int cur = len;
if (f->left < len) {
cur = f->left;
}
memcpy (f->ptr, src, (size_t)cur);
f->ptr += cur;
f->left -= cur;
if ((len -= cur)) {
dl_zout_flush (f);
src += cur;
}
}
return save_len;
}
off_t dl_zout_pos (dl_zout *f) {
return fpos[f->id] + (f->ptr - f->buf);
}
void dl_zout_free (dl_zout *f) {
dl_zout_flush (f); //save for legacy
dl_zout_free_buffer (f);
}
void dl_zin_init (dl_zin *f, int id, int len) {
f->buf_len = len;
f->id = id;
assert ("Too small buffer for input" && f->buf_len > 8);
f->ptr = f->buf = dl_malloc ((size_t)f->buf_len);
f->left = 0;
off_t cur = lseek (fd[f->id], 0, SEEK_CUR),
end = lseek (fd[f->id], 0, SEEK_END);
lseek (fd[f->id], cur, SEEK_SET);
f->r_left = end - cur;
}
static inline int dl_zin_flush (dl_zin *f) {
assert (f->left == 0);
if (likely(f->r_left)) {
int cur = (int) min ((off_t)f->buf_len, f->r_left);
assert (read (fd[f->id], f->buf, (size_t)cur) == cur);
fpos[f->id] += cur;
f->r_left -= cur;
f->left = cur;
f->ptr = f->buf;
return cur;
} else {
return 0;
}
}
int dl_zin_read (dl_zin *f, void *dest, int len) {
int tmp = len;
while (len) {
int cur = len;
if (cur > f->left) {
cur = f->left;
}
memcpy (dest, f->ptr, (size_t)cur);
f->ptr += cur;
f->left -= cur;
if ((len -= cur) && !dl_zin_flush (f)) {
return tmp - len;
}
dest += cur;
}
return tmp;
}
off_t dl_zin_pos (dl_zin *f) {
return fpos[f->id] - f->left;
}
void dl_zin_free (dl_zin *f) {
dl_free (f->buf, (size_t)f->buf_len);
}
int dl_get_stack_depth (void) {
#define max_depth 50
#define uncounted_depth 12
static void *tmp[max_depth];
int res = backtrace (tmp, max_depth) - uncounted_depth;
return res < 0 ? 0 : res;
}
#if DL_DEBUG_MEM >= 1
# define MEM_POS {\
void *buffer[64]; \
int nptrs = backtrace (buffer, 4); \
fprintf (stderr, "\n------- Stack Backtrace -------\n"); \
backtrace_symbols_fd (buffer + 1, nptrs - 1, 2); \
fprintf (stderr, "-------------------------------\n"); \
}
#else
# define MEM_POS
#endif
struct dl_log_t {
char s[DL_LOG_SIZE];
char v[DL_LOG_SIZE];
int f, i;
int verbosity_stderr, verbosity_log;
} dl_log[LOG_ID_MX];
void dl_log_set_verb (int log_id, int verbosity_stderr, int verbosity_log) {
dl_log[log_id].verbosity_stderr = verbosity_stderr;
dl_log[log_id].verbosity_log = verbosity_log;
}
void dl_log_add (int log_id, int verb, const char *s, ...) {
assert (0 <= log_id && log_id < LOG_ID_MX);
static char tmp[DL_LOG_SIZE];
va_list args;
if (verb > dl_log[log_id].verbosity_stderr && verb > dl_log[log_id].verbosity_log) {
return;
}
va_start (args, s);
static time_t old_timestamp = -1;
time_t timestamp = now ? now : time (NULL);
static int len = 0;
if (timestamp != old_timestamp) {
old_timestamp = timestamp;
len = dl_print_local_time (tmp, DL_LOG_SIZE, timestamp);
assert (len < DL_LOG_SIZE);
}
vsnprintf (tmp + len, (size_t)(DL_LOG_SIZE - len), s, args);
va_end (args);
if (verb <= dl_log[log_id].verbosity_stderr) {
fprintf (stderr, "%s", tmp);
}
if (verb <= dl_log[log_id].verbosity_log) {
char *t = tmp;
while (*t) {
dl_log[log_id].s[dl_log[log_id].i] = *t++;
dl_log[log_id].v[dl_log[log_id].i++] = (char)verb;
if (dl_log[log_id].i == DL_LOG_SIZE) {
dl_log[log_id].i = 0;
dl_log[log_id].f = 1;
}
}
}
}
void dl_log_dump (int log_id, int verb) {
assert (0 <= log_id && log_id < LOG_ID_MX);
int i = (dl_log[log_id].f ? dl_log[log_id].i : 0);
do {
if (dl_log[log_id].s[i] && verb >= dl_log[log_id].v[i]) {
putc (dl_log[log_id].s[i], stderr);
}
if (++i == DL_LOG_SIZE) {
i = 0;
}
} while (dl_log[log_id].i != i);
}
int dl_log_dump_to_buf (int log_id, int verb_min, int verb_max, char *buf, int buf_n, int line_mx) {
assert (0 <= log_id && log_id < LOG_ID_MX);
int i = dl_log[log_id].i, bi = 0;
do {
if (--i == -1) {
i = DL_LOG_SIZE - 1;
}
char c = dl_log[log_id].s[i];
if (unlikely (c == 0)) {
break;
}
if (verb_max >= dl_log[log_id].v[i] && dl_log[log_id].v[i] >= verb_min) {
if (c == '\n') {
if (--line_mx < 0) {
break;
}
}
buf[bi++] = c;
}
} while (dl_log[log_id].i != i && bi + 1 < buf_n);
buf[bi] = 0;
i = 0;
int j = bi - 1;
while (i < j) {
char t = buf[i];
buf[i] = buf[j];
buf[j] = t;
i++, j--;
}
return bi;
}
static void *stack_bottom_ptr = NULL;
void *dl_cur_stack() {
int x;
void *ptr = &x;
return ptr;
}
void dl_init_stack_size() {
stack_bottom_ptr = dl_cur_stack();
}
size_t dl_get_stack_size() {
size_t res = (char *)dl_cur_stack() - (char *)stack_bottom_ptr;
return -res;
}
void dl_runtime_handler (const int sig) {
//signal (sig, SIG_DFL);
fprintf (stderr, "%s caught, terminating program\n", sig == SIGSEGV ? "SIGSEGV" : "SIGABRT");
fprintf (stderr, "----------------- LOG BEGINS -----------------\n");
dl_log_dump (LOG_DEF, 0x7f);
fprintf (stderr, "----------------- HISTORY -----------------\n");
dl_log_dump (LOG_HISTORY, 0x7f);
fprintf (stderr, "----------------- WARNINGS -----------------\n");
dl_log_dump (LOG_WARNINGS, 0x7f);
fprintf (stderr, "----------------- CRITICAL -----------------\n");
dl_log_dump (LOG_CRITICAL, 0x7f);
fprintf (stderr, "----------------- LOG ENDS -----------------\n");
dl_print_backtrace();
dl_print_backtrace_gdb();
_exit (EXIT_FAILURE);
}
void dl_set_debug_handlers (void) {
// signal (SIGFPE, dl_runtime_handler);
dl_signal (SIGSEGV, dl_runtime_handler);
dl_signal (SIGABRT, dl_runtime_handler);
//TODO: move this somewhere else
#ifdef DL_DEBUG_OUT
dl_log_set_verb (LOG_DEF, 3, 3);
#else
dl_log_set_verb (LOG_DEF, 0, 3);
#endif
dl_log_set_verb (LOG_HISTORY, 0, 0x7F);
dl_log_set_verb (LOG_WARNINGS, 0, 9);
dl_log_set_verb (LOG_CRITICAL, 0, 9);
}
int dl_print_local_time (char *buf, int buf_size, time_t timestamp) {
struct tm t;
assert (localtime_r (×tamp, &t));
assert (buf_size > 0);
return snprintf (buf, (size_t)buf_size, "[%4d-%02d-%02d %02d:%02d:%02d local] ", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
}
long long dl_strhash (const char *s) {
unsigned long long h = 0;
while (*s) {
h = h * HASH_MUL + (unsigned long long)*s++;
}
return (long long)h;
}
char *dl_strstr_kmp (const char *a, int *kmp, const char *b) {
int i, j = 0;
for (i = 0; b[i]; i++) {
while (j && a[j] != b[i]) {
j = kmp[j];
}
if (a[j] == b[i]) {
j++;
}
if (!a[j]) {
return (char *)(b + i - j + 1);
}
}
return NULL;
}
void dl_kmp (const char *a, int *kmp) {
if (kmp == NULL) {
return;
}
int i, j = 0;
kmp[0] = 0;
for (i = 0; a[i]; i++) {
while (j && a[i] != a[j]) {
j = kmp[j];
}
if (i != j && a[i] == a[j]) {
j++;
}
kmp[i + 1] = j;
}
}
char *dl_strstr (const char *a, const char *b) {
return (char *)strstr (a, b);
}
| gpl-2.0 |
vanfanel/scummvm | engines/ags/engine/ac/dynobj/cc_gui.cpp | 1695 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "ags/engine/ac/dynobj/cc_gui.h"
#include "ags/engine/ac/dynobj/script_gui.h"
#include "ags/globals.h"
namespace AGS3 {
// return the type name of the object
const char *CCGUI::GetType() {
return "GUI";
}
// serialize the object into BUFFER (which is BUFSIZE bytes)
// return number of bytes used
int CCGUI::Serialize(const char *address, char *buffer, int bufsize) {
const ScriptGUI *shh = (const ScriptGUI *)address;
StartSerialize(buffer);
SerializeInt(shh->id);
return EndSerialize();
}
void CCGUI::Unserialize(int index, const char *serializedData, int dataSize) {
StartUnserialize(serializedData, dataSize);
int num = UnserializeInt();
ccRegisterUnserializedObject(index, &_G(scrGui)[num], this);
}
} // namespace AGS3
| gpl-2.0 |
sjmudd/MaxScale | Documentation/Tutorials/Notification-Service.md | 2753 | # MaxScale Notification Service and Feedback Support
Massimiliano Pinto
Last Updated: 10th March 2015
## Contents
## Document History
<table>
<tr>
<td>Date</td>
<td>Change</td>
<td>Who</td>
</tr>
<tr>
<td>10th March 2015</td>
<td>Initial version</td>
<td>Massimiliano Pinto</td>
</tr>
</table>
## Overview
The purpose of Notification Service in MaxScale is for a customer registered for the service to receive update notices, security bulletins, fixes and workarounds that are tailored to the database server configuration.
## MaxScale Setup
MaxScale may collect the installed plugins and send the information's nightly, between 2:00 AM and 4:59 AM.
It tries to send data and if there is any failure (timeout, server is down, etc), the next retry is in 1800 seconds (30 minutes)
This feature is not enabled by default: MaxScale must be configured in [feedback] section:
[feedback]
feedback_enable=1
feedback_url=https://enterprise.mariadb.com/feedback/post
feedback_user_info=x-y-z-w
The activation code that will be provided by MariaDB corp upon request by the customer and it should be put in feedback_user_info.
Example:
feedback_user_info=0467009f-b04d-45b1-a77b-b6b2ec9c6cf4
MaxScale generates the feedback report containing following information:
-The activation code used to enable feedback
- MaxScale Version
- An identifier of the MaxScale installation, i.e. the HEX encoding of SHA1 digest of the first network interface MAC address
- Operating System (i.e Linux)
- Operating Suystem Distribution (i.e. CentOS release 6.5 (Final))
- All the modules in use in MaxScale and their API and version
- MaxScale server UNIX_TIME at generation time
MaxScale shall send the generated feedback report to a feedback server specified in feedback_url
## Manual Operation
If it’s not possible to send data due to firewall or security settings the report could be generated manually (feedback_user_info is required) via MaxAdmin
MaxScale>show feedbackreport
Report could be saved to report.txt file:
maxadmin -uxxx -pyyy show feedbackreport > ./report.txt
curl -F data=@./report.txt https://mariadb.org/feedback_plugin/post
Report Example:
FEEDBACK_SERVER_UID 6B5C44AEA73137D049B02E6D1C7629EF431A350F
FEEDBACK_USER_INFO 0467009f-b04d-45b1-a77b-b6b2ec9c6cf4
VERSION 1.0.6-unstable
NOW 1425914890
PRODUCT maxscale
Uname_sysname Linux
Uname_distribution CentOS release 6.5 (Final)
module_maxscaled_type Protocol
module_maxscaled_version V1.0.0
module_maxscaled_api 1.0.0
module_maxscaled_releasestatus GA
module_telnetd_type Protocol
module_telnetd_version V1.0.1
module_telnetd_api 1.0.0
module_telnetd_releasestatus GA
| gpl-2.0 |
grate-driver/linux-2.6 | drivers/scsi/lpfc/lpfc_nportdisc.c | 66895 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2004-2009 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* Portions Copyright (C) 2004-2005 Christoph Hellwig *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of version 2 of the GNU General *
* Public License as published by the Free Software Foundation. *
* This program is distributed in the hope that it will be useful. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#include <linux/blkdev.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_vport.h"
#include "lpfc_debugfs.h"
/* Called to verify a rcv'ed ADISC was intended for us. */
static int
lpfc_check_adisc(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct lpfc_name *nn, struct lpfc_name *pn)
{
/* Compare the ADISC rsp WWNN / WWPN matches our internal node
* table entry for that node.
*/
if (memcmp(nn, &ndlp->nlp_nodename, sizeof (struct lpfc_name)))
return 0;
if (memcmp(pn, &ndlp->nlp_portname, sizeof (struct lpfc_name)))
return 0;
/* we match, return success */
return 1;
}
int
lpfc_check_sparm(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct serv_parm *sp, uint32_t class, int flogi)
{
volatile struct serv_parm *hsp = &vport->fc_sparam;
uint16_t hsp_value, ssp_value = 0;
/*
* The receive data field size and buffer-to-buffer receive data field
* size entries are 16 bits but are represented as two 8-bit fields in
* the driver data structure to account for rsvd bits and other control
* bits. Reconstruct and compare the fields as a 16-bit values before
* correcting the byte values.
*/
if (sp->cls1.classValid) {
if (!flogi) {
hsp_value = ((hsp->cls1.rcvDataSizeMsb << 8) |
hsp->cls1.rcvDataSizeLsb);
ssp_value = ((sp->cls1.rcvDataSizeMsb << 8) |
sp->cls1.rcvDataSizeLsb);
if (!ssp_value)
goto bad_service_param;
if (ssp_value > hsp_value) {
sp->cls1.rcvDataSizeLsb =
hsp->cls1.rcvDataSizeLsb;
sp->cls1.rcvDataSizeMsb =
hsp->cls1.rcvDataSizeMsb;
}
}
} else if (class == CLASS1)
goto bad_service_param;
if (sp->cls2.classValid) {
if (!flogi) {
hsp_value = ((hsp->cls2.rcvDataSizeMsb << 8) |
hsp->cls2.rcvDataSizeLsb);
ssp_value = ((sp->cls2.rcvDataSizeMsb << 8) |
sp->cls2.rcvDataSizeLsb);
if (!ssp_value)
goto bad_service_param;
if (ssp_value > hsp_value) {
sp->cls2.rcvDataSizeLsb =
hsp->cls2.rcvDataSizeLsb;
sp->cls2.rcvDataSizeMsb =
hsp->cls2.rcvDataSizeMsb;
}
}
} else if (class == CLASS2)
goto bad_service_param;
if (sp->cls3.classValid) {
if (!flogi) {
hsp_value = ((hsp->cls3.rcvDataSizeMsb << 8) |
hsp->cls3.rcvDataSizeLsb);
ssp_value = ((sp->cls3.rcvDataSizeMsb << 8) |
sp->cls3.rcvDataSizeLsb);
if (!ssp_value)
goto bad_service_param;
if (ssp_value > hsp_value) {
sp->cls3.rcvDataSizeLsb =
hsp->cls3.rcvDataSizeLsb;
sp->cls3.rcvDataSizeMsb =
hsp->cls3.rcvDataSizeMsb;
}
}
} else if (class == CLASS3)
goto bad_service_param;
/*
* Preserve the upper four bits of the MSB from the PLOGI response.
* These bits contain the Buffer-to-Buffer State Change Number
* from the target and need to be passed to the FW.
*/
hsp_value = (hsp->cmn.bbRcvSizeMsb << 8) | hsp->cmn.bbRcvSizeLsb;
ssp_value = (sp->cmn.bbRcvSizeMsb << 8) | sp->cmn.bbRcvSizeLsb;
if (ssp_value > hsp_value) {
sp->cmn.bbRcvSizeLsb = hsp->cmn.bbRcvSizeLsb;
sp->cmn.bbRcvSizeMsb = (sp->cmn.bbRcvSizeMsb & 0xF0) |
(hsp->cmn.bbRcvSizeMsb & 0x0F);
}
memcpy(&ndlp->nlp_nodename, &sp->nodeName, sizeof (struct lpfc_name));
memcpy(&ndlp->nlp_portname, &sp->portName, sizeof (struct lpfc_name));
return 1;
bad_service_param:
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0207 Device %x "
"(%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x) sent "
"invalid service parameters. Ignoring device.\n",
ndlp->nlp_DID,
sp->nodeName.u.wwn[0], sp->nodeName.u.wwn[1],
sp->nodeName.u.wwn[2], sp->nodeName.u.wwn[3],
sp->nodeName.u.wwn[4], sp->nodeName.u.wwn[5],
sp->nodeName.u.wwn[6], sp->nodeName.u.wwn[7]);
return 0;
}
static void *
lpfc_check_elscmpl_iocb(struct lpfc_hba *phba, struct lpfc_iocbq *cmdiocb,
struct lpfc_iocbq *rspiocb)
{
struct lpfc_dmabuf *pcmd, *prsp;
uint32_t *lp;
void *ptr = NULL;
IOCB_t *irsp;
irsp = &rspiocb->iocb;
pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
/* For lpfc_els_abort, context2 could be zero'ed to delay
* freeing associated memory till after ABTS completes.
*/
if (pcmd) {
prsp = list_get_first(&pcmd->list, struct lpfc_dmabuf,
list);
if (prsp) {
lp = (uint32_t *) prsp->virt;
ptr = (void *)((uint8_t *)lp + sizeof(uint32_t));
}
} else {
/* Force ulpStatus error since we are returning NULL ptr */
if (!(irsp->ulpStatus)) {
irsp->ulpStatus = IOSTAT_LOCAL_REJECT;
irsp->un.ulpWord[4] = IOERR_SLI_ABORTED;
}
ptr = NULL;
}
return ptr;
}
/*
* Free resources / clean up outstanding I/Os
* associated with a LPFC_NODELIST entry. This
* routine effectively results in a "software abort".
*/
int
lpfc_els_abort(struct lpfc_hba *phba, struct lpfc_nodelist *ndlp)
{
LIST_HEAD(completions);
struct lpfc_sli *psli = &phba->sli;
struct lpfc_sli_ring *pring = &psli->ring[LPFC_ELS_RING];
struct lpfc_iocbq *iocb, *next_iocb;
/* Abort outstanding I/O on NPort <nlp_DID> */
lpfc_printf_vlog(ndlp->vport, KERN_INFO, LOG_DISCOVERY,
"0205 Abort outstanding I/O on NPort x%x "
"Data: x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_flag, ndlp->nlp_state,
ndlp->nlp_rpi);
lpfc_fabric_abort_nport(ndlp);
/* First check the txq */
spin_lock_irq(&phba->hbalock);
list_for_each_entry_safe(iocb, next_iocb, &pring->txq, list) {
/* Check to see if iocb matches the nport we are looking for */
if (lpfc_check_sli_ndlp(phba, pring, iocb, ndlp)) {
/* It matches, so deque and call compl with anp error */
list_move_tail(&iocb->list, &completions);
pring->txq_cnt--;
}
}
/* Next check the txcmplq */
list_for_each_entry_safe(iocb, next_iocb, &pring->txcmplq, list) {
/* Check to see if iocb matches the nport we are looking for */
if (lpfc_check_sli_ndlp(phba, pring, iocb, ndlp)) {
lpfc_sli_issue_abort_iotag(phba, pring, iocb);
}
}
spin_unlock_irq(&phba->hbalock);
/* Cancel all the IOCBs from the completions list */
lpfc_sli_cancel_iocbs(phba, &completions, IOSTAT_LOCAL_REJECT,
IOERR_SLI_ABORTED);
lpfc_cancel_retry_delay_tmo(phba->pport, ndlp);
return 0;
}
static int
lpfc_rcv_plogi(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct lpfc_iocbq *cmdiocb)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_dmabuf *pcmd;
uint32_t *lp;
IOCB_t *icmd;
struct serv_parm *sp;
LPFC_MBOXQ_t *mbox;
struct ls_rjt stat;
int rc;
memset(&stat, 0, sizeof (struct ls_rjt));
if (vport->port_state <= LPFC_FDISC) {
/* Before responding to PLOGI, check for pt2pt mode.
* If we are pt2pt, with an outstanding FLOGI, abort
* the FLOGI and resend it first.
*/
if (vport->fc_flag & FC_PT2PT) {
lpfc_els_abort_flogi(phba);
if (!(vport->fc_flag & FC_PT2PT_PLOGI)) {
/* If the other side is supposed to initiate
* the PLOGI anyway, just ACC it now and
* move on with discovery.
*/
phba->fc_edtov = FF_DEF_EDTOV;
phba->fc_ratov = FF_DEF_RATOV;
/* Start discovery - this should just do
CLEAR_LA */
lpfc_disc_start(vport);
} else
lpfc_initial_flogi(vport);
} else {
stat.un.b.lsRjtRsnCode = LSRJT_LOGICAL_BSY;
stat.un.b.lsRjtRsnCodeExp = LSEXP_NOTHING_MORE;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb,
ndlp, NULL);
return 0;
}
}
pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
lp = (uint32_t *) pcmd->virt;
sp = (struct serv_parm *) ((uint8_t *) lp + sizeof (uint32_t));
if (wwn_to_u64(sp->portName.u.wwn) == 0) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0140 PLOGI Reject: invalid nname\n");
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_INVALID_PNAME;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp,
NULL);
return 0;
}
if (wwn_to_u64(sp->nodeName.u.wwn) == 0) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0141 PLOGI Reject: invalid pname\n");
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_INVALID_NNAME;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp,
NULL);
return 0;
}
if ((lpfc_check_sparm(vport, ndlp, sp, CLASS3, 0) == 0)) {
/* Reject this request because invalid parameters */
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_SPARM_OPTIONS;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp,
NULL);
return 0;
}
icmd = &cmdiocb->iocb;
/* PLOGI chkparm OK */
lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
"0114 PLOGI chkparm OK Data: x%x x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_state, ndlp->nlp_flag,
ndlp->nlp_rpi);
if (vport->cfg_fcp_class == 2 && sp->cls2.classValid)
ndlp->nlp_fcp_info |= CLASS2;
else
ndlp->nlp_fcp_info |= CLASS3;
ndlp->nlp_class_sup = 0;
if (sp->cls1.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS1;
if (sp->cls2.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS2;
if (sp->cls3.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS3;
if (sp->cls4.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS4;
ndlp->nlp_maxframe =
((sp->cmn.bbRcvSizeMsb & 0x0F) << 8) | sp->cmn.bbRcvSizeLsb;
/* no need to reg_login if we are already in one of these states */
switch (ndlp->nlp_state) {
case NLP_STE_NPR_NODE:
if (!(ndlp->nlp_flag & NLP_NPR_ADISC))
break;
case NLP_STE_REG_LOGIN_ISSUE:
case NLP_STE_PRLI_ISSUE:
case NLP_STE_UNMAPPED_NODE:
case NLP_STE_MAPPED_NODE:
lpfc_els_rsp_acc(vport, ELS_CMD_PLOGI, cmdiocb, ndlp, NULL);
return 1;
}
if ((vport->fc_flag & FC_PT2PT) &&
!(vport->fc_flag & FC_PT2PT_PLOGI)) {
/* rcv'ed PLOGI decides what our NPortId will be */
vport->fc_myDID = icmd->un.rcvels.parmRo;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (mbox == NULL)
goto out;
lpfc_config_link(phba, mbox);
mbox->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
mbox->vport = vport;
rc = lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT);
if (rc == MBX_NOT_FINISHED) {
mempool_free(mbox, phba->mbox_mem_pool);
goto out;
}
lpfc_can_disctmo(vport);
}
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox)
goto out;
rc = lpfc_reg_rpi(phba, vport->vpi, icmd->un.rcvels.remoteID,
(uint8_t *) sp, mbox, 0);
if (rc) {
mempool_free(mbox, phba->mbox_mem_pool);
goto out;
}
/* ACC PLOGI rsp command needs to execute first,
* queue this mbox command to be processed later.
*/
mbox->mbox_cmpl = lpfc_mbx_cmpl_reg_login;
/*
* mbox->context2 = lpfc_nlp_get(ndlp) deferred until mailbox
* command issued in lpfc_cmpl_els_acc().
*/
mbox->vport = vport;
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= (NLP_ACC_REGLOGIN | NLP_RCV_PLOGI);
spin_unlock_irq(shost->host_lock);
/*
* If there is an outstanding PLOGI issued, abort it before
* sending ACC rsp for received PLOGI. If pending plogi
* is not canceled here, the plogi will be rejected by
* remote port and will be retried. On a configuration with
* single discovery thread, this will cause a huge delay in
* discovery. Also this will cause multiple state machines
* running in parallel for this node.
*/
if (ndlp->nlp_state == NLP_STE_PLOGI_ISSUE) {
/* software abort outstanding PLOGI */
lpfc_els_abort(phba, ndlp);
}
if ((vport->port_type == LPFC_NPIV_PORT &&
vport->cfg_restrict_login)) {
/* In order to preserve RPIs, we want to cleanup
* the default RPI the firmware created to rcv
* this ELS request. The only way to do this is
* to register, then unregister the RPI.
*/
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_RM_DFLT_RPI;
spin_unlock_irq(shost->host_lock);
stat.un.b.lsRjtRsnCode = LSRJT_INVALID_CMD;
stat.un.b.lsRjtRsnCodeExp = LSEXP_NOTHING_MORE;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb,
ndlp, mbox);
return 1;
}
lpfc_els_rsp_acc(vport, ELS_CMD_PLOGI, cmdiocb, ndlp, mbox);
return 1;
out:
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_OUT_OF_RESOURCE;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp, NULL);
return 0;
}
static int
lpfc_rcv_padisc(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct lpfc_iocbq *cmdiocb)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_dmabuf *pcmd;
struct serv_parm *sp;
struct lpfc_name *pnn, *ppn;
struct ls_rjt stat;
ADISC *ap;
IOCB_t *icmd;
uint32_t *lp;
uint32_t cmd;
pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
lp = (uint32_t *) pcmd->virt;
cmd = *lp++;
if (cmd == ELS_CMD_ADISC) {
ap = (ADISC *) lp;
pnn = (struct lpfc_name *) & ap->nodeName;
ppn = (struct lpfc_name *) & ap->portName;
} else {
sp = (struct serv_parm *) lp;
pnn = (struct lpfc_name *) & sp->nodeName;
ppn = (struct lpfc_name *) & sp->portName;
}
icmd = &cmdiocb->iocb;
if (icmd->ulpStatus == 0 && lpfc_check_adisc(vport, ndlp, pnn, ppn)) {
if (cmd == ELS_CMD_ADISC) {
lpfc_els_rsp_adisc_acc(vport, cmdiocb, ndlp);
} else {
lpfc_els_rsp_acc(vport, ELS_CMD_PLOGI, cmdiocb, ndlp,
NULL);
}
return 1;
}
/* Reject this request because invalid parameters */
stat.un.b.lsRjtRsvd0 = 0;
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_SPARM_OPTIONS;
stat.un.b.vendorUnique = 0;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp, NULL);
/* 1 sec timeout */
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
ndlp->nlp_prev_state = ndlp->nlp_state;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
return 0;
}
static int
lpfc_rcv_logo(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct lpfc_iocbq *cmdiocb, uint32_t els_cmd)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
/* Put ndlp in NPR state with 1 sec timeout for plogi, ACC logo */
/* Only call LOGO ACC for first LOGO, this avoids sending unnecessary
* PLOGIs during LOGO storms from a device.
*/
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_LOGO_ACC;
spin_unlock_irq(shost->host_lock);
if (els_cmd == ELS_CMD_PRLO)
lpfc_els_rsp_acc(vport, ELS_CMD_PRLO, cmdiocb, ndlp, NULL);
else
lpfc_els_rsp_acc(vport, ELS_CMD_ACC, cmdiocb, ndlp, NULL);
if ((ndlp->nlp_DID == Fabric_DID) &&
vport->port_type == LPFC_NPIV_PORT) {
lpfc_linkdown_port(vport);
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_FDISC;
} else if ((!(ndlp->nlp_type & NLP_FABRIC) &&
((ndlp->nlp_type & NLP_FCP_TARGET) ||
!(ndlp->nlp_type & NLP_FCP_INITIATOR))) ||
(ndlp->nlp_state == NLP_STE_ADISC_ISSUE)) {
/* Only try to re-login if this is NOT a Fabric Node */
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
}
ndlp->nlp_prev_state = ndlp->nlp_state;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
spin_unlock_irq(shost->host_lock);
/* The driver has to wait until the ACC completes before it continues
* processing the LOGO. The action will resume in
* lpfc_cmpl_els_logo_acc routine. Since part of processing includes an
* unreg_login, the driver waits so the ACC does not get aborted.
*/
return 0;
}
static void
lpfc_rcv_prli(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
struct lpfc_iocbq *cmdiocb)
{
struct lpfc_dmabuf *pcmd;
uint32_t *lp;
PRLI *npr;
struct fc_rport *rport = ndlp->rport;
u32 roles;
pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
lp = (uint32_t *) pcmd->virt;
npr = (PRLI *) ((uint8_t *) lp + sizeof (uint32_t));
ndlp->nlp_type &= ~(NLP_FCP_TARGET | NLP_FCP_INITIATOR);
ndlp->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
if (npr->prliType == PRLI_FCP_TYPE) {
if (npr->initiatorFunc)
ndlp->nlp_type |= NLP_FCP_INITIATOR;
if (npr->targetFunc)
ndlp->nlp_type |= NLP_FCP_TARGET;
if (npr->Retry)
ndlp->nlp_fcp_info |= NLP_FCP_2_DEVICE;
}
if (rport) {
/* We need to update the rport role values */
roles = FC_RPORT_ROLE_UNKNOWN;
if (ndlp->nlp_type & NLP_FCP_INITIATOR)
roles |= FC_RPORT_ROLE_FCP_INITIATOR;
if (ndlp->nlp_type & NLP_FCP_TARGET)
roles |= FC_RPORT_ROLE_FCP_TARGET;
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_RPORT,
"rport rolechg: role:x%x did:x%x flg:x%x",
roles, ndlp->nlp_DID, ndlp->nlp_flag);
fc_remote_port_rolechg(rport, roles);
}
}
static uint32_t
lpfc_disc_set_adisc(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (!(ndlp->nlp_flag & NLP_RPI_VALID)) {
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
return 0;
}
if (!(vport->fc_flag & FC_PT2PT)) {
/* Check config parameter use-adisc or FCP-2 */
if ((vport->cfg_use_adisc && (vport->fc_flag & FC_RSCN_MODE)) ||
ndlp->nlp_fcp_info & NLP_FCP_2_DEVICE) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NPR_ADISC;
spin_unlock_irq(shost->host_lock);
return 1;
}
}
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
lpfc_unreg_rpi(vport, ndlp);
return 0;
}
static uint32_t
lpfc_disc_illegal(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0271 Illegal State Transition: node x%x "
"event x%x, state x%x Data: x%x x%x\n",
ndlp->nlp_DID, evt, ndlp->nlp_state, ndlp->nlp_rpi,
ndlp->nlp_flag);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_plogi_illegal(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
/* This transition is only legal if we previously
* rcv'ed a PLOGI. Since we don't want 2 discovery threads
* working on the same NPortID, do nothing for this thread
* to stop it.
*/
if (!(ndlp->nlp_flag & NLP_RCV_PLOGI)) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0272 Illegal State Transition: node x%x "
"event x%x, state x%x Data: x%x x%x\n",
ndlp->nlp_DID, evt, ndlp->nlp_state, ndlp->nlp_rpi,
ndlp->nlp_flag);
}
return ndlp->nlp_state;
}
/* Start of Discovery State Machine routines */
static uint32_t
lpfc_rcv_plogi_unused_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
if (lpfc_rcv_plogi(vport, ndlp, cmdiocb)) {
return ndlp->nlp_state;
}
return NLP_STE_FREED_NODE;
}
static uint32_t
lpfc_rcv_els_unused_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
lpfc_issue_els_logo(vport, ndlp, 0);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_unused_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_LOGO_ACC;
spin_unlock_irq(shost->host_lock);
lpfc_els_rsp_acc(vport, ELS_CMD_ACC, cmdiocb, ndlp, NULL);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_logo_unused_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
return NLP_STE_FREED_NODE;
}
static uint32_t
lpfc_device_rm_unused_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
return NLP_STE_FREED_NODE;
}
static uint32_t
lpfc_rcv_plogi_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb = arg;
struct lpfc_dmabuf *pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
uint32_t *lp = (uint32_t *) pcmd->virt;
struct serv_parm *sp = (struct serv_parm *) (lp + 1);
struct ls_rjt stat;
int port_cmp;
memset(&stat, 0, sizeof (struct ls_rjt));
/* For a PLOGI, we only accept if our portname is less
* than the remote portname.
*/
phba->fc_stat.elsLogiCol++;
port_cmp = memcmp(&vport->fc_portname, &sp->portName,
sizeof(struct lpfc_name));
if (port_cmp >= 0) {
/* Reject this request because the remote node will accept
ours */
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_CMD_IN_PROGRESS;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp,
NULL);
} else {
if (lpfc_rcv_plogi(vport, ndlp, cmdiocb) &&
(ndlp->nlp_flag & NLP_NPR_2B_DISC) &&
(vport->num_disc_nodes)) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
/* Check if there are more PLOGIs to be sent */
lpfc_more_plogi(vport);
if (vport->num_disc_nodes == 0) {
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~FC_NDISC_ACTIVE;
spin_unlock_irq(shost->host_lock);
lpfc_can_disctmo(vport);
lpfc_end_rscn(vport);
}
}
} /* If our portname was less */
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
struct ls_rjt stat;
memset(&stat, 0, sizeof (struct ls_rjt));
stat.un.b.lsRjtRsnCode = LSRJT_LOGICAL_BSY;
stat.un.b.lsRjtRsnCodeExp = LSEXP_NOTHING_MORE;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp, NULL);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
/* software abort outstanding PLOGI */
lpfc_els_abort(vport->phba, ndlp);
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_els_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
/* software abort outstanding PLOGI */
lpfc_els_abort(phba, ndlp);
if (evt == NLP_EVT_RCV_LOGO) {
lpfc_els_rsp_acc(vport, ELS_CMD_ACC, cmdiocb, ndlp, NULL);
} else {
lpfc_issue_els_logo(vport, ndlp, 0);
}
/* Put ndlp in npr state set plogi timer for 1 sec */
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
ndlp->nlp_prev_state = NLP_STE_PLOGI_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_plogi_plogi_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_hba *phba = vport->phba;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb, *rspiocb;
struct lpfc_dmabuf *pcmd, *prsp, *mp;
uint32_t *lp;
IOCB_t *irsp;
struct serv_parm *sp;
LPFC_MBOXQ_t *mbox;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
if (ndlp->nlp_flag & NLP_ACC_REGLOGIN) {
/* Recovery from PLOGI collision logic */
return ndlp->nlp_state;
}
irsp = &rspiocb->iocb;
if (irsp->ulpStatus)
goto out;
pcmd = (struct lpfc_dmabuf *) cmdiocb->context2;
prsp = list_get_first(&pcmd->list, struct lpfc_dmabuf, list);
lp = (uint32_t *) prsp->virt;
sp = (struct serv_parm *) ((uint8_t *) lp + sizeof (uint32_t));
/* Some switches have FDMI servers returning 0 for WWN */
if ((ndlp->nlp_DID != FDMI_DID) &&
(wwn_to_u64(sp->portName.u.wwn) == 0 ||
wwn_to_u64(sp->nodeName.u.wwn) == 0)) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0142 PLOGI RSP: Invalid WWN.\n");
goto out;
}
if (!lpfc_check_sparm(vport, ndlp, sp, CLASS3, 0))
goto out;
/* PLOGI chkparm OK */
lpfc_printf_vlog(vport, KERN_INFO, LOG_ELS,
"0121 PLOGI chkparm OK Data: x%x x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_state,
ndlp->nlp_flag, ndlp->nlp_rpi);
if (vport->cfg_fcp_class == 2 && (sp->cls2.classValid))
ndlp->nlp_fcp_info |= CLASS2;
else
ndlp->nlp_fcp_info |= CLASS3;
ndlp->nlp_class_sup = 0;
if (sp->cls1.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS1;
if (sp->cls2.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS2;
if (sp->cls3.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS3;
if (sp->cls4.classValid)
ndlp->nlp_class_sup |= FC_COS_CLASS4;
ndlp->nlp_maxframe =
((sp->cmn.bbRcvSizeMsb & 0x0F) << 8) | sp->cmn.bbRcvSizeLsb;
mbox = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!mbox) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0133 PLOGI: no memory for reg_login "
"Data: x%x x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_state,
ndlp->nlp_flag, ndlp->nlp_rpi);
goto out;
}
lpfc_unreg_rpi(vport, ndlp);
if (lpfc_reg_rpi(phba, vport->vpi, irsp->un.elsreq64.remoteID,
(uint8_t *) sp, mbox, 0) == 0) {
switch (ndlp->nlp_DID) {
case NameServer_DID:
mbox->mbox_cmpl = lpfc_mbx_cmpl_ns_reg_login;
break;
case FDMI_DID:
mbox->mbox_cmpl = lpfc_mbx_cmpl_fdmi_reg_login;
break;
default:
mbox->mbox_cmpl = lpfc_mbx_cmpl_reg_login;
}
mbox->context2 = lpfc_nlp_get(ndlp);
mbox->vport = vport;
if (lpfc_sli_issue_mbox(phba, mbox, MBX_NOWAIT)
!= MBX_NOT_FINISHED) {
lpfc_nlp_set_state(vport, ndlp,
NLP_STE_REG_LOGIN_ISSUE);
return ndlp->nlp_state;
}
/* decrement node reference count to the failed mbox
* command
*/
lpfc_nlp_put(ndlp);
mp = (struct lpfc_dmabuf *) mbox->context1;
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(mbox, phba->mbox_mem_pool);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0134 PLOGI: cannot issue reg_login "
"Data: x%x x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_state,
ndlp->nlp_flag, ndlp->nlp_rpi);
} else {
mempool_free(mbox, phba->mbox_mem_pool);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0135 PLOGI: cannot format reg_login "
"Data: x%x x%x x%x x%x\n",
ndlp->nlp_DID, ndlp->nlp_state,
ndlp->nlp_flag, ndlp->nlp_rpi);
}
out:
if (ndlp->nlp_DID == NameServer_DID) {
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0261 Cannot Register NameServer login\n");
}
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DEFER_RM;
spin_unlock_irq(shost->host_lock);
return NLP_STE_FREED_NODE;
}
static uint32_t
lpfc_cmpl_logo_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_reglogin_plogi_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp, void *arg, uint32_t evt)
{
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_rm_plogi_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NODEV_REMOVE;
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
} else {
/* software abort outstanding PLOGI */
lpfc_els_abort(vport->phba, ndlp);
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
}
static uint32_t
lpfc_device_recov_plogi_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
/* Don't do anything that will mess up processing of the
* previous RSCN.
*/
if (vport->fc_flag & FC_RSCN_DEFERRED)
return ndlp->nlp_state;
/* software abort outstanding PLOGI */
lpfc_els_abort(phba, ndlp);
ndlp->nlp_prev_state = NLP_STE_PLOGI_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_adisc_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb;
/* software abort outstanding ADISC */
lpfc_els_abort(phba, ndlp);
cmdiocb = (struct lpfc_iocbq *) arg;
if (lpfc_rcv_plogi(vport, ndlp, cmdiocb)) {
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_NPR_2B_DISC;
spin_unlock_irq(shost->host_lock);
if (vport->num_disc_nodes)
lpfc_more_adisc(vport);
}
return ndlp->nlp_state;
}
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
lpfc_nlp_set_state(vport, ndlp, NLP_STE_PLOGI_ISSUE);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_adisc_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_prli_acc(vport, cmdiocb, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_adisc_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
/* software abort outstanding ADISC */
lpfc_els_abort(phba, ndlp);
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_adisc_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prlo_adisc_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
/* Treat like rcv logo */
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_PRLO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_adisc_adisc_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb, *rspiocb;
IOCB_t *irsp;
ADISC *ap;
int rc;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
ap = (ADISC *)lpfc_check_elscmpl_iocb(phba, cmdiocb, rspiocb);
irsp = &rspiocb->iocb;
if ((irsp->ulpStatus) ||
(!lpfc_check_adisc(vport, ndlp, &ap->nodeName, &ap->portName))) {
/* 1 sec timeout */
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
memset(&ndlp->nlp_nodename, 0, sizeof(struct lpfc_name));
memset(&ndlp->nlp_portname, 0, sizeof(struct lpfc_name));
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
lpfc_unreg_rpi(vport, ndlp);
return ndlp->nlp_state;
}
if (phba->sli_rev == LPFC_SLI_REV4) {
rc = lpfc_sli4_resume_rpi(ndlp);
if (rc) {
/* Stay in state and retry. */
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
return ndlp->nlp_state;
}
}
if (ndlp->nlp_type & NLP_FCP_TARGET) {
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_MAPPED_NODE);
} else {
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_rm_adisc_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NODEV_REMOVE;
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
} else {
/* software abort outstanding ADISC */
lpfc_els_abort(vport->phba, ndlp);
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
}
static uint32_t
lpfc_device_recov_adisc_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
/* Don't do anything that will mess up processing of the
* previous RSCN.
*/
if (vport->fc_flag & FC_RSCN_DEFERRED)
return ndlp->nlp_state;
/* software abort outstanding ADISC */
lpfc_els_abort(phba, ndlp);
ndlp->nlp_prev_state = NLP_STE_ADISC_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
lpfc_disc_set_adisc(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_plogi(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_prli_acc(vport, cmdiocb, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
LPFC_MBOXQ_t *mb;
LPFC_MBOXQ_t *nextmb;
struct lpfc_dmabuf *mp;
cmdiocb = (struct lpfc_iocbq *) arg;
/* cleanup any ndlp on mbox q waiting for reglogin cmpl */
if ((mb = phba->sli.mbox_active)) {
if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) &&
(ndlp == (struct lpfc_nodelist *) mb->context2)) {
lpfc_nlp_put(ndlp);
mb->context2 = NULL;
mb->mbox_cmpl = lpfc_sli_def_mbox_cmpl;
}
}
spin_lock_irq(&phba->hbalock);
list_for_each_entry_safe(mb, nextmb, &phba->sli.mboxq, list) {
if ((mb->u.mb.mbxCommand == MBX_REG_LOGIN64) &&
(ndlp == (struct lpfc_nodelist *) mb->context2)) {
if (phba->sli_rev == LPFC_SLI_REV4) {
spin_unlock_irq(&phba->hbalock);
lpfc_sli4_free_rpi(phba,
mb->u.mb.un.varRegLogin.rpi);
spin_lock_irq(&phba->hbalock);
}
mp = (struct lpfc_dmabuf *) (mb->context1);
if (mp) {
__lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
}
lpfc_nlp_put(ndlp);
list_del(&mb->list);
phba->sli.mboxq_cnt--;
mempool_free(mb, phba->mbox_mem_pool);
}
}
spin_unlock_irq(&phba->hbalock);
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prlo_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_acc(vport, ELS_CMD_PRLO, cmdiocb, ndlp, NULL);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_reglogin_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
LPFC_MBOXQ_t *pmb = (LPFC_MBOXQ_t *) arg;
MAILBOX_t *mb = &pmb->u.mb;
uint32_t did = mb->un.varWords[1];
if (mb->mbxStatus) {
/* RegLogin failed */
lpfc_printf_vlog(vport, KERN_ERR, LOG_DISCOVERY,
"0246 RegLogin failed Data: x%x x%x x%x\n",
did, mb->mbxStatus, vport->port_state);
/*
* If RegLogin failed due to lack of HBA resources do not
* retry discovery.
*/
if (mb->mbxStatus == MBXERR_RPI_FULL) {
ndlp->nlp_prev_state = NLP_STE_REG_LOGIN_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
return ndlp->nlp_state;
}
/* Put ndlp in npr state set plogi timer for 1 sec */
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
lpfc_issue_els_logo(vport, ndlp, 0);
ndlp->nlp_prev_state = NLP_STE_REG_LOGIN_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
return ndlp->nlp_state;
}
ndlp->nlp_rpi = mb->un.varWords[0];
ndlp->nlp_flag |= NLP_RPI_VALID;
/* Only if we are not a fabric nport do we issue PRLI */
if (!(ndlp->nlp_type & NLP_FABRIC)) {
ndlp->nlp_prev_state = NLP_STE_REG_LOGIN_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_PRLI_ISSUE);
lpfc_issue_els_prli(vport, ndlp, 0);
} else {
ndlp->nlp_prev_state = NLP_STE_REG_LOGIN_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_rm_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NODEV_REMOVE;
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
} else {
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
}
static uint32_t
lpfc_device_recov_reglogin_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
/* Don't do anything that will mess up processing of the
* previous RSCN.
*/
if (vport->fc_flag & FC_RSCN_DEFERRED)
return ndlp->nlp_state;
ndlp->nlp_prev_state = NLP_STE_REG_LOGIN_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
lpfc_disc_set_adisc(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb;
cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_plogi(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_prli_acc(vport, cmdiocb, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
/* Software abort outstanding PRLI before sending acc */
lpfc_els_abort(vport->phba, ndlp);
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
/* This routine is envoked when we rcv a PRLO request from a nport
* we are logged into. We should send back a PRLO rsp setting the
* appropriate bits.
* NEXT STATE = PRLI_ISSUE
*/
static uint32_t
lpfc_rcv_prlo_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_acc(vport, ELS_CMD_PRLO, cmdiocb, ndlp, NULL);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_prli_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb, *rspiocb;
struct lpfc_hba *phba = vport->phba;
IOCB_t *irsp;
PRLI *npr;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
npr = (PRLI *)lpfc_check_elscmpl_iocb(phba, cmdiocb, rspiocb);
irsp = &rspiocb->iocb;
if (irsp->ulpStatus) {
if ((vport->port_type == LPFC_NPIV_PORT) &&
vport->cfg_restrict_login) {
goto out;
}
ndlp->nlp_prev_state = NLP_STE_PRLI_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
return ndlp->nlp_state;
}
/* Check out PRLI rsp */
ndlp->nlp_type &= ~(NLP_FCP_TARGET | NLP_FCP_INITIATOR);
ndlp->nlp_fcp_info &= ~NLP_FCP_2_DEVICE;
if ((npr->acceptRspCode == PRLI_REQ_EXECUTED) &&
(npr->prliType == PRLI_FCP_TYPE)) {
if (npr->initiatorFunc)
ndlp->nlp_type |= NLP_FCP_INITIATOR;
if (npr->targetFunc)
ndlp->nlp_type |= NLP_FCP_TARGET;
if (npr->Retry)
ndlp->nlp_fcp_info |= NLP_FCP_2_DEVICE;
}
if (!(ndlp->nlp_type & NLP_FCP_TARGET) &&
(vport->port_type == LPFC_NPIV_PORT) &&
vport->cfg_restrict_login) {
out:
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_TARGET_REMOVE;
spin_unlock_irq(shost->host_lock);
lpfc_issue_els_logo(vport, ndlp, 0);
ndlp->nlp_prev_state = NLP_STE_PRLI_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
return ndlp->nlp_state;
}
ndlp->nlp_prev_state = NLP_STE_PRLI_ISSUE;
if (ndlp->nlp_type & NLP_FCP_TARGET)
lpfc_nlp_set_state(vport, ndlp, NLP_STE_MAPPED_NODE);
else
lpfc_nlp_set_state(vport, ndlp, NLP_STE_UNMAPPED_NODE);
return ndlp->nlp_state;
}
/*! lpfc_device_rm_prli_issue
*
* \pre
* \post
* \param phba
* \param ndlp
* \param arg
* \param evt
* \return uint32_t
*
* \b Description:
* This routine is envoked when we a request to remove a nport we are in the
* process of PRLIing. We should software abort outstanding prli, unreg
* login, send a logout. We will change node state to UNUSED_NODE, put it
* on plogi list so it can be freed when LOGO completes.
*
*/
static uint32_t
lpfc_device_rm_prli_issue(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NODEV_REMOVE;
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
} else {
/* software abort outstanding PLOGI */
lpfc_els_abort(vport->phba, ndlp);
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
}
/*! lpfc_device_recov_prli_issue
*
* \pre
* \post
* \param phba
* \param ndlp
* \param arg
* \param evt
* \return uint32_t
*
* \b Description:
* The routine is envoked when the state of a device is unknown, like
* during a link down. We should remove the nodelist entry from the
* unmapped list, issue a UNREG_LOGIN, do a software abort of the
* outstanding PRLI command, then free the node entry.
*/
static uint32_t
lpfc_device_recov_prli_issue(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_hba *phba = vport->phba;
/* Don't do anything that will mess up processing of the
* previous RSCN.
*/
if (vport->fc_flag & FC_RSCN_DEFERRED)
return ndlp->nlp_state;
/* software abort outstanding PRLI */
lpfc_els_abort(phba, ndlp);
ndlp->nlp_prev_state = NLP_STE_PRLI_ISSUE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
lpfc_disc_set_adisc(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_unmap_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_plogi(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_unmap_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_prli(vport, ndlp, cmdiocb);
lpfc_els_rsp_prli_acc(vport, cmdiocb, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_unmap_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_unmap_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prlo_unmap_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_acc(vport, ELS_CMD_PRLO, cmdiocb, ndlp, NULL);
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_recov_unmap_node(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
ndlp->nlp_prev_state = NLP_STE_UNMAPPED_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
lpfc_disc_set_adisc(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_mapped_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_plogi(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_mapped_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_els_rsp_prli_acc(vport, cmdiocb, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_mapped_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_mapped_node(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prlo_mapped_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_hba *phba = vport->phba;
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
/* flush the target */
lpfc_sli_abort_iocb(vport, &phba->sli.ring[phba->sli.fcp_ring],
ndlp->nlp_sid, 0, LPFC_CTX_TGT);
/* Treat like rcv logo */
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_PRLO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_recov_mapped_node(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg,
uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
ndlp->nlp_prev_state = NLP_STE_MAPPED_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_NPR_NODE);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
lpfc_disc_set_adisc(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_plogi_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
/* Ignore PLOGI if we have an outstanding LOGO */
if (ndlp->nlp_flag & (NLP_LOGO_SND | NLP_LOGO_ACC))
return ndlp->nlp_state;
if (lpfc_rcv_plogi(vport, ndlp, cmdiocb)) {
lpfc_cancel_retry_delay_tmo(vport, ndlp);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NPR_ADISC | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
} else if (!(ndlp->nlp_flag & NLP_NPR_2B_DISC)) {
/* send PLOGI immediately, move to PLOGI issue state */
if (!(ndlp->nlp_flag & NLP_DELAY_TMO)) {
ndlp->nlp_prev_state = NLP_STE_NPR_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_PLOGI_ISSUE);
lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
}
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prli_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
struct ls_rjt stat;
memset(&stat, 0, sizeof (struct ls_rjt));
stat.un.b.lsRjtRsnCode = LSRJT_UNABLE_TPC;
stat.un.b.lsRjtRsnCodeExp = LSEXP_NOTHING_MORE;
lpfc_els_rsp_reject(vport, stat.un.lsRjtError, cmdiocb, ndlp, NULL);
if (!(ndlp->nlp_flag & NLP_DELAY_TMO)) {
if (ndlp->nlp_flag & NLP_NPR_ADISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
ndlp->nlp_prev_state = NLP_STE_NPR_NODE;
spin_unlock_irq(shost->host_lock);
lpfc_nlp_set_state(vport, ndlp, NLP_STE_ADISC_ISSUE);
lpfc_issue_els_adisc(vport, ndlp, 0);
} else {
ndlp->nlp_prev_state = NLP_STE_NPR_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_PLOGI_ISSUE);
lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
}
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_logo_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_logo(vport, ndlp, cmdiocb, ELS_CMD_LOGO);
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_padisc_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
lpfc_rcv_padisc(vport, ndlp, cmdiocb);
/*
* Do not start discovery if discovery is about to start
* or discovery in progress for this node. Starting discovery
* here will affect the counting of discovery threads.
*/
if (!(ndlp->nlp_flag & NLP_DELAY_TMO) &&
!(ndlp->nlp_flag & NLP_NPR_2B_DISC)) {
if (ndlp->nlp_flag & NLP_NPR_ADISC) {
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
ndlp->nlp_prev_state = NLP_STE_NPR_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_ADISC_ISSUE);
lpfc_issue_els_adisc(vport, ndlp, 0);
} else {
ndlp->nlp_prev_state = NLP_STE_NPR_NODE;
lpfc_nlp_set_state(vport, ndlp, NLP_STE_PLOGI_ISSUE);
lpfc_issue_els_plogi(vport, ndlp->nlp_DID, 0);
}
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_rcv_prlo_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
struct lpfc_iocbq *cmdiocb = (struct lpfc_iocbq *) arg;
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_LOGO_ACC;
spin_unlock_irq(shost->host_lock);
lpfc_els_rsp_acc(vport, ELS_CMD_ACC, cmdiocb, ndlp, NULL);
if ((ndlp->nlp_flag & NLP_DELAY_TMO) == 0) {
mod_timer(&ndlp->nlp_delayfunc, jiffies + HZ * 1);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_DELAY_TMO;
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
spin_unlock_irq(shost->host_lock);
ndlp->nlp_last_elscmd = ELS_CMD_PLOGI;
} else {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~NLP_NPR_ADISC;
spin_unlock_irq(shost->host_lock);
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_plogi_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb, *rspiocb;
IOCB_t *irsp;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
irsp = &rspiocb->iocb;
if (irsp->ulpStatus) {
ndlp->nlp_flag |= NLP_DEFER_RM;
return NLP_STE_FREED_NODE;
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_prli_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb, *rspiocb;
IOCB_t *irsp;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
irsp = &rspiocb->iocb;
if (irsp->ulpStatus && (ndlp->nlp_flag & NLP_NODEV_REMOVE)) {
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_logo_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_DID == Fabric_DID) {
spin_lock_irq(shost->host_lock);
vport->fc_flag &= ~(FC_FABRIC | FC_PUBLIC_LOOP);
spin_unlock_irq(shost->host_lock);
}
lpfc_unreg_rpi(vport, ndlp);
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_adisc_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct lpfc_iocbq *cmdiocb, *rspiocb;
IOCB_t *irsp;
cmdiocb = (struct lpfc_iocbq *) arg;
rspiocb = cmdiocb->context_un.rsp_iocb;
irsp = &rspiocb->iocb;
if (irsp->ulpStatus && (ndlp->nlp_flag & NLP_NODEV_REMOVE)) {
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_cmpl_reglogin_npr_node(struct lpfc_vport *vport,
struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
LPFC_MBOXQ_t *pmb = (LPFC_MBOXQ_t *) arg;
MAILBOX_t *mb = &pmb->u.mb;
if (!mb->mbxStatus) {
ndlp->nlp_rpi = mb->un.varWords[0];
ndlp->nlp_flag |= NLP_RPI_VALID;
} else {
if (ndlp->nlp_flag & NLP_NODEV_REMOVE) {
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
}
return ndlp->nlp_state;
}
static uint32_t
lpfc_device_rm_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if (ndlp->nlp_flag & NLP_NPR_2B_DISC) {
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag |= NLP_NODEV_REMOVE;
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
}
lpfc_drop_node(vport, ndlp);
return NLP_STE_FREED_NODE;
}
static uint32_t
lpfc_device_recov_npr_node(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
/* Don't do anything that will mess up processing of the
* previous RSCN.
*/
if (vport->fc_flag & FC_RSCN_DEFERRED)
return ndlp->nlp_state;
lpfc_cancel_retry_delay_tmo(vport, ndlp);
spin_lock_irq(shost->host_lock);
ndlp->nlp_flag &= ~(NLP_NODEV_REMOVE | NLP_NPR_2B_DISC);
spin_unlock_irq(shost->host_lock);
return ndlp->nlp_state;
}
/* This next section defines the NPort Discovery State Machine */
/* There are 4 different double linked lists nodelist entries can reside on.
* The plogi list and adisc list are used when Link Up discovery or RSCN
* processing is needed. Each list holds the nodes that we will send PLOGI
* or ADISC on. These lists will keep track of what nodes will be effected
* by an RSCN, or a Link Up (Typically, all nodes are effected on Link Up).
* The unmapped_list will contain all nodes that we have successfully logged
* into at the Fibre Channel level. The mapped_list will contain all nodes
* that are mapped FCP targets.
*/
/*
* The bind list is a list of undiscovered (potentially non-existent) nodes
* that we have saved binding information on. This information is used when
* nodes transition from the unmapped to the mapped list.
*/
/* For UNUSED_NODE state, the node has just been allocated .
* For PLOGI_ISSUE and REG_LOGIN_ISSUE, the node is on
* the PLOGI list. For REG_LOGIN_COMPL, the node is taken off the PLOGI list
* and put on the unmapped list. For ADISC processing, the node is taken off
* the ADISC list and placed on either the mapped or unmapped list (depending
* on its previous state). Once on the unmapped list, a PRLI is issued and the
* state changed to PRLI_ISSUE. When the PRLI completion occurs, the state is
* changed to UNMAPPED_NODE. If the completion indicates a mapped
* node, the node is taken off the unmapped list. The binding list is checked
* for a valid binding, or a binding is automatically assigned. If binding
* assignment is unsuccessful, the node is left on the unmapped list. If
* binding assignment is successful, the associated binding list entry (if
* any) is removed, and the node is placed on the mapped list.
*/
/*
* For a Link Down, all nodes on the ADISC, PLOGI, unmapped or mapped
* lists will receive a DEVICE_RECOVERY event. If the linkdown or devloss timers
* expire, all effected nodes will receive a DEVICE_RM event.
*/
/*
* For a Link Up or RSCN, all nodes will move from the mapped / unmapped lists
* to either the ADISC or PLOGI list. After a Nameserver query or ALPA loopmap
* check, additional nodes may be added or removed (via DEVICE_RM) to / from
* the PLOGI or ADISC lists. Once the PLOGI and ADISC lists are populated,
* we will first process the ADISC list. 32 entries are processed initially and
* ADISC is initited for each one. Completions / Events for each node are
* funnelled thru the state machine. As each node finishes ADISC processing, it
* starts ADISC for any nodes waiting for ADISC processing. If no nodes are
* waiting, and the ADISC list count is identically 0, then we are done. For
* Link Up discovery, since all nodes on the PLOGI list are UNREG_LOGIN'ed, we
* can issue a CLEAR_LA and reenable Link Events. Next we will process the PLOGI
* list. 32 entries are processed initially and PLOGI is initited for each one.
* Completions / Events for each node are funnelled thru the state machine. As
* each node finishes PLOGI processing, it starts PLOGI for any nodes waiting
* for PLOGI processing. If no nodes are waiting, and the PLOGI list count is
* indentically 0, then we are done. We have now completed discovery / RSCN
* handling. Upon completion, ALL nodes should be on either the mapped or
* unmapped lists.
*/
static uint32_t (*lpfc_disc_action[NLP_STE_MAX_STATE * NLP_EVT_MAX_EVENT])
(struct lpfc_vport *, struct lpfc_nodelist *, void *, uint32_t) = {
/* Action routine Event Current State */
lpfc_rcv_plogi_unused_node, /* RCV_PLOGI UNUSED_NODE */
lpfc_rcv_els_unused_node, /* RCV_PRLI */
lpfc_rcv_logo_unused_node, /* RCV_LOGO */
lpfc_rcv_els_unused_node, /* RCV_ADISC */
lpfc_rcv_els_unused_node, /* RCV_PDISC */
lpfc_rcv_els_unused_node, /* RCV_PRLO */
lpfc_disc_illegal, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_cmpl_logo_unused_node, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_disc_illegal, /* CMPL_REG_LOGIN */
lpfc_device_rm_unused_node, /* DEVICE_RM */
lpfc_disc_illegal, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_plogi_issue, /* RCV_PLOGI PLOGI_ISSUE */
lpfc_rcv_prli_plogi_issue, /* RCV_PRLI */
lpfc_rcv_logo_plogi_issue, /* RCV_LOGO */
lpfc_rcv_els_plogi_issue, /* RCV_ADISC */
lpfc_rcv_els_plogi_issue, /* RCV_PDISC */
lpfc_rcv_els_plogi_issue, /* RCV_PRLO */
lpfc_cmpl_plogi_plogi_issue, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_cmpl_logo_plogi_issue, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_cmpl_reglogin_plogi_issue,/* CMPL_REG_LOGIN */
lpfc_device_rm_plogi_issue, /* DEVICE_RM */
lpfc_device_recov_plogi_issue, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_adisc_issue, /* RCV_PLOGI ADISC_ISSUE */
lpfc_rcv_prli_adisc_issue, /* RCV_PRLI */
lpfc_rcv_logo_adisc_issue, /* RCV_LOGO */
lpfc_rcv_padisc_adisc_issue, /* RCV_ADISC */
lpfc_rcv_padisc_adisc_issue, /* RCV_PDISC */
lpfc_rcv_prlo_adisc_issue, /* RCV_PRLO */
lpfc_disc_illegal, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_disc_illegal, /* CMPL_LOGO */
lpfc_cmpl_adisc_adisc_issue, /* CMPL_ADISC */
lpfc_disc_illegal, /* CMPL_REG_LOGIN */
lpfc_device_rm_adisc_issue, /* DEVICE_RM */
lpfc_device_recov_adisc_issue, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_reglogin_issue, /* RCV_PLOGI REG_LOGIN_ISSUE */
lpfc_rcv_prli_reglogin_issue, /* RCV_PLOGI */
lpfc_rcv_logo_reglogin_issue, /* RCV_LOGO */
lpfc_rcv_padisc_reglogin_issue, /* RCV_ADISC */
lpfc_rcv_padisc_reglogin_issue, /* RCV_PDISC */
lpfc_rcv_prlo_reglogin_issue, /* RCV_PRLO */
lpfc_cmpl_plogi_illegal, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_disc_illegal, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_cmpl_reglogin_reglogin_issue,/* CMPL_REG_LOGIN */
lpfc_device_rm_reglogin_issue, /* DEVICE_RM */
lpfc_device_recov_reglogin_issue,/* DEVICE_RECOVERY */
lpfc_rcv_plogi_prli_issue, /* RCV_PLOGI PRLI_ISSUE */
lpfc_rcv_prli_prli_issue, /* RCV_PRLI */
lpfc_rcv_logo_prli_issue, /* RCV_LOGO */
lpfc_rcv_padisc_prli_issue, /* RCV_ADISC */
lpfc_rcv_padisc_prli_issue, /* RCV_PDISC */
lpfc_rcv_prlo_prli_issue, /* RCV_PRLO */
lpfc_cmpl_plogi_illegal, /* CMPL_PLOGI */
lpfc_cmpl_prli_prli_issue, /* CMPL_PRLI */
lpfc_disc_illegal, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_disc_illegal, /* CMPL_REG_LOGIN */
lpfc_device_rm_prli_issue, /* DEVICE_RM */
lpfc_device_recov_prli_issue, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_unmap_node, /* RCV_PLOGI UNMAPPED_NODE */
lpfc_rcv_prli_unmap_node, /* RCV_PRLI */
lpfc_rcv_logo_unmap_node, /* RCV_LOGO */
lpfc_rcv_padisc_unmap_node, /* RCV_ADISC */
lpfc_rcv_padisc_unmap_node, /* RCV_PDISC */
lpfc_rcv_prlo_unmap_node, /* RCV_PRLO */
lpfc_disc_illegal, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_disc_illegal, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_disc_illegal, /* CMPL_REG_LOGIN */
lpfc_disc_illegal, /* DEVICE_RM */
lpfc_device_recov_unmap_node, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_mapped_node, /* RCV_PLOGI MAPPED_NODE */
lpfc_rcv_prli_mapped_node, /* RCV_PRLI */
lpfc_rcv_logo_mapped_node, /* RCV_LOGO */
lpfc_rcv_padisc_mapped_node, /* RCV_ADISC */
lpfc_rcv_padisc_mapped_node, /* RCV_PDISC */
lpfc_rcv_prlo_mapped_node, /* RCV_PRLO */
lpfc_disc_illegal, /* CMPL_PLOGI */
lpfc_disc_illegal, /* CMPL_PRLI */
lpfc_disc_illegal, /* CMPL_LOGO */
lpfc_disc_illegal, /* CMPL_ADISC */
lpfc_disc_illegal, /* CMPL_REG_LOGIN */
lpfc_disc_illegal, /* DEVICE_RM */
lpfc_device_recov_mapped_node, /* DEVICE_RECOVERY */
lpfc_rcv_plogi_npr_node, /* RCV_PLOGI NPR_NODE */
lpfc_rcv_prli_npr_node, /* RCV_PRLI */
lpfc_rcv_logo_npr_node, /* RCV_LOGO */
lpfc_rcv_padisc_npr_node, /* RCV_ADISC */
lpfc_rcv_padisc_npr_node, /* RCV_PDISC */
lpfc_rcv_prlo_npr_node, /* RCV_PRLO */
lpfc_cmpl_plogi_npr_node, /* CMPL_PLOGI */
lpfc_cmpl_prli_npr_node, /* CMPL_PRLI */
lpfc_cmpl_logo_npr_node, /* CMPL_LOGO */
lpfc_cmpl_adisc_npr_node, /* CMPL_ADISC */
lpfc_cmpl_reglogin_npr_node, /* CMPL_REG_LOGIN */
lpfc_device_rm_npr_node, /* DEVICE_RM */
lpfc_device_recov_npr_node, /* DEVICE_RECOVERY */
};
int
lpfc_disc_state_machine(struct lpfc_vport *vport, struct lpfc_nodelist *ndlp,
void *arg, uint32_t evt)
{
uint32_t cur_state, rc;
uint32_t(*func) (struct lpfc_vport *, struct lpfc_nodelist *, void *,
uint32_t);
uint32_t got_ndlp = 0;
if (lpfc_nlp_get(ndlp))
got_ndlp = 1;
cur_state = ndlp->nlp_state;
/* DSM in event <evt> on NPort <nlp_DID> in state <cur_state> */
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0211 DSM in event x%x on NPort x%x in "
"state %d Data: x%x\n",
evt, ndlp->nlp_DID, cur_state, ndlp->nlp_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_DSM,
"DSM in: evt:%d ste:%d did:x%x",
evt, cur_state, ndlp->nlp_DID);
func = lpfc_disc_action[(cur_state * NLP_EVT_MAX_EVENT) + evt];
rc = (func) (vport, ndlp, arg, evt);
/* DSM out state <rc> on NPort <nlp_DID> */
if (got_ndlp) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0212 DSM out state %d on NPort x%x Data: x%x\n",
rc, ndlp->nlp_DID, ndlp->nlp_flag);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_DSM,
"DSM out: ste:%d did:x%x flg:x%x",
rc, ndlp->nlp_DID, ndlp->nlp_flag);
/* Decrement the ndlp reference count held for this function */
lpfc_nlp_put(ndlp);
} else {
lpfc_printf_vlog(vport, KERN_INFO, LOG_DISCOVERY,
"0213 DSM out state %d on NPort free\n", rc);
lpfc_debugfs_disc_trc(vport, LPFC_DISC_TRC_DSM,
"DSM out: ste:%d did:x%x flg:x%x",
rc, 0, 0);
}
return rc;
}
| gpl-2.0 |
grueni/pacemaker | include/crm/common/iso8601.h | 4567 | /*
* Copyright (C) 2005 Andrew Beekhof <andrew@beekhof.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* \file
* \brief ISO_8601 Date handling
* \ingroup date
*/
/*
* http://en.wikipedia.org/wiki/ISO_8601
*
*/
#ifndef CRM_COMMON_ISO8601
# define CRM_COMMON_ISO8601
# include <time.h>
# include <ctype.h>
# include <stdbool.h>
typedef struct crm_time_s crm_time_t;
typedef struct crm_time_period_s {
crm_time_t *start;
crm_time_t *end;
crm_time_t *diff;
} crm_time_period_t;
/* Creates a new date/time object conforming to iso8601:
* http://en.wikipedia.org/wiki/ISO_8601
*
* Eg.
* Ordinal: 2010-01 12:00:00 +10:00
* Gregorian: 2010-01-01 12:00:00 +10:00
* ISO Week: 2010-W53-6 12:00:00 +10:00
*
* Notes:
* Only one of date, time is required
* If date or timezone is unspecified, they default to the current one
* Supplying NULL results in the current date/time
* Dashes may be ommitted from dates
* Colons may be ommitted from times and timezones
* A timezone of 'Z' denoted UTC time
*/
crm_time_t *crm_time_new(const char *string);
void crm_time_free(crm_time_t * dt);
char *crm_time_as_string(crm_time_t * dt, int flags);
# define crm_time_log(level, prefix, dt, flags) crm_time_log_alias(level, __FILE__, __FUNCTION__, __LINE__, prefix, dt, flags)
void crm_time_log_alias(int log_level, const char *file, const char *function, int line,
const char *prefix, crm_time_t * date_time, int flags);
# define crm_time_log_date 0x001
# define crm_time_log_timeofday 0x002
# define crm_time_log_with_timezone 0x004
# define crm_time_log_duration 0x008
# define crm_time_ordinal 0x010
# define crm_time_weeks 0x020
# define crm_time_seconds 0x100
# define crm_time_epoch 0x200
crm_time_t *crm_time_parse_duration(const char *duration_str);
crm_time_t *crm_time_calculate_duration(crm_time_t * dt, crm_time_t * value);
crm_time_period_t *crm_time_parse_period(const char *period_str);
int crm_time_compare(crm_time_t * dt, crm_time_t * rhs);
int crm_time_get_timeofday(crm_time_t * dt, uint32_t * h, uint32_t * m, uint32_t * s);
int crm_time_get_timezone(crm_time_t * dt, uint32_t * h, uint32_t * m);
int crm_time_get_gregorian(crm_time_t * dt, uint32_t * y, uint32_t * m, uint32_t * d);
int crm_time_get_ordinal(crm_time_t * dt, uint32_t * y, uint32_t * d);
int crm_time_get_isoweek(crm_time_t * dt, uint32_t * y, uint32_t * w, uint32_t * d);
/* Time in seconds since 0000-01-01 00:00:00Z */
long long int crm_time_get_seconds(crm_time_t * dt);
/* Time in seconds since 1970-01-01 00:00:00Z */
long long int crm_time_get_seconds_since_epoch(crm_time_t * dt);
void crm_time_set(crm_time_t * target, crm_time_t * source);
void crm_time_set_timet(crm_time_t * target, time_t * source);
/* Returns a new time object */
crm_time_t *crm_time_add(crm_time_t * dt, crm_time_t * value);
crm_time_t *crm_time_subtract(crm_time_t * dt, crm_time_t * value);
/* All crm_time_add_... functions support negative values */
void crm_time_add_seconds(crm_time_t * dt, int value);
void crm_time_add_minutes(crm_time_t * dt, int value);
void crm_time_add_hours(crm_time_t * dt, int value);
void crm_time_add_days(crm_time_t * dt, int value);
void crm_time_add_weekdays(crm_time_t * dt, int value);
void crm_time_add_weeks(crm_time_t * dt, int value);
void crm_time_add_months(crm_time_t * dt, int value);
void crm_time_add_years(crm_time_t * dt, int value);
void crm_time_add_ordinalyears(crm_time_t * dt, int value);
void crm_time_add_weekyears(crm_time_t * dt, int value);
/* Useful helper functions */
int crm_time_january1_weekday(int year);
int crm_time_weeks_in_year(int year);
int crm_time_days_in_month(int month, int year);
bool crm_time_leapyear(int year);
bool crm_time_check(crm_time_t * dt);
#endif
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.