content
stringlengths 7
2.61M
|
---|
Tachyon Condensation on Torus and T-duality We find an exact solution, with a nonzero net D-brane charge, in the boundary string field theory of brane-anti-brane pairs on a torus. We explicitly take the T-dual of this configuration. The Nahm-transformation of the instantons is derived from the tachyon condensation. Introduction The open sting tachyon condensation on unstable D-branes have been intensively investigated in the past decade. Among them, the exact solutions of the tachyon condensation, were found in the boundary string field theory * or in the boundary state on R r. Those solutions include the topologically non-trivial solutions, for example, the kink or the vortex, which represent lower dimensional Dbranes, with codimension one and two, respectively. This constructions of lower dimensional D-branes from unstable D-branes by the tachyon condensation were known as the decent relations. On the other hand, we can construct higher dimensional D-branes from lower dimensional unstable D-branes, like the matrix models, by the tachyon condensation on R r, which were known as the ascent relations. Since R r is topologically trivial and non-compact, there is no winding modes and the solutions in the boundary string field theory can have a trivial bundle. Since the torus is simplest non trivial compact manifold, the study of the tachyon condensation on torus will be interesting. However, it will be very difficult to find an exact solution * Recently, the exact solution in the Witten's cubic string field theory for the bosonic string was found in. it may represent a closed string vacuum. Recently, the boundary string field theory was reconstructed via the boundary state. On a torus with the self dual radius, an exact solution of the tachyon condensation of a D−Dbrane pairs was given in by the marginal deformations (the "tachyon" is massless). This solution corresponds to the lower dimensional D−D-brane systems. By the marginal deformation, we always has a D−D-brane or non BPS D-branes which do not have net D-brane charges because of the charge conservation. In this paper we will study the soliton with a net D-brane charge. of a soliton on a D−D-brane pair on a torus. To be explicit, let us consider a vortex soliton of the tachyon of a D2−D2-brane pair on T 2. This soliton will represent a D0-brane. Since the torus is an orbifold of R 2, it seems easy to construct such soliton, however, the orbifolding of the solution is not straightforward. Actually, on R 2 the D0-brane solution is represented by a following non-periodic configuration: in the boundary string field theory. Here T is the tachyon and A and A are the gauge fields on the D2-brane and anti-D2-brane, respectively. This is the exact solution of the equations of motion in the u → ∞ limit. Obviously, it is difficult to extend this solution (1.1) on R 2 to a solution on T 2 = R 2 /Z 2 because of the non periodicity of (1.1). § Moreover, the gauge fields can not be trivial on T 2 because it is a compact space. It will be interesting, but, highly non-trivial to construct a vortex solution (D T ∼ 0) with non-zero A (i). In this paper, we consider the tachyon condensation of D−D-brane pairs on a torus and find exact solutions, which have a net D-brane charge, in the boundary string field theory or the boundary state formalism. Our construction uses infinitely many D−D-brane pairs instead of a pair. By the T-dual transformation, we can change the dimensions of the D−D-brane pairs and we will see that the soliton on the D0−D-brane pairs which represents a D(2p)-brane is the simplest one. As an application of the soliton solution, we can consider the Nahm-transformation which maps an anti-self dual gauge field (instanton) of U(N) with the instanton number k on four dimensional torus T 4 to an anti-self dual configuration of U(k) with the instanton number N on on a dual torusT 4. In string theory, the bound state of N D(p + 4)-branes and k Dp-branes on T 4 is given by the U(N) gauge instanton. If we introduce a probe D(p − 4)-brane and consider the low energy limit on it, the Nahm transformation was interpreted as the T-dual transformation, generalizing the ADHM(N) cases. Recently, the ADHM transformation was given in a D-brane setup without a probe D-brane and nor a low energy limit by the method using the tachyon condensation. For a bound state of two different D-branes, say the D(p + q)-branes and the Dp-branes, this method gives the equivalence between the descriptions using the D(p + q)-branes and using the Dp-branes. This method can be applied to T 4 case and we will see that the § If we take the bundle on the D2-brane as (2.7) and the trivial bundle on the anti-D2-brane, a general tachyon field would be written as where G( 1, 2 ) is a periodic function of. Nahm transformation is naturally interpreted as this equivalence (plus the T-dual transformation). It is worth noticing that this equivalence is exact in, therefore, the N D4-brane with the k instanton on T 4 is equivalent to k D4-branes with the N instanton on the T-dual torusT 4, which has a sub-stringy size if the size of T 4 is much bigger than string scale. This paper is organized as follows. In section 2, we review how to obtain the T-dual picture of the D0-branes on torus, according to. In section 3, we give an exact solution in the boundary string field theory of brane-anti-brane pairs on torus. We take the T-dual of this configuration. The Nahm-transformation of the instantons is derived from the tachyon condensation. We conclude with some discussions in section 4. D0-branes on Torus and T-dual In this section, we will review how to describe D0-branes in type II superstring theory on a (rectangular) torus as an orbifold T r = R r /Z r, whose periodic coordinates 0 ≤ x < 2R, according to and how to take the T-dual of the D0-branes. We consider only the scalars corresponding to the locations of the D0-branes in the torus, X (t), where = 1,..., r although there are many fields on the D0branes. In this paper, the time t is always fixed, and thus abbreviated below. If we consider the time-independent X, it can be considered as the static configuration in the A 0 = 0 gauge. Since T r = R r /Z r, the N D-branes on tours will be equivalent to the N ∞ Dbranes on R r whose coordinates X will be operator valued Hermite N N matrices. Here we regard an ∞ ∞ matrix as an operator. By the orbifolding, we need the following identification with translation operators U along x which should be operator valued N N unitary matrices: where is an N N unitary matrix, i.e. a gauge transformation of the N D-branes. Throughout this paper, we take a convention that an index is not summed over except explicitly indicated by. We will define 2) We assume we can employ off-shell boundary states, which are naive extensions of the boundary state, as in. They have possibility of suffering from divergences when away from onshell background fields. However, the off-shell boundary states have a natural interpretation in consistency with the boundary string field theories. Furthermore, our main concern is the onshell configurations although finding those are not discussed in this paper. Actually, the instanton configurations on torus is expected to be on-shell for all order in as discussed in. A representation of (2.2) is Here is the periodic coordinate of the T-dual torusT r and 0 ≤ < 2L and is the gauge field of the N Dr-branes onT r. Note that this implies that the gauge field () is a connection on theT r, whose component is not necessary a periodic function of. If the bundle of the N Dr-branes onT r with the gauge field () is trivial, i.e. () is periodic, the base of the Hilbert space is spanned by where n ∈ Z and v N is a base of a N-vector. If the bundle of Dr-branes is nontrivial, the base of the Hilbert space will be the sections of the bundle on the dual torusT r. Finally, let us consider a bound state of a D0-brane and m Dr-branes on the torus T r. First, we sketch how to construct a Dr-brane within m D0-branes on the T-dual torusT r. We will consider r = 2 case as an example. The bound state of the D2-brane and the D0-branes onT 2 will be given b where m is an integer which is the D0-brane charge. The transition function (or the gauge transformation) between the different patches is given by Note that this is the exact solution. Here an exact solution means that a solution of the equations of motions of the D2-brane (string field theory) action including all order in the expansions, but leading order in the string coupling g s. Then, from the T-dual map (2.3), we can read the D0-brane configuration X of the bound state of the D0-brane and the m Dr-branes on T r. The gauge transformation of the N D0-branes should not change the (2.2). Thus the transformation is generated by a N N unitary matrix U N N (, ∂ ∂ ) which commutes with U. This is actually a gauge transformation of the N Dr-branes, i.e. a unitary matrix U N N (). D0−D0 pairs on Torus In this section, we will construct a solution which is equivalent to M D(2p)-branes in the boundary string field theory of infinitely many D0−D0-brane pairs on a torus T 2p. First, we consider the infinitely many D0−D0-brane pairs on R 2p. The solution where X is the transverse scalars of D0-branes and the T is the tachyon which acts on the D0-branes and T acts on the anti-D0-branes, which correspond to the antichiral spinors. Here we have set that the anti-D0-branes has the transverse scalars with the same v.e.v as the D0-branes. The operatorsx,p satisfy = i, and is the Dirac gamma matrix of SO(2p) which satisfies Note that T and X act on the Dirac spinors which transformed as a fundamental representation of the U(M) gauge symmetry on the manifold spanned by M D(2p)-branes. Thus the (3.1) can be written as Using this configuration we can construct the M D(2p)-branes with gauge field A (x) on the torus T 2p, which is spanned by 0 ≤ x ≤ 2R, by the orbifolding of R 2p. Here we assume that A (x) satisfies where is a transition function (or gauge transformation) on the torus. Thus the A is a gauge field on R 2p which is extended from the gauge field on the torus, i.e. a pull back connection of the map from R 2p to T 2p = R 2p /Z 2p. The constraint for the tachyon T by the orbifolding may be same as the constraint for transverse coordinates. Thus we require that where we take same in (2.1) for the D0-branes and the anti-D0-branes. Then the configuration (3.1) is consistent with the constraint (3.4) of the orbifolding if we take This is obvious if we notice that the D0−D0-branes given by the configuration (3.1) uniformly distributed in R 2p and the unit shift (3.5) is a symmetry. Note that which is from the fundamental property of the transition functions. Therefore, the configuration (3.1) with the orbifolding operator (3.5) is a consistent configuration of the infinitely many D0−D0-brane pairs on a torus T 2p which is equivalent to M D(2p)-branes with the gauge field A (x). Since the orbifolding will consistently truncate the equations of motion or the (on-shell) boundary state, (3.1) with the orbifolding by the generator (3.5) will be an exact solution on the torus if we set A = 0 or, for example, an anti self-dual configuration for p = 2. * * Nahm Transformation and Tachyon condensation on D0−D0 pairs If we consider M D(2p)-branes with a nontrivial gauge bundle on the torus, it is the bound state of M D(2p)-branes and the lower dimensional D-branes, for example D0-branes. In this case, following (see also ) we can find a configuration of D0-branes which is equivalent to the bound state. We will apply this to the solution on the torus and see that the Nahm transformation naturally appears. In, we first take a configuration of D0−D0 pairs which represents the M D(2p)-branes by the tachyon condensation. Then the tachyon is diagonalized by the gauge transformation and then only D0-branes which corresponds to zero modes remain after the tachyon condensation, namely the u → ∞ limit. Then we see that the remaining D0-branes have the transverse scalars or the matrix coordinateX is given by just a truncation of the Chan-Patton-Hilbert space to those composed by the the zero modes only: where | i is a zero mode of the tachyon. This gives the D0-brane picture of the boundary state. For the M D(2p)-branes with a nontrivial gauge bundle on the torus, the tachyon, acts on (x) which is a spinor on R 2p. Now we decompose a spinor on R 2p into a spinor on torus and a plain wave like the Bloch wave function: which means that (x) is a section of the spinor bundle on T 2p and 0 ≤ < 2L. Indeed, is the eigen state of the unitary operator U : Thus any spinor (x) on R 2p can be written as (3.12) because any eigen state of U can be written as (3.9). Using this, we have (3.14) Then, the zero modes of the tachyon, D / (x) = 0, is given by (i = 1,, m) and m is the number of the zero modes of D /. From the index theorem, we know that m does not depend on. For p = 2, m is the instanton number. The zero modes are labeled by and i. We will see that the discrete eigen values of ∂ ∂ parameterize mirror images of D0-branes by the Z 2p orbifolding. We normalize the zero modes as 1 which is equivalent to where 0 ≤ x ≤ 2R. (Because of the Euclidean nature, is the SO(2p) invariant.) This can been seen from (3.19) Here we assume that m > 0 and the all zero modes have positive chirality, i.e. i (x) = i (x), which means that only the m D0-branes are remained and all anti-D0-branes disappear after the tachyon condensation. However, this assumptions is not essential, even for cases with zero modes of both chiralities, as discussed in. where x = x + 2R l and we have used. Now we can evaluate the coordinateX of m D0-branes corresponding to the remaining m zero modes: This means that Tr eF 2, (3.24) are followed from the index theorem. Therefore, we find an equivalence between the N D(2p)-branes on the T 2p with the gauge field A (x) and the m D(2p)-branes on the dual torusT 2p with the gauge field () given by (3.21) using the Dirac zero modes (3.16). The transition function for () is given by and which satisfies D / () j (x) = 0, thus a linear combinations of i (x). If we take p = 2 and A (x) is anti-self dual, the formula (3.21) is indeed the Nahm transformation of, which is a generalization of the formula given in for the ADHM case. We note that the Nahm transformation can be viewed as a combination of the two different equivalences: the T-dual and the equivalence between the N D4-brane with A and the m D0-branes withX. T-dual of the D0−D0-brane pairs Let us take the T-dual of the D(2p)-brane solution on the torus, (3.1). Now we assume that the bundle on the D(2p)-brane is trivial and A (x) = /(2 ), where is a constant. In this case, U is just a translation operator. As we have seen, the Hilbert space of the Chan-Paton index is spanned by the spinors on the R 2p and any spinor (x) on R 2p can be written as which is just a Fourier transformation with the momentum R nx (, n) which is periodic, namely, U (x) = (x) and (, n) is a constant spinor. Then, is a basis of the Hilbert space labeled by {, n} and the spinor index of a constant spinor. We note that,n (x) is an eigen state of U, and also an eigen state of the tachyon T = lim u→∞ u D /, In this basis, X =x is represented as 2 i ∂ ∂. This means that the gauge fields of the D(2p)-branes and anti-D(2p)-branes in the T-dual picture vanish. Now we expect that the T-dual of the tachyon will be given by the tachyon in the above basis of the Chan-Paton bundle since we regard the torus as the orbifold of R 2p. Therefore, in the T-dual picture, this system is equivalent to infinitely many pairs of D(2p)-brane and anti-D(2p)-brane, labeled by {n } ∈ Z 2p, on the dual torus T 2p. The tachyon condensation is given b T () = ( − + 2L n ), (3.32) which is diagonal in n and = 0. Here we defined = u 2. We interpreted that the { } parameterize the world volume of the pairs of D2−D2-branes, on the other hand, {n } are the Chan-Paton indices. is the location of the a solitonic D0-branes on the dual torusT 2p. Since,n =,n, where = + 2 L and n = n +, the transition function of the infinitely many pairs of D(2p)-branes and anti-D(2p)-branes in this T-dual picture, is given by where U n→n+, is the unitary operator which maps,n to,n. Thus the tachyon (3.32) is a consistent configuration on the dual torus although it is not periodic. We note that the configuration (3.8) of the D0−D0 pairs is more convenient than its T-dual configuration (3.32) of D(2p)-anti-D(2p) pairs, especially, for a configuration with a non-trivial A (x). For a non-trivial A (x), from a spinor,n (x) stisfying U,n (x) =,n (x), D /,n (x) = E,n,n (x), (3.34) a basis is given by,n (x) = e i 1 2 x,n (x), (3.35) where,n (x) is an eigen state of U and D /. Then, the tachyon configuration of D(2p)-anti-D(2p) pairs onT 2p is implicitly given b T () = u E,n (3.36) in this basis. Let us take the large radius limit of the torus or the T-dual torus. If we take the L → ∞, then only the pair of D(2p)-brane and anti-D(2p)-brane with n = 0 will remain and the configuration (3.32) becomes which is just the Atiyah-Bott-Shapiro solution for the decent relation. On the other hand, if we take the R → ∞, the original infinitely many D0−D0-brane pairs on T r become those on R r and the solution (3.1) is same as the solution for the ascent relation found in. Thus we can say that on the torus the two solutionsfor the decent relation (3.37) and the ascent relation (3.1) are T-dual each other. We thank Koji Hashimoto for suggesting this solution. Finally, we will comment on the classification of the D-branes by the K-theory. The configuration (3.37) for the decent relation is related to the K-theory (using the infinitely many D9−D9 pairs ). On the other hand, (3.1) represnts the (analytic) K-homology class in. Therefore, we expext that the T-dual maps the K-theory to the analytic K-homology. However, the winding modes are neglected to obtain the analytic K-homology by assuming the size of the compactified manifold is very large in although the winding modes are important for the T-dual picture. The duality of the KK-theory discussed in will be important to study the role of the widing modes. It would be interesting to investigate the relation to it further. Concluding remarks In this paper, we found an exact solution, with a nonzero net D-brane charge, of the tachyon condesation in the boundary string field theory of brane-anti-brane pairs on torus. The Nahm-transformation of the instantons was derived from this tachyon condensation. We also found the T-dual configutration of this. There are several interesting future directions. Since our method is not restricted to the instanton (i.e. p = 2) case, it will be interesting to study the Nahm transformation for D0-D8 or D0-D6 cases. Morevoer, the BPS properties are not (explicitly) assumed in this paper. Therefore, the non-BPS cases, for exampole models dicussed in, are also covered in thie paper. To extend our result to other orbifolds, like ALE spaces, are also interesting. In this paper, we do not explicitly use the boundary state formalism though we believe the exact solutions in the boundary string field theory can be mapped to the boudnary state. (The marginal deformation case was studied in.) It would be desired to do it explicitly. |
Digital Planning of Harmonised Quality Testing Activities throughout the Product Life Cycle Contemporary companies tend to avoid quality testing activities as they are regarded as non-value-adding efforts. Nevertheless, certain quality tests are mandatory to ensure the product quality to the customer. In order to reduce financial efforts and avoid testing overhead, quality testing activities need to be planned and harmonised throughout the entire product life cycle. The following paper focuses the development of a digital configuration system for quality testing activities throughout the product life cycle. To identify all important inspection processes, an overview of life cycle-orientated quality testing activities is presented. Thereafter, a development concept for the digital configuration system is introduced. The scope of the paper includes the digitalised process of planning quality testing activities in context of product life cycle management applied within developing and producing companies running volume production. Introduction Contemporary companies often classify quality testing activities as non-value-adding processes. Therefore, activities related to quality inspection are frequently brought into focus of optimisation projects with the result of occasionally being eliminated from the process concept. This implies that the process itself needs to be designed in a way that quality requirements can be met which is often unreasonably expensive. In addition, a certain amount of quality testing activities is necessary to determine whether the inspected product, process or service complies with its specific requirements. First, these inspections assure product quality to external customers. Second, companies are able to derive measures for continuous improvement by using the knowledge about failures and process capability which is acquired by quality inspections. Third, especially supplier companies have the obligation to prove their quality assurance activities using certain pre-defined documents. Hence, quality testing activities are necessary support performances for value-adding processes and need to be planned thoroughly. Due to the fact that quality testing processes are non-valueadding activities, companies are panting for aligning and optimising their inspection activities throughout the entire product life cycle. When drawing an extensive balance sheet for quality testing activities, time and financial efforts spent on inspection activities should be minimized throughout the entire product life cycle. A suitable concept for summarising expenses on quality inspection is the idea of stating out a "quality testing footprint", which is used in latest research activities (see ). Quality testing activities take place in different stages of the product life cycle. The most popular testing activities are common inspection routines during the stage of production, such as dimensional checks or functional tests. However, quality management has extended its activity focus during the last century from the production stage to all phases of the product life cycle. Hence, activities related to quality testing also take place in both earlier and later stages of the entire product life cycle. Exemplary inspection processes are design reviews in the stage of product development or reliability tests during product use. Considering quality testing activities throughout the product life cycle, a huge variety of dependencies between particular inspection processes can be identified. For example, functional tests performed in the stage of production can be aligned with the results of a design review which is conducted during product development. In order to align quality testing activities and therefore optimise the quality testing footprint, interdependencies between quality inspections need to be identified and analysed. At first, a common understanding of quality inspections as well as a review of common inspection activities is mandatory. Hence, the present paper provides an overview on quality testing and inspection activities throughout the product life cycle. Based on the identification of relevant testing processes at all stages of the product life cycle, interdependences between inspection activities as well as influencing boundary conditions can be analysed. On the basis of a deeper understanding of the interconnections, it is possible to align quality testing activities at all stages of the product life cycle. For this purpose, a development concept for a digital configuration system of life cycle-orientated inspection planning is introduced. The development approach towards the digital configuration system is presented as well as the field of application in context of product life cycle management and digital process planning. Product Life Cycle Management Aligning quality testing activities throughout the product life cycle requires a common understanding of both quality testing activities and the product life cycle term. The present paper refers to the definition of product life cycle management named by Eigner and Stelzer. They consider the product life cycle concept as one of contemporary companies' core processes, covering all activities related to planning and designing products, resources and processes as well as activities within product use and recycling. In order to structure the entire process, different stages within the product life cycle can be identified. These stages as well as exemplary corresponding tasks are illustrated in figure 1. The illustrated understanding of product life cycle management is commonly spread. Similar product life cycle concepts can also be found within. As product life cycle management includes all activities regarding product and process planning, it also comprehends the task of planning and harmonising quality inspections. This especially applies when considering quality testing activities throughout the entire product life cycle (also see chapter 3.3). Furthermore, the stage concept, illustrated in figure 1, facilitates a classification of quality testing activities into different phases of the product life cycle. Inspection Planning The planning and development of quality testing activities is performed within the process of inspection planning. Examining contemporary literature, significant differences in the definition of the term "inspection planning" can be identified. According to the guideline VDI/VDE/DGQ 2619, inspection planning deals with the process of planning quality testing activities which are conducted during the stage of production. Hence, the scope of inspection planning can be seen as defining quality testing activities related to the stages of manufacturing and assembly. Consequently, the process of inspection planning mainly takes place during production planning since manufacturing processes as well as necessary resources are planned during this phase. Nevertheless, various quality testing activities executed at production stage are identified and determined in earlier stages of the product life cycle, as shown in. The definition of inspection planning introduced above is a conventional definition stated by various authors, such as. Adjacent to this interpretation, a more comprehensive definition can be found in contemporary references. According to these, the process of inspection planning does not only comprise quality testing activities conducted during the stage of production but also the process of planning inspection activities taking place during further stages of the product life cycle. These are inspection activities from the perspective of quality assurance addressing process results from early stages of the product life cycle, such as verifying design quality during product development. For example, quality inspections such as FMEA execution or design reviews investigating the results of a development process also need to be planned. Hence, the comprehensive process of inspection planning plays an important role in the context of product life cycle management. The present paper adapts this comprehensive definition of inspection planning. |
Genetic reduction of Nrf2 exacerbates cognitive deficits in a mouse model of Alzheimers disease Aging is the major risk factor for several neurodegenerative diseases, including Alzheimer's disease (AD). However, the mechanisms by which aging contributes to neurodegeneration remain elusive. The nuclear factor (erythroid-derived 2)-like 2 (Nrf2) is a transcription factor that regulates expression of a vast number of genes by binding to the antioxidant response element. Nrf2 levels decrease as a function of age, and reduced Nrf2 levels have been reported in postmortem human brains and animal models of AD. Nevertheless, it is still unknown whether Nrf2 plays a role in the cognitive deficits associated with AD. To address this question, we used a genetic approach to remove the Nrf2 gene from APP/PS1 mice, a widely used animal model of AD. We found that the lack of Nrf2 significantly exacerbates cognitive deficits in APP/PS1, without altering gross motor function. Specifically, we found an exacerbation of deficits in spatial learning and memory, as well as in working and associative memory. Different brain regions control these behavioral tests, indicating that the lack of Nrf2 has a global effect on brain function. The changes in cognition were linked to an increase in A and interferon-gamma (IFN) levels, and microgliosis. The changes in IFN levels are noteworthy as previously published evidence indicates that IFN can increase microglia activation and induce A production. Our data suggest a clear link between Nrf2 and AD-mediated cognitive decline and further strengthen the connection between Nrf2 and AD. |
package modbus
import (
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"time"
"strings"
"sync"
)
type RegType uint
type Endianness uint
type WordOrder uint
const (
PARITY_NONE uint = 0
PARITY_EVEN uint = 1
PARITY_ODD uint = 2
HOLDING_REGISTER RegType = 0
INPUT_REGISTER RegType = 1
// endianness of 16-bit registers
BIG_ENDIAN Endianness = 1
LITTLE_ENDIAN Endianness = 2
// word order of 32-bit registers
HIGH_WORD_FIRST WordOrder = 1
LOW_WORD_FIRST WordOrder = 2
)
// Modbus client configuration object.
type ClientConfiguration struct {
// URL sets the client mode and target location in the form
// <mode>://<serial device or host:port> e.g. tcp://plc:502
URL string
// Speed sets the serial link speed (in bps, rtu only)
Speed uint
// DataBits sets the number of bits per serial character (rtu only)
DataBits uint
// Parity sets the serial link parity mode (rtu only)
Parity uint
// StopBits sets the number of serial stop bits (rtu only)
StopBits uint
// Timeout sets the request timeout value
Timeout time.Duration
// TLSClientCert sets the client-side TLS key pair (tcp+tls only)
TLSClientCert *tls.Certificate
// TLSRootCAs sets the list of CA certificates used to authenticate
// the server (tcp+tls only). Leaf (i.e. server) certificates can also
// be used in case of self-signed certs, or if cert pinning is required.
TLSRootCAs *x509.CertPool
}
// Modbus client object.
type ModbusClient struct {
conf ClientConfiguration
logger *logger
lock sync.Mutex
endianness Endianness
wordOrder WordOrder
transport transport
unitId uint8
transportType transportType
}
// NewClient creates, configures and returns a modbus client object.
func NewClient(conf *ClientConfiguration) (mc *ModbusClient, err error) {
var clientType string
var splitURL []string
mc = &ModbusClient{
conf: *conf,
}
splitURL = strings.SplitN(mc.conf.URL, "://", 2)
if len(splitURL) == 2 {
clientType = splitURL[0]
mc.conf.URL = splitURL[1]
}
mc.logger = newLogger(fmt.Sprintf("modbus-client(%s)", mc.conf.URL))
switch clientType {
case "rtu":
// set useful defaults
if mc.conf.Speed == 0 {
mc.conf.Speed = 9600
}
// note: the "modbus over serial line v1.02" document specifies an
// 11-bit character frame, with even parity and 1 stop bit as default,
// and mandates the use of 2 stop bits when no parity is used.
// This stack defaults to 8/N/2 as most devices seem to use no parity,
// but giving 8/N/1, 8/E/1 and 8/O/1 a shot may help with serial
// issues.
if mc.conf.DataBits == 0 {
mc.conf.DataBits = 8
}
if mc.conf.StopBits == 0 {
if mc.conf.Parity == PARITY_NONE {
mc.conf.StopBits = 2
} else {
mc.conf.StopBits = 1
}
}
if mc.conf.Timeout == 0 {
mc.conf.Timeout = 300 * time.Millisecond
}
mc.transportType = modbusRTU
case "rtuovertcp":
if mc.conf.Timeout == 0 {
mc.conf.Timeout = 1 * time.Second
}
mc.transportType = modbusRTUOverTCP
case "tcp":
if mc.conf.Timeout == 0 {
mc.conf.Timeout = 1 * time.Second
}
mc.transportType = modbusTCP
case "tcp+tls":
if mc.conf.Timeout == 0 {
mc.conf.Timeout = 1 * time.Second
}
// expect a client-side certificate for mutual auth as the
// modbus/mpab protocol has no inherent auth facility.
// (see requirements R-08 and R-19 of the MBAPS spec)
if mc.conf.TLSClientCert == nil {
mc.logger.Errorf("missing client certificate")
err = ErrConfigurationError
return
}
// expect a CertPool object containing at least 1 CA or
// leaf certificate to validate the server-side cert
if mc.conf.TLSRootCAs == nil {
mc.logger.Errorf("missing CA/server certificate")
err = ErrConfigurationError
return
}
mc.transportType = modbusTCPOverTLS
default:
if len(splitURL) != 2 {
mc.logger.Errorf("missing client type in URL '%s'", mc.conf.URL)
} else {
mc.logger.Errorf("unsupported client type '%s'", clientType)
}
err = ErrConfigurationError
return
}
mc.unitId = 1
mc.endianness = BIG_ENDIAN
mc.wordOrder = HIGH_WORD_FIRST
return
}
// Opens the underlying transport (tcp socket or serial line).
func (mc *ModbusClient) Open() (err error) {
var spw *serialPortWrapper
var sock net.Conn
mc.lock.Lock()
defer mc.lock.Unlock()
switch mc.transportType {
case modbusRTU:
// create a serial port wrapper object
spw = newSerialPortWrapper(&serialPortConfig{
Device: mc.conf.URL,
Speed: mc.conf.Speed,
DataBits: mc.conf.DataBits,
Parity: mc.conf.Parity,
StopBits: mc.conf.StopBits,
})
// open the serial device
err = spw.Open()
if err != nil {
return
}
// discard potentially stale serial data
discard(spw)
// create the RTU transport
mc.transport = newRTUTransport(
spw, mc.conf.URL, mc.conf.Speed, mc.conf.Timeout)
case modbusRTUOverTCP:
// connect to the remote host
sock, err = net.DialTimeout("tcp", mc.conf.URL, 5 * time.Second)
if err != nil {
return
}
// discard potentially stale serial data
discard(sock)
// create the RTU transport
mc.transport = newRTUTransport(
sock, mc.conf.URL, mc.conf.Speed, mc.conf.Timeout)
case modbusTCP:
// connect to the remote host
sock, err = net.DialTimeout("tcp", mc.conf.URL, 5 * time.Second)
if err != nil {
return
}
// create the TCP transport
mc.transport = newTCPTransport(sock, mc.conf.Timeout)
case modbusTCPOverTLS:
// connect to the remote host with TLS
sock, err = tls.DialWithDialer(
&net.Dialer{
Deadline: time.Now().Add(15 * time.Second),
}, "tcp", mc.conf.URL,
&tls.Config{
Certificates: []tls.Certificate{
*mc.conf.TLSClientCert,
},
RootCAs: mc.conf.TLSRootCAs,
// mandate TLS 1.2 or higher (see R-01 of the MBAPS spec)
MinVersion: tls.VersionTLS12,
})
if err != nil {
return
}
// force the TLS handshake
err = sock.(*tls.Conn).Handshake()
if err != nil {
sock.Close()
return
}
// create the TCP transport
mc.transport = newTCPTransport(sock, mc.conf.Timeout)
default:
// should never happen
err = ErrConfigurationError
}
return
}
// Closes the underlying transport.
func (mc *ModbusClient) Close() (err error) {
mc.lock.Lock()
defer mc.lock.Unlock()
err = mc.transport.Close()
return
}
// Sets the unit id of subsequent requests.
func (mc *ModbusClient) SetUnitId(id uint8) (err error) {
mc.lock.Lock()
defer mc.lock.Unlock()
mc.unitId = id
return
}
// Sets the encoding (endianness and word ordering) of subsequent requests.
func (mc *ModbusClient) SetEncoding(endianness Endianness, wordOrder WordOrder) (err error) {
mc.lock.Lock()
defer mc.lock.Unlock()
if endianness != BIG_ENDIAN && endianness != LITTLE_ENDIAN {
mc.logger.Errorf("unknown endianness value %v", endianness)
err = ErrUnexpectedParameters
return
}
if wordOrder != HIGH_WORD_FIRST && wordOrder != LOW_WORD_FIRST {
mc.logger.Errorf("unknown word order value %v", wordOrder)
err = ErrUnexpectedParameters
return
}
mc.endianness = endianness
mc.wordOrder = wordOrder
return
}
// Reads multiple coils (function code 01).
func (mc *ModbusClient) ReadCoils(addr uint16, quantity uint16) (values []bool, err error) {
values, err = mc.readBools(addr, quantity, false)
return
}
// Reads a single coil (function code 01).
func (mc *ModbusClient) ReadCoil(addr uint16) (value bool, err error) {
var values []bool
values, err = mc.readBools(addr, 1, false)
if err == nil {
value = values[0]
}
return
}
// Reads multiple discrete inputs (function code 02).
func (mc *ModbusClient) ReadDiscreteInputs(addr uint16, quantity uint16) (values []bool, err error) {
values, err = mc.readBools(addr, quantity, true)
return
}
// Reads a single discrete input (function code 02).
func (mc *ModbusClient) ReadDiscreteInput(addr uint16) (value bool, err error) {
var values []bool
values, err = mc.readBools(addr, 1, true)
if err == nil {
value = values[0]
}
return
}
// Reads multiple 16-bit registers (function code 03 or 04).
func (mc *ModbusClient) ReadRegisters(addr uint16, quantity uint16, regType RegType) (values []uint16, err error) {
var mbPayload []byte
// read 1 uint16 register, as bytes
mbPayload, err = mc.readRegisters(addr, quantity, regType)
if err != nil {
return
}
// decode payload bytes as uint16s
values = bytesToUint16s(mc.endianness, mbPayload)
return
}
// Reads a single 16-bit register (function code 03 or 04).
func (mc *ModbusClient) ReadRegister(addr uint16, regType RegType) (value uint16, err error) {
var values []uint16
values, err = mc.ReadRegisters(addr, 1, regType)
if err == nil {
value = values[0]
}
return
}
// Reads multiple 32-bit registers.
func (mc *ModbusClient) ReadUint32s(addr uint16, quantity uint16, regType RegType) (values []uint32, err error) {
var mbPayload []byte
// read 2 * quantity uint16 registers, as bytes
mbPayload, err = mc.readRegisters(addr, quantity * 2, regType)
if err != nil {
return
}
// decode payload bytes as uint32s
values = bytesToUint32s(mc.endianness, mc.wordOrder, mbPayload)
return
}
// Reads a single 32-bit register.
func (mc *ModbusClient) ReadUint32(addr uint16, regType RegType) (value uint32, err error) {
var values []uint32
values, err = mc.ReadUint32s(addr, 1, regType)
if err == nil {
value = values[0]
}
return
}
// Reads multiple 32-bit float registers.
func (mc *ModbusClient) ReadFloat32s(addr uint16, quantity uint16, regType RegType) (values []float32, err error) {
var mbPayload []byte
// read 2 * quantity uint16 registers, as bytes
mbPayload, err = mc.readRegisters(addr, quantity * 2, regType)
if err != nil {
return
}
// decode payload bytes as float32s
values = bytesToFloat32s(mc.endianness, mc.wordOrder, mbPayload)
return
}
// Reads a single 32-bit float register.
func (mc *ModbusClient) ReadFloat32(addr uint16, regType RegType) (value float32, err error) {
var values []float32
values, err = mc.ReadFloat32s(addr, 1, regType)
if err == nil {
value = values[0]
}
return
}
// Reads multiple 64-bit registers.
func (mc *ModbusClient) ReadUint64s(addr uint16, quantity uint16, regType RegType) (values []uint64, err error) {
var mbPayload []byte
// read 4 * quantity uint16 registers, as bytes
mbPayload, err = mc.readRegisters(addr, quantity * 4, regType)
if err != nil {
return
}
// decode payload bytes as uint64s
values = bytesToUint64s(mc.endianness, mc.wordOrder, mbPayload)
return
}
// Reads a single 64-bit register.
func (mc *ModbusClient) ReadUint64(addr uint16, regType RegType) (value uint64, err error) {
var values []uint64
values, err = mc.ReadUint64s(addr, 1, regType)
if err == nil {
value = values[0]
}
return
}
// Reads multiple 64-bit float registers.
func (mc *ModbusClient) ReadFloat64s(addr uint16, quantity uint16, regType RegType) (values []float64, err error) {
var mbPayload []byte
// read 4 * quantity uint16 registers, as bytes
mbPayload, err = mc.readRegisters(addr, quantity * 4, regType)
if err != nil {
return
}
// decode payload bytes as float64s
values = bytesToFloat64s(mc.endianness, mc.wordOrder, mbPayload)
return
}
// Reads a single 64-bit float register.
func (mc *ModbusClient) ReadFloat64(addr uint16, regType RegType) (value float64, err error) {
var values []float64
values, err = mc.ReadFloat64s(addr, 1, regType)
if err == nil {
value = values[0]
}
return
}
// Writes a single coil (function code 05)
func (mc *ModbusClient) WriteCoil(addr uint16, value bool) (err error) {
var req *pdu
var res *pdu
mc.lock.Lock()
defer mc.lock.Unlock()
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
functionCode: fcWriteSingleCoil,
}
// coil address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// coil value
if value {
req.payload = append(req.payload, 0xff, 0x00)
} else {
req.payload = append(req.payload, 0x00, 0x00)
}
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// expect 4 bytes (2 byte of address + 2 bytes of value)
if len(res.payload) != 4 ||
// bytes 1-2 should be the coil address
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
// bytes 3-4 should either be {0xff, 0x00} or {0x00, 0x00}
// depending on the coil value
(value == true && res.payload[2] != 0xff) ||
res.payload[3] != 0x00 {
err = ErrProtocolError
return
}
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
// Writes multiple coils (function code 15)
func (mc *ModbusClient) WriteCoils(addr uint16, values []bool) (err error) {
var req *pdu
var res *pdu
var quantity uint16
var encodedValues []byte
mc.lock.Lock()
defer mc.lock.Unlock()
quantity = uint16(len(values))
if quantity == 0 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of coils is 0")
return
}
if quantity > 0x7b0 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of coils exceeds 1968")
return
}
if uint32(addr) + uint32(quantity) - 1 > 0xffff {
err = ErrUnexpectedParameters
mc.logger.Error("end coil address is past 0xffff")
return
}
encodedValues = encodeBools(values)
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
functionCode: fcWriteMultipleCoils,
}
// start address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// quantity
req.payload = append(req.payload, uint16ToBytes(BIG_ENDIAN, quantity)...)
// byte count
req.payload = append(req.payload, byte(len(encodedValues)))
// payload
req.payload = append(req.payload, encodedValues...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// expect 4 bytes (2 byte of address + 2 bytes of quantity)
if len(res.payload) != 4 ||
// bytes 1-2 should be the base coil address
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
// bytes 3-4 should be the quantity of coils
bytesToUint16(BIG_ENDIAN, res.payload[2:4]) != quantity {
err = ErrProtocolError
return
}
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
// Writes a single 16-bit register (function code 06).
func (mc *ModbusClient) WriteRegister(addr uint16, value uint16) (err error) {
var req *pdu
var res *pdu
mc.lock.Lock()
defer mc.lock.Unlock()
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
functionCode: fcWriteSingleRegister,
}
// register address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// register value
req.payload = append(req.payload, uint16ToBytes(mc.endianness, value)...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// expect 4 bytes (2 byte of address + 2 bytes of value)
if len(res.payload) != 4 ||
// bytes 1-2 should be the register address
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
// bytes 3-4 should be the value
bytesToUint16(mc.endianness, res.payload[2:4]) != value {
err = ErrProtocolError
return
}
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
// Writes multiple 16-bit registers (function code 16).
func (mc *ModbusClient) WriteRegisters(addr uint16, values []uint16) (err error) {
var payload []byte
// turn registers to bytes
for _, value := range values {
payload = append(payload, uint16ToBytes(mc.endianness, value)...)
}
err = mc.writeRegisters(addr, payload)
return
}
// Writes multiple 32-bit registers.
func (mc *ModbusClient) WriteUint32s(addr uint16, values []uint32) (err error) {
var payload []byte
// turn registers to bytes
for _, value := range values {
payload = append(payload, uint32ToBytes(mc.endianness, mc.wordOrder, value)...)
}
err = mc.writeRegisters(addr, payload)
return
}
// Writes a single 32-bit register.
func (mc *ModbusClient) WriteUint32(addr uint16, value uint32) (err error) {
err = mc.writeRegisters(addr, uint32ToBytes(mc.endianness, mc.wordOrder, value))
return
}
// Writes multiple 32-bit float registers.
func (mc *ModbusClient) WriteFloat32s(addr uint16, values []float32) (err error) {
var payload []byte
// turn registers to bytes
for _, value := range values {
payload = append(payload, float32ToBytes(mc.endianness, mc.wordOrder, value)...)
}
err = mc.writeRegisters(addr, payload)
return
}
// Writes a single 32-bit float register.
func (mc *ModbusClient) WriteFloat32(addr uint16, value float32) (err error) {
err = mc.writeRegisters(addr, float32ToBytes(mc.endianness, mc.wordOrder, value))
return
}
// Writes multiple 64-bit registers.
func (mc *ModbusClient) WriteUint64s(addr uint16, values []uint64) (err error) {
var payload []byte
// turn registers to bytes
for _, value := range values {
payload = append(payload, uint64ToBytes(mc.endianness, mc.wordOrder, value)...)
}
err = mc.writeRegisters(addr, payload)
return
}
// Writes a single 64-bit register.
func (mc *ModbusClient) WriteUint64(addr uint16, value uint64) (err error) {
err = mc.writeRegisters(addr, uint64ToBytes(mc.endianness, mc.wordOrder, value))
return
}
// Writes multiple 64-bit float registers.
func (mc *ModbusClient) WriteFloat64s(addr uint16, values []float64) (err error) {
var payload []byte
// turn registers to bytes
for _, value := range values {
payload = append(payload, float64ToBytes(mc.endianness, mc.wordOrder, value)...)
}
err = mc.writeRegisters(addr, payload)
return
}
// Writes a single 64-bit float register.
func (mc *ModbusClient) WriteFloat64(addr uint16, value float64) (err error) {
err = mc.writeRegisters(addr, float64ToBytes(mc.endianness, mc.wordOrder, value))
return
}
/*** unexported methods ***/
// Reads and returns quantity booleans.
// Digital inputs are read if di is true, otherwise coils are read.
func (mc *ModbusClient) readBools(addr uint16, quantity uint16, di bool) (values []bool, err error) {
var req *pdu
var res *pdu
var expectedLen int
mc.lock.Lock()
defer mc.lock.Unlock()
if quantity == 0 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of coils/discrete inputs is 0")
return
}
if quantity > 2000 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of coils/discrete inputs exceeds 2000")
return
}
if uint32(addr) + uint32(quantity) - 1 > 0xffff {
err = ErrUnexpectedParameters
mc.logger.Error("end coil/discrete input address is past 0xffff")
return
}
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
}
if di {
req.functionCode = fcReadDiscreteInputs
} else {
req.functionCode = fcReadCoils
}
// start address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// quantity
req.payload = append(req.payload, uint16ToBytes(BIG_ENDIAN, quantity)...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// expect a payload of 1 byte (byte count) + 1 byte for 8 coils/discrete inputs)
expectedLen = 1
expectedLen += int(quantity) / 8
if quantity % 8 != 0 {
expectedLen++
}
if len(res.payload) != expectedLen {
err = ErrProtocolError
return
}
// validate the byte count field
if int(res.payload[0]) + 1 != expectedLen {
err = ErrProtocolError
return
}
// turn bits into a bool slice
values = decodeBools(quantity, res.payload[1:])
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
// Reads and returns quantity registers of type regType, as bytes.
func (mc *ModbusClient) readRegisters(addr uint16, quantity uint16, regType RegType) (bytes []byte, err error) {
var req *pdu
var res *pdu
mc.lock.Lock()
defer mc.lock.Unlock()
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
}
switch regType {
case HOLDING_REGISTER: req.functionCode = fcReadHoldingRegisters
case INPUT_REGISTER: req.functionCode = fcReadInputRegisters
default:
err = ErrUnexpectedParameters
mc.logger.Errorf("unexpected register type (%v)", regType)
return
}
if quantity == 0 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of registers is 0")
}
if quantity > 123 {
err = ErrUnexpectedParameters
mc.logger.Error("quantity of registers exceeds 123")
}
if uint32(addr) + uint32(quantity) - 1 > 0xffff {
err = ErrUnexpectedParameters
mc.logger.Error("end register address is past 0xffff")
return
}
// start address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// quantity
req.payload = append(req.payload, uint16ToBytes(BIG_ENDIAN, quantity)...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// make sure the payload length is what we expect
// (1 byte of length + 2 bytes per register)
if len(res.payload) != 1 + 2 * int(quantity) {
err = ErrProtocolError
return
}
// validate the byte count field
// (2 bytes per register * number of registers)
if uint(res.payload[0]) != 2 * uint(quantity) {
err = ErrProtocolError
return
}
// remove the byte count field from the returned slice
bytes = res.payload[1:]
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
// Writes multiple registers starting from base address addr.
// Register values are passed as bytes, each value being exactly 2 bytes.
func (mc *ModbusClient) writeRegisters(addr uint16, values []byte) (err error) {
var req *pdu
var res *pdu
var payloadLength uint16
var quantity uint16
mc.lock.Lock()
defer mc.lock.Unlock()
payloadLength = uint16(len(values))
quantity = payloadLength / 2
if quantity == 0 {
err = ErrUnexpectedParameters
mc.logger.Errorf("quantity of registers is 0")
return
}
if quantity > 123 {
err = ErrUnexpectedParameters
mc.logger.Errorf("quantity of registers exceeds 123")
return
}
if uint32(addr) + uint32(quantity) - 1 > 0xffff {
err = ErrUnexpectedParameters
mc.logger.Errorf("end register address is past 0xffff")
return
}
// create and fill in the request object
req = &pdu{
unitId: mc.unitId,
functionCode: fcWriteMultipleRegisters,
}
// base address
req.payload = uint16ToBytes(BIG_ENDIAN, addr)
// quantity of registers (2 bytes per register)
req.payload = append(req.payload, uint16ToBytes(BIG_ENDIAN, quantity)...)
// byte count
req.payload = append(req.payload, byte(payloadLength))
// registers value
req.payload = append(req.payload, values...)
// run the request across the transport and wait for a response
res, err = mc.executeRequest(req)
if err != nil {
return
}
// validate the response code
switch {
case res.functionCode == req.functionCode:
// expect 4 bytes (2 byte of address + 2 bytes of quantity)
if len(res.payload) != 4 ||
// bytes 1-2 should be the base register address
bytesToUint16(BIG_ENDIAN, res.payload[0:2]) != addr ||
// bytes 3-4 should be the quantity of registers (2 bytes per register)
bytesToUint16(BIG_ENDIAN, res.payload[2:4]) != quantity {
err = ErrProtocolError
return
}
case res.functionCode == (req.functionCode | 0x80):
if len(res.payload) != 1 {
err = ErrProtocolError
return
}
err = mapExceptionCodeToError(res.payload[0])
default:
err = ErrProtocolError
mc.logger.Warningf("unexpected response code (%v)", res.functionCode)
}
return
}
func (mc *ModbusClient) executeRequest(req *pdu) (res *pdu, err error) {
// send the request over the wire, wait for and decode the response
res, err = mc.transport.ExecuteRequest(req)
if err != nil {
return
}
// make sure the source unit id matches that of the request
if (res.functionCode & 0x80) == 0x00 && res.unitId != req.unitId {
err = ErrBadUnitId
return
}
// accept errors from gateway devices (using special unit id #255)
if (res.functionCode & 0x80) == 0x80 &&
(res.unitId != req.unitId && res.unitId != 0xff) {
err = ErrBadUnitId
return
}
return
}
|
The persistent offenders debate: Using birth cohort conviction records, this study estimates that around 640,000 males and 54,000 females aged 46 years or under had been persistent offenders at some point in their lives. These figures represent 4.7 per cent and 0.4 per cent of the relevant male and female population respectively. Both male and female offenders who are first convicted at a young age are much more likely to become persistent offenders than their older counterparts. While young male offenders are at much greater risk of becoming persistent offenders than females, young female offenders are becoming increasingly more like males. It is vital that gender differences are not neglected. While the proportion of young offenders who become persistent is increasing, the proportions are fairly stable for offenders aged 20 and over. However, the numbers of both general and persistent young offenders show recent dramatic falls not evident among older offenders. For males aged 20 and over, the numbers are largely stable, while the numbers fall much less sharply for these older females. The present climate of focusing on younger offenders, especially persistent ones, may be having the desired effect of reduced numbers, but it is important that the ongoing situation with these older offenders is not overlooked. |
import React from 'react';
import Head from 'next/head';
import { AppProps } from 'next/app';
import {PATH_PREFIX} from "@/env";
export default function MyApp(props: AppProps) {
const { Component, pageProps } = props;
React.useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles && jssStyles.parentElement) {
jssStyles.parentElement.removeChild(jssStyles);
}
}, []);
return (
<React.Fragment>
<Head>
<title>jsffmpeg</title>
<meta name="keywords" content="jsffmpeg"/>
<meta name="description" content="jsffmpeg"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="renderer" content="webkit"/>
<link rel="manifest" href={`${PATH_PREFIX}/manifest.json`} />
<link rel="icon" type="image/x-icon" href={`${PATH_PREFIX}/favicon.ico`} />
<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no,minimal-ui"/>
</Head>
<Component {...pageProps} />
</React.Fragment>
);
}
|
<reponame>kevinboone/dbcmd
/*---------------------------------------------------------------------------
dbcmd
cmd_list.c
GPL v3.0
---------------------------------------------------------------------------*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fnmatch.h>
#include "cJSON.h"
#include "dropbox.h"
#include "token.h"
#include "commands.h"
#include "log.h"
#include "errmsg.h"
/*==========================================================================
make_display_time
*==========================================================================*/
static char *make_display_time (time_t t)
{
time_t now = time (NULL);
struct tm tm_now, tm_t;
localtime_r (&now, &tm_now);
localtime_r (&t, &tm_t);
char buff[50];
if (tm_now.tm_year != tm_t.tm_year)
strftime (buff, sizeof (buff) - 1, "%H:%M %b %d %Y", &tm_t);
else if (tm_now.tm_mday != tm_t.tm_mday || tm_now.tm_mon != tm_t.tm_mon)
strftime (buff, sizeof (buff) - 1, "%H:%M %b %d", &tm_t);
else
strftime (buff, sizeof (buff) - 1, "%H:%M today", &tm_t);
return strdup (buff);;
}
/*==========================================================================
make_display_name
*==========================================================================*/
static char *make_display_name (const DBStat *stat, BOOL recursive)
{
char *ret;
if (recursive)
{
if (stat->type == DBSTAT_FOLDER)
asprintf (&ret, "%s/", stat->path);
else
asprintf (&ret, "%s", stat->path);
}
else
{
if (stat->type == DBSTAT_FOLDER)
asprintf (&ret, "%s/", stat->name);
else
asprintf (&ret, "%s", stat->name);
}
return ret;
}
/*==========================================================================
display_list_long
*==========================================================================*/
static void display_list_long (List *list, BOOL recursive)
{
int i, l = list_length (list);
int name_max = 0;
int size_max = 0;
int time_max = 0;
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
char *name = make_display_name (stat, recursive);
char buff[20];
sprintf (buff, "%ld", stat->length);
int ll = strlen (name);
if (ll > name_max) name_max = ll;
ll = strlen (buff);
if (ll > size_max) size_max = ll;
if (stat->type == DBSTAT_FILE)
{
char *display_time = make_display_time (stat->server_modified);
ll = strlen (display_time);
if (ll > time_max) time_max = ll;
free (display_time);
}
free (name);
}
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
char *name = make_display_name (stat, recursive);
char buff[20];
int j;
if (stat->type == DBSTAT_FILE)
{
char *display_time = make_display_time (stat->server_modified);
printf ("file ");
sprintf (buff, "%ld", stat->length);
printf ("%s", buff);
for (j = strlen (buff); j <= size_max + 1; j++)
printf (" ");
printf ("%s", display_time);
for (j = strlen (display_time); j <= time_max + 1; j++)
printf (" ");
free (display_time);
}
else
{
printf ("fldr ");
for (j = 0; j <= size_max + 1; j++)
printf (" ");
for (j = 0; j <= time_max + 1; j++)
printf (" ");
}
printf ("%s\n", name);
free (name);
}
}
/*==========================================================================
pad
*==========================================================================*/
void pad (int n)
{
int j;
for (j = 0; j < n; j++)
fputs (" ", stdout);
}
/*==========================================================================
calc_line_len
Works out the maximum line length with a specified number of columns
*==========================================================================*/
int calc_line_len (List *list, int cols)
{
int i, l = list_length (list);
int *col_widths = malloc (cols * sizeof (int));
for (i = 0; i < cols; i++)
{
col_widths[i] = 0;
}
int col = 0;
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
char *name = make_display_name (stat, FALSE);
int namelen = strlen (name);
if (namelen > col_widths[col]) col_widths[col] = namelen;
free (name);
col++;
if (col == cols)
{
col = 0;
}
}
int line_length = 0;
for (i = 0; i < cols; i++)
{
line_length += col_widths[i] + 1;
}
free (col_widths);
return line_length;
}
/*==========================================================================
display_list_short
*==========================================================================*/
static void display_list_short (List *list, int screen_width)
{
int i, l = list_length (list);
BOOL stop = FALSE;
int cols = 1;
if (isatty (STDOUT_FILENO))
{
while (!stop /*&& cols < l*/)
{
cols++;
int line_length = calc_line_len (list, cols);
if (line_length >= screen_width - 1)
stop = TRUE;
if (cols >= screen_width / 2)
stop = TRUE;
}
cols--;
}
int *col_widths = malloc (cols * sizeof (int));
for (i = 0; i < cols; i++)
{
col_widths[i] = 0;
}
int col = 0;
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
char *name = make_display_name (stat, FALSE);
int namelen = strlen (name);
if (namelen > col_widths[col]) col_widths[col] = namelen;
free (name);
col++;
if (col == cols)
{
col = 0;
}
}
col = 0;
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
char *name = make_display_name (stat, FALSE);
int namelen = strlen (name);
fputs (name, stdout);
pad (col_widths[col] - namelen);
pad (1);
free (name);
col++;
if (col == cols)
{
puts ("");
col = 0;
}
}
free (col_widths);
puts ("");
}
/*==========================================================================
cmd_list
*==========================================================================*/
int cmd_list (const CmdContext *context, int argc, char **argv)
{
int ret = 0;
char *error = NULL;
char *path = NULL;
int screen_width = context->screen_width;
log_debug ("Starting list command");
BOOL recursive = context->recursive;
BOOL long_ = context->long_;
if (argc < 2)
path = strdup (""); // Root
else
{
const char *patharg = argv[1];
if (strcmp (patharg, "/") == 0)
path = strdup (""); // Not / for root on DB
else
path = strdup (patharg);
}
if (path[0] == 0 || path[0] == '/')
{
// Nothing other than / itself should end in a /
if (strlen (path) > 1)
{
if (path[strlen(path) - 1] == '/')
path[strlen(path) - 1] = 0;
}
char *token = token_init (&error);
if (token)
{
DBStat *stat = dropbox_stat_create();
dropbox_get_file_info (token, path, stat, &error);
if (error)
{
log_error ("%s: %s: %s",
argv[0], ERROR_CANTINFOSERVER, error);
free (error);
ret = EBADRQC;
}
else
{
char *spec = NULL;
char *dir = NULL;
switch (dropbox_stat_get_type (stat))
{
case DBSTAT_FOLDER:
spec = strdup ("*");
dir = strdup (path);
break;
default:
{
char *pathcopy = strdup (path);
char *p = strrchr (pathcopy, '/');
if (p == pathcopy) // e.g., /*.foo
{
dir = strdup (""); // DB root
spec = strdup (p+1);
}
else
{
*p = 0;
dir = strdup (pathcopy);
spec = strdup (p+1);
}
free (pathcopy);
}
break;
}
List *list = dropbox_stat_create_list();
dropbox_list_files (token, dir, list, TRUE, recursive, &error);
if (error)
{
log_error ("%s: %s: %s", argv[0], ERROR_CANTLISTSERVER, error);
free (error);
ret = -1;
}
else
{
List *globbed_list = dropbox_stat_create_list ();
int i, l = list_length (list);
for (i = 0; i < l; i++)
{
const DBStat *stat = list_get (list, i);
const char *path = dropbox_stat_get_path (stat);
char *pathcopy = strdup (path);
char *filename = basename (pathcopy);
// Not sure about this logic
if ((fnmatch (spec, path, 0) == 0)
|| (fnmatch (spec, filename, 0) == 0))
{
DBStat *statcopy = dropbox_stat_clone (stat);
list_append (globbed_list, statcopy);
}
free (pathcopy);
}
if (list_length (globbed_list) > 0)
{
if (long_ || recursive )
display_list_long (globbed_list, recursive);
else
display_list_short (globbed_list, screen_width);
}
else
{
// This is not an error message; well, not really
printf ("%s: %s: %s\n", NAME, argv[0], ERROR_NOMATCHING);
}
list_destroy (globbed_list);
}
list_destroy (list);
free (spec);
free (dir);
}
dropbox_stat_destroy (stat);
free (token);
}
else
{
log_error ("%s: %s: %s",
argv[0], ERROR_INITTOKEN, error);
free (error);
ret = EBADRQC;
}
}
else
{
log_error ("%s: %s",
argv[0], ERROR_STARTSLASH);
ret = EINVAL;
}
if (path) free (path);
return ret;
}
|
Q:
Why was this question closed as off-topic?
Why was this closed as off-topic?
https://ebooks.stackexchange.com/questions/210/are-there-any-ebook-formats-that-by-their-nature-are-immune-to-transmitting-a-vi
Seems to be perfectly on-topic.
A:
I talked with Shog, who deleted the question and he explained that he didn't think this was a very useful test case of the topicality of viruses in ebooks questions. It certainly didn't show much effort. Here is the text of the question for those who are interested:
There are many eBook formats. Are any of them incapable of transmitting a virus?
What problem is the question trying to solve? There were a few answers, but no way to know if any of them provided actionable advice. The question just wasn't concrete enough about criteria to know.
Nor was it a very useful question for figuring out what was on or off topic on the site. It was closed by 5 members of the community. Presumably the reason was as one of the commenters noted:
This question appears to be more fit for Security.SE.
However, as asked, it wouldn't really fly there either since it was rather nonspecific about the nature of the threat. A little-to-no effort question like this would probably be closed anywhere. It's not a good question to determine the scope of this (very new) site.
Perhaps more importantly, especially at this stage, is that the question seemed to be motivated more from idle curiosity rather than an actual need. Nobody (at least not today) is making their decisions about which format to publish or consume based on virus vulnerabilities. Issues like reader support and suitability to the content are vastly more important than the theoretical possibility that a bit of malicious code might be introduced somehow.
Stack Exchange sites work best when questions are surrounding some task that a person is doing. Answers should solve real problems and not hypothetical ones. |
<reponame>felipe-jm/gatsby-blog<gh_stars>1-10
import React from 'react';
import getThemeColor from '@/utils/getThemeColor';
import * as S from './styles';
const RecommendedPosts: React.FC<RecommendedPostsProps> = ({
previousPost,
nextPost,
}) => (
<S.RecommendedWrapper>
{previousPost ? (
<S.RecommendedLink
to={previousPost.fields.slug}
className="previous"
cover
direction="left"
bg={getThemeColor()}
duraction={0.6}
>
{previousPost.frontmatter.title}
</S.RecommendedLink>
) : (
<div />
)}
{nextPost && (
<S.RecommendedLink
to={nextPost.fields.slug}
className="next"
cover
direction="right"
bg={getThemeColor()}
duraction={0.6}
>
{nextPost.frontmatter.title}
</S.RecommendedLink>
)}
</S.RecommendedWrapper>
);
export default RecommendedPosts;
|
// Draw a torus (doughnut), using the current 1D texture for light shading
void DrawTorus(GLTMatrix mTransform)
{
GLfloat majorRadius = 0.35f;
GLfloat minorRadius = 0.15f;
GLint numMajor = 40;
GLint numMinor = 20;
GLTVector3 objectVertex;
GLTVector3 transformedVertex;
double majorStep = 2.0f*GLT_PI / numMajor;
double minorStep = 2.0f*GLT_PI / numMinor;
int i, j;
for (i=0; i<numMajor; ++i)
{
double a0 = i * majorStep;
double a1 = a0 + majorStep;
GLfloat x0 = (GLfloat) cos(a0);
GLfloat y0 = (GLfloat) sin(a0);
GLfloat x1 = (GLfloat) cos(a1);
GLfloat y1 = (GLfloat) sin(a1);
glBegin(GL_TRIANGLE_STRIP);
for (j=0; j<=numMinor; ++j)
{
double b = j * minorStep;
GLfloat c = (GLfloat) cos(b);
GLfloat r = minorRadius * c + majorRadius;
GLfloat z = minorRadius * (GLfloat) sin(b);
objectVertex[0] = x0*r;
objectVertex[1] = y0*r;
objectVertex[2] = z;
gltTransformPoint(objectVertex, mTransform, transformedVertex);
glVertex3fv(transformedVertex);
objectVertex[0] = x1*r;
objectVertex[1] = y1*r;
objectVertex[2] = z;
gltTransformPoint(objectVertex, mTransform, transformedVertex);
glVertex3fv(transformedVertex);
}
glEnd();
}
} |
Overproduction and nucleotide sequence of the respiratory D-lactate dehydrogenase of Escherichia coli Recombinant DNA plasmids containing the gene for the membrane-bound D-lactate dehydrogenase (D-LDH) of Escherichia coli linked to the promoter PL from lambda were constructed. After induction, the levels of D-LDH were elevated 300-fold over that of the wild type and amounted to 35% of the total cellular protein. The nucleotide sequence of the D-LDH gene was determined and shown to agree with the amino acid composition and the amino-terminal sequence of the purified enzyme. Removal of the amino-terminal formyl-Met from D-LDH was not inhibited in cells which contained these high levels of D-LDH. |
/*
* This file is generated by jOOQ.
*/
package com.tokenplay.ue4.model.db.tables.pojos;
import java.io.Serializable;
import java.time.OffsetDateTime;
import javax.annotation.Generated;
import javax.validation.constraints.NotNull;
/**
* This class is generated by jOOQ.
*/
@Generated(value = {
"http://www.jooq.org", "jOOQ version:3.10.6"}, comments = "This class is generated by jOOQ")
@SuppressWarnings({
"all", "unchecked", "rawtypes"})
public class Pilot implements Serializable {
private static final long serialVersionUID = -1165824115;
private String id;
private String callsign;
private Long usuId;
private String srvId;
private String token;
private OffsetDateTime lastPing;
private String lastIp;
private String lastVersion;
private OffsetDateTime lastLogin;
private Boolean disableChat;
private String rmbrToken;
private String uthId;
private Boolean disableRequests;
private String leaveReason;
private OffsetDateTime leaveDate;
private Boolean offLimits;
private String defaultScheme;
private Boolean useCustomScheme;
public Pilot() {
}
public Pilot(Pilot value) {
this.id = value.id;
this.callsign = value.callsign;
this.usuId = value.usuId;
this.srvId = value.srvId;
this.token = value.token;
this.lastPing = value.lastPing;
this.lastIp = value.lastIp;
this.lastVersion = value.lastVersion;
this.lastLogin = value.lastLogin;
this.disableChat = value.disableChat;
this.rmbrToken = value.rmbrToken;
this.uthId = value.uthId;
this.disableRequests = value.disableRequests;
this.leaveReason = value.leaveReason;
this.leaveDate = value.leaveDate;
this.offLimits = value.offLimits;
this.defaultScheme = value.defaultScheme;
this.useCustomScheme = value.useCustomScheme;
}
public Pilot(String id, String callsign, Long usuId, String srvId, String token, OffsetDateTime lastPing, String lastIp, String lastVersion,
OffsetDateTime lastLogin, Boolean disableChat, String rmbrToken, String uthId, Boolean disableRequests, String leaveReason,
OffsetDateTime leaveDate, Boolean offLimits, String defaultScheme, Boolean useCustomScheme) {
this.id = id;
this.callsign = callsign;
this.usuId = usuId;
this.srvId = srvId;
this.token = <PASSWORD>;
this.lastPing = lastPing;
this.lastIp = lastIp;
this.lastVersion = lastVersion;
this.lastLogin = lastLogin;
this.disableChat = disableChat;
this.rmbrToken = rmbrToken;
this.uthId = uthId;
this.disableRequests = disableRequests;
this.leaveReason = leaveReason;
this.leaveDate = leaveDate;
this.offLimits = offLimits;
this.defaultScheme = defaultScheme;
this.useCustomScheme = useCustomScheme;
}
@NotNull
public String getPilId() {
return this.id;
}
public void setPilId(String id) {
this.id = id;
}
@NotNull
public String getPilCallsign() {
return this.callsign;
}
public void setPilCallsign(String callsign) {
this.callsign = callsign;
}
@NotNull
public Long getPilUsuId() {
return this.usuId;
}
public void setPilUsuId(Long usuId) {
this.usuId = usuId;
}
public String getPilSrvId() {
return this.srvId;
}
public void setPilSrvId(String srvId) {
this.srvId = srvId;
}
public String getPilToken() {
return this.token;
}
public void setPilToken(String token) {
this.token = token;
}
public OffsetDateTime getPilLastPing() {
return this.lastPing;
}
public void setPilLastPing(OffsetDateTime lastPing) {
this.lastPing = lastPing;
}
public String getPilLastIp() {
return this.lastIp;
}
public void setPilLastIp(String lastIp) {
this.lastIp = lastIp;
}
public String getPilLastVersion() {
return this.lastVersion;
}
public void setPilLastVersion(String lastVersion) {
this.lastVersion = lastVersion;
}
public OffsetDateTime getPilLastLogin() {
return this.lastLogin;
}
public void setPilLastLogin(OffsetDateTime lastLogin) {
this.lastLogin = lastLogin;
}
public Boolean getPilDisableChat() {
return this.disableChat;
}
public void setPilDisableChat(Boolean disableChat) {
this.disableChat = disableChat;
}
public String getPilRmbrToken() {
return this.rmbrToken;
}
public void setPilRmbrToken(String rmbrToken) {
this.rmbrToken = rmbrToken;
}
public String getPilUthId() {
return this.uthId;
}
public void setPilUthId(String uthId) {
this.uthId = uthId;
}
public Boolean getPilDisableRequests() {
return this.disableRequests;
}
public void setPilDisableRequests(Boolean disableRequests) {
this.disableRequests = disableRequests;
}
public String getPilLeaveReason() {
return this.leaveReason;
}
public void setPilLeaveReason(String leaveReason) {
this.leaveReason = leaveReason;
}
public OffsetDateTime getPilLeaveDate() {
return this.leaveDate;
}
public void setPilLeaveDate(OffsetDateTime leaveDate) {
this.leaveDate = leaveDate;
}
public Boolean getPilOffLimits() {
return this.offLimits;
}
public void setPilOffLimits(Boolean offLimits) {
this.offLimits = offLimits;
}
public String getPilDefaultScheme() {
return this.defaultScheme;
}
public void setPilDefaultScheme(String defaultScheme) {
this.defaultScheme = defaultScheme;
}
public Boolean getPilUseCustomScheme() {
return this.useCustomScheme;
}
public void setPilUseCustomScheme(Boolean useCustomScheme) {
this.useCustomScheme = useCustomScheme;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Pilot (");
sb.append(id);
sb.append(", ").append(callsign);
sb.append(", ").append(usuId);
sb.append(", ").append(srvId);
sb.append(", ").append(token);
sb.append(", ").append(lastPing);
sb.append(", ").append(lastIp);
sb.append(", ").append(lastVersion);
sb.append(", ").append(lastLogin);
sb.append(", ").append(disableChat);
sb.append(", ").append(rmbrToken);
sb.append(", ").append(uthId);
sb.append(", ").append(disableRequests);
sb.append(", ").append(leaveReason);
sb.append(", ").append(leaveDate);
sb.append(", ").append(offLimits);
sb.append(", ").append(defaultScheme);
sb.append(", ").append(useCustomScheme);
sb.append(")");
return sb.toString();
}
}
|
<filename>src/script_opt/DefItem.cc
// See the file "COPYING" in the main distribution directory for copyright.
#include "DefItem.h"
#include "Expr.h"
namespace zeek::detail {
DefinitionItem::DefinitionItem(const ID* _id)
: name(_id->Name())
{
is_id = true;
id = _id;
di = nullptr;
field_name = nullptr;
t = id->GetType();
CheckForRecord();
}
DefinitionItem::DefinitionItem(const DefinitionItem* _di,
const char* _field_name, TypePtr _t)
{
is_id = false;
id = nullptr;
di = _di;
field_name = _field_name;
t = std::move(_t);
name += di->Name();
name += '$';
name += field_name;
CheckForRecord();
}
std::shared_ptr<DefinitionItem>
DefinitionItem::FindField(const char* field) const
{
if ( ! IsRecord() )
return nullptr;
auto offset = rt->FieldOffset(field);
return FindField(offset);
}
std::shared_ptr<DefinitionItem> DefinitionItem::FindField(int offset) const
{
if ( ! IsRecord() )
return nullptr;
return (*fields)[offset];
}
std::shared_ptr<DefinitionItem>
DefinitionItem::CreateField(const char* field, TypePtr t)
{
auto offset = rt->FieldOffset(field);
if ( (*fields)[offset] )
return (*fields)[offset];
(*fields)[offset] =
std::make_shared<DefinitionItem>(this, field, std::move(t));
return (*fields)[offset];
}
std::shared_ptr<DefinitionItem>
DefinitionItem::CreateField(int offset, TypePtr t)
{
if ( (*fields)[offset] )
return (*fields)[offset];
auto field = rt->FieldName(offset);
(*fields)[offset] =
std::make_shared<DefinitionItem>(this, field, std::move(t));
return (*fields)[offset];
}
void DefinitionItem::CheckForRecord()
{
if ( ! IsRecord() )
{
rt = nullptr;
return;
}
rt = t->AsRecordType();
num_fields = rt->NumFields();
fields = std::vector<std::shared_ptr<DefinitionItem>>(num_fields);
}
std::shared_ptr<DefinitionItem> DefItemMap::GetExprDI(const Expr* expr)
{
if ( expr->Tag() == EXPR_NAME )
{
auto id_e = expr->AsNameExpr();
auto id = id_e->Id();
return GetID_DI(id);
}
else if ( expr->Tag() == EXPR_FIELD )
{
auto f = expr->AsFieldExpr();
auto r = f->Op();
auto r_def = GetExprDI(r);
if ( ! r_def )
return nullptr;
auto field = f->FieldName();
return r_def->FindField(field);
}
else
return nullptr;
}
std::shared_ptr<DefinitionItem> DefItemMap::GetID_DI(const ID* id)
{
auto di = i2d.find(id);
if ( di == i2d.end() )
{
auto new_entry = std::make_shared<DefinitionItem>(id);
i2d[id] = new_entry;
return new_entry;
}
else
return di->second;
}
const DefinitionItem* DefItemMap::GetConstID_DI(const ID* id) const
{
auto di = i2d.find(id);
return di == i2d.end() ? nullptr : di->second.get();
}
const DefinitionItem* DefItemMap::GetConstID_DI(const DefinitionItem* di,
const char* field_name) const
{
return di->FindField(field_name).get();
}
} // zeek::detail
|
We strive to always give exceptional customer service.
We believe in giving value for money.
Face Painting & Glitter Tattoos an excellent addition to any party or event. We only use market leading Face Paints.
Children's Disco's are a fantastic extra to any childrens party. We have 2 options available and we are happy to discuss these options. |
import axios from 'axios';
const request = axios.create({
baseURL: process.env.VUE_APP_API_URL,
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
params: { 'api-key': process.env.VUE_APP_API_TOKEN },
});
export default request;
|
The present invention relates generally to a fluid transfer machine, and more particularly to a fluid transfer machine that can be used as a pump or motor.
Fluid transfer machines can have different types of pumping mechanisms to move fluid through the machine. One type of pumping mechanism useful for a variety of fluid transfer machines is a positive displacement rotary pump. Conventional positive displacement rotary pumps include single rotors (vane, piston, progressing cavity, screw or peristaltic), or multiple rotors (internal/external gear, lobe, circumferential piston or screw). The mechanisms all have advantages and drawbacks, depending on the fluid to be pumped, and the particular application.
During movement of the pumping mechanisms, friction can cause wear and heating of the moving parts, which can degrade the machine over time, and lead to failure and/or costly and time-consuming repairs.
Fluid is typically used for lubricating the moving parts of the pumping mechanism. It is particularly advantageous to use a portion of the fluid being transferred through the machine as the cooling and lubricating fluid. It is well-known to provide additional flow passages through the housing of the machine and to tap or bleed off a portion of the fluid from the primary flow for use in lubrication and cooling. It is also known to intentionally provide leak paths between the moving components and then collect the fluid for return to the primary flow path. Examples of such machines are shown in Ishizuka, U.S. Pat. No. 6,048,185; Riddle, U.S. Pat. No. 3,994,634; and Zieg, U.S. Pat. No. 2,940,399.
It is also known to provide grooves in rotating shafts to assist in moving the cooling and lubrication fluid between the components in the fluid transfer machine, such as shown in Sluijters, U.S. Pat. No. 3,368,799.
While the machines shown and described above are useful in some applications, forming (e.g., drilling) the flow passages in the machine to direct the cooling and lubricating fluid to the various components can be labor-intensive and difficult. A number of angled passages are typically required, which requires multiple drilling steps. This is shown particularly in Janczak, U.S. Pat. No. 4,548,557, where complex passages requiring multiple drilling steps are used to avoid connecting the primary fluid flow path directly with the drive shaft. Janczak points out that high pressure fluid around the drive shaft could damage or weaken the seals along the shaft.
Providing such complex passages also increases the size of the machine and the space necessary for locating the machine in the fluid transfer system. With the demand for smaller and lighter pumps and motors, and smaller fluid transfer systems, it has become increasingly difficult to manufacture such machines in a cost-effective, compact manner, particularly for high-performance applications which require high flow rates.
One partial solution is shown in Dworak, U.S. Pat. No. 4,038,000, where the primary flow path through the machine is directed from the inlet, through the gear mechanism (stub shafts and bearings), to the outlet. There are no additional lubrication and cooling passages for the bearings and stub shafts, beyond what is used to direct the primary flow through the machine. The Dworak machine has the advantage in that the machine is smaller and easier to construct, and keeps the pumping mechanism properly lubricated and cooled. Nevertheless, the Dworak machine does not address friction and wearing of the drive shaft, as the primary flow path in Dworak is limited to only the stub shaft and associated bearings. The drive shaft is also rotating, and particularly in high-performance applications, also has friction and wear issues.
Thus, it is believed there is a further demand for an improved fluid transfer machine, particularly a machine that can be used as a pump or motor, where the drive shaft is properly lubricated and cooled, and which has a compact design that is easily-manufactured.
The present invention provides a novel and unique fluid transfer machine, particularly useful as a pump or motor, where the drive shaft (as well as the pump mechanism) is properly lubricated and cooled, and which has a compact design that is easily-manufactured.
According to the present invention, the fluid transfer machine has a pumping mechanism that is a positive displacement, rotary (single or multiple rotor) type pump appropriate for the particular application. An external gear-type pump is used in a preferred form of the invention. The machine can be run as a motor or as a pump, as should be well know, typically by reversing the rotation of the pumping mechanism.
The pumping mechanism includes a typical arrangement of components such as bearings and stub shafts, which are preferably lubricated in a conventional manner, such as by allowing a slight leak path between the moving components.
The pumping mechanism is driven by a drive shaft, which extends out of the housing and is acted upon by (or acts upon) an external device. To lubricate and cool the drive shaft, and in particular the portion of the drive shaft internal to the housing, the drive shaft is located in the primary flow path through the fluid transfer machine. In a preferred embodiment, the drive shaft is located in the inlet flow path of the primary flow. The primary flow is directed from the inlet port to a cavity that surrounds the drive shaft, at a location between a pair of journal bearings or sleeves. The flow then continues to the suction side of the pumping mechanism. Alternatively, the drive shaft could be located in the outlet flow path of the primary flow path, between the pressure side of the pumping mechanism and the outlet port. In either case, the primary flow cools and lubricates the drive shaft (and drive shaft bearings), and reduces the size of the fluid transfer machine, as additional cooling and lubrication flow passage(s) are not necessary. This also reduces the complexity of manufacture of the machine.
The present invention thereby addresses many of the issues with prior machines, and provides a fluid transfer machine, particularly useful as a pump or motor, where the drive shaft (as well as the pump mechanism) is lubricated and cooled, and which has a compact design that is easily-manufactured. |
#Perceptrón
import numpy as np
def threshold(x):
if(x>=1):
return 1
elif(x<1):
return 0
def update(error, j):
global weights
global input_data
a = 0.2
for i in range(2):
weights['node_0'][i] = weights['node_0'][i] + (a*error*input_data[j][i])
#Datos de entrada
input_data = np.array([np.array([0,0]),np.array([0,1]),np.array([1,0]),np.array([1,1])])
weights = {'node_0': np.array([-0.2,0.4])}
output = np.array([0,0,0,1])
real = np.array([0,0,0,0])
epoch = 15
#epoch
for j in range(epoch):
print("Epoch ","(X1,X2) ","SalidaE ","SalidaR ","Error ","W1 ","W2\t")
for i in range(4):
valor = (input_data[i] * weights['node_0']).sum()
#print('Imprimir valor',valor) #BORRAR ESTO
salida = threshold(valor)
real[i] = salida
if(real[i] == output[i]):
error = 0
elif(real[i] != output[i]):
if(valor > 1):
error = -1
elif(valor < 1):
error = 1
if(error != 0):
update(error, i)
print("{} {} {} {} {} {:.2f} {:.2f}\t".format(j+1,input_data[i,],output[i],real[i] ,error,weights['node_0'][0],weights['node_0'][1]))
#Terminar
finaliza = (output == real)
if(finaliza.all()):
print('\nTermino')
break
|
import { List } from "../../Data/List";
import { bind, bindF, fromJust, isNothing, join, Just, liftM2 } from "../../Data/Maybe";
import { lookup } from "../../Data/OrderedMap";
import { ActionTypes } from "../Constants/ActionTypes";
import { HeroModel } from "../Models/Hero/HeroModel";
import { L10nRecord } from "../Models/Wiki/L10n";
import { getAvailableAPMap } from "../Selectors/adventurePointsSelectors";
import { getIsInCharacterCreation } from "../Selectors/phaseSelectors";
import { getCombatTechniques, getCurrentHeroPresent, getWikiCombatTechniques } from "../Selectors/stateSelectors";
import { translate, translateP } from "../Utilities/I18n";
import { getAreSufficientAPAvailableForIncrease } from "../Utilities/Increasable/increasableUtils";
import { pipe_ } from "../Utilities/pipe";
import { CombatTechniquesSortOptions } from "../Utilities/Raw/JSON/Config";
import { ReduxAction } from "./Actions";
import { addAlert, AlertOptions } from "./AlertActions";
export interface AddCombatTechniquePointAction {
type: ActionTypes.ADD_COMBATTECHNIQUE_POINT
payload: {
id: string;
}
}
export const addCombatTechniquePoint =
(l10n: L10nRecord) =>
(id: string): ReduxAction<Promise<void>> =>
async (dispatch, getState) => {
const state = getState ()
const mhero_combat_techniques = getCombatTechniques (state)
const wiki_combat_techniques = getWikiCombatTechniques (state)
const mhero = getCurrentHeroPresent (state)
const missingAPForInc =
pipe_ (
mhero,
bindF (hero => getAvailableAPMap (HeroModel.A.id (hero)) (state, { l10n, hero })),
join,
liftM2 (getAreSufficientAPAvailableForIncrease (getIsInCharacterCreation (state))
(bind (mhero_combat_techniques)
(lookup (id))))
(lookup (id) (wiki_combat_techniques)),
join
)
if (isNothing (missingAPForInc)) {
dispatch<AddCombatTechniquePointAction> ({
type: ActionTypes.ADD_COMBATTECHNIQUE_POINT,
payload: {
id,
},
})
}
else {
const opts = AlertOptions ({
title: Just (translate (l10n) ("notenoughap")),
message: translateP (l10n) ("notenoughap.text") (List (fromJust (missingAPForInc))),
})
await dispatch (addAlert (l10n) (opts))
}
}
export interface RemoveCombatTechniquePointAction {
type: ActionTypes.REMOVE_COMBATTECHNIQUE_POINT
payload: {
id: string;
}
}
export const removeCombatTechniquePoint = (id: string): RemoveCombatTechniquePointAction => ({
type: ActionTypes.REMOVE_COMBATTECHNIQUE_POINT,
payload: {
id,
},
})
export interface SetCombatTechniquesSortOrderAction {
type: ActionTypes.SET_COMBATTECHNIQUES_SORT_ORDER
payload: {
sortOrder: CombatTechniquesSortOptions;
}
}
export const setCombatTechniquesSortOrder =
(sortOrder: CombatTechniquesSortOptions): SetCombatTechniquesSortOrderAction => ({
type: ActionTypes.SET_COMBATTECHNIQUES_SORT_ORDER,
payload: {
sortOrder,
},
})
export interface SetCombatTechniquesFilterTextAction {
type: ActionTypes.SET_COMBAT_TECHNIQUES_FILTER_TEXT
payload: {
filterText: string;
}
}
export const setCombatTechniquesFilterText =
(filterText: string): SetCombatTechniquesFilterTextAction => ({
type: ActionTypes.SET_COMBAT_TECHNIQUES_FILTER_TEXT,
payload: {
filterText,
},
})
|
<gh_stars>10-100
/*
* Copyright 2014-2021 Web Firm Framework
*
* 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 com.webfirmframework.wffweb.server.page.action;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import com.webfirmframework.wffweb.server.page.Task;
import com.webfirmframework.wffweb.util.StringUtil;
import com.webfirmframework.wffweb.util.WffBinaryMessageUtil;
import com.webfirmframework.wffweb.util.data.NameValue;
public enum BrowserPageAction {
RELOAD(Task.RELOAD_BROWSER, null), RELOAD_FROM_CACHE(Task.RELOAD_BROWSER_FROM_CACHE, null);
private byte[] actionBytes;
private BrowserPageAction(final Task task, final String js) {
init(task, js);
}
private void init(final Task task, final String js) {
if (js != null) {
final NameValue nameValue = new NameValue();
nameValue.setName(js.getBytes(StandardCharsets.UTF_8));
nameValue.setValues(new byte[][] {});
actionBytes = WffBinaryMessageUtil.VERSION_1
.getWffBinaryMessageBytes(Task.RELOAD_BROWSER.getTaskNameValue(), nameValue);
} else {
actionBytes = WffBinaryMessageUtil.VERSION_1
.getWffBinaryMessageBytes(Task.RELOAD_BROWSER.getTaskNameValue());
}
}
/**
* @return the bytes for the browser action
* @since 2.0.3
* @author WFF
*/
public byte[] getActionBytes() {
return Arrays.copyOf(actionBytes, actionBytes.length);
}
/**
* @return the action {@code ByteBuffer} for the browser action
* @since 2.0.3
* @author WFF
*/
public ByteBuffer getActionByteBuffer() {
return ByteBuffer.wrap(actionBytes);
}
/**
* Gets the action {@code ByteBuffer} for executing the given JavaScript
*
* @param js JavaScript to execute in the browser
* @return the action {@code ByteBuffer} for executing the given JavaScript in
* the browser.
*
* @since 2.1.0 initial implementation.
* @since 3.0.15 throwing UnsupportedEncodingException is removed as announced
* in 3.0.1 release.
* @author WFF
*/
public static ByteBuffer getActionByteBufferForExecuteJS(final String js) {
return ByteBuffer.wrap(getActionBytesForExecuteJS(js));
}
/**
* Gets the action bytes for executing the given JavaScript in the browser.
*
* @param js JavaScript to execute in the browser
* @return the action bytes for executing the given JavaScript in the browser.
*
* @since 2.1.0 initial implementation.
* @since 3.0.15 throwing UnsupportedEncodingException is removed as announced
* in 3.0.1 release.
* @author WFF
*/
public static byte[] getActionBytesForExecuteJS(final String js) {
// this method will never throw UnsupportedEncodingException
// but not changing the method signature to keep consistency of this
// method
final NameValue taskNameValue = Task.EXEC_JS.getTaskNameValue();
final byte[][] taskValue = taskNameValue.getValues();
final byte[][] values = new byte[taskValue.length + 1][0];
System.arraycopy(taskValue, 0, values, 0, taskValue.length);
// previously it was passing "UTF-8" so it was throwing
// UnsupportedEncodingException
// but not it is not throwing this exception
// however, do not change method signature to keep consistency of the
// method accross multiple versions.
// handling JsUtil.toDynamicJs at server side is much better otherwise if the
// script is huge the client browser page might get frozen.
values[taskValue.length] = StringUtil.strip(js).getBytes(StandardCharsets.UTF_8);
taskNameValue.setValues(values);
return WffBinaryMessageUtil.VERSION_1.getWffBinaryMessageBytes(taskNameValue);
}
}
|
College of Business Faculty Views on Gift Authorships in Business Journals The views of college of business faculty were sought to determine their perception on the extent of undeserved authorship in business journals and their impact on the faculty reward system. Six hundred ninety-eight faculty members responded to an electronic survey conducted through Zoomerang. A total of 80% of the respondents indicated that they had been aware of a faculty member undeservedly being carried on a published business journal article, and 58% indicated that they had collaborated with a coauthor who had performed very little work, and 18% reported working with a coauthor who had actually done no work on a published article. |
Nephropathy and growth hormone deficiency in a patient with mitochondrial tRNA(Leu(UUR)) mutation. A mitochondrial A 3243 G mutation in the tRNA(Leu(UUR)) gene was first described as a common cause of MELAS syndrome (mitochondrial myopathy, encephalopathy, lactic acidosis, and stroke-like syndrome). This same mutation is also the cause of a totally different disorder, a subtype of diabetes mellitus which is inherited maternally and often associated with sensorineural hearing loss. In this paper, we report on a Japanese boy with A 3243 G who developed a previously undescribed combination of symptoms, nephropathy and growth hormone deficiency. The patient first presented with short stature and moderate mental retardation. Growth hormone (GH) provocation tests showed deficient growth hormone secretion. During the course of follow up, he presented with progressive nephropathy followed by the development of diabetes mellitus. The results of laboratory tests and renal biopsy were against incidental association of known types of nephropathy. On PCR-RFLP analysis, the percentage of mutated mtDNA was higher in the renal biopsy specimen than 12 peripheral blood leucocytes. Our case suggests that mitochondrial diseases should be taken into account when there is nephropathy of unknown cause. In addition, the presence of growth hormone deficiency may account for part of the mechanism leading to short stature commonly seen in these patients. |
1. Field of Invention
The invention relates to the field of surgical instruments, and more specifically to improvements in flexible shaft stabilizer devices and surgical tools usable in conjunction therewith.
2. Description of Related Art
In the field of medical instrumentation, flexible shaft stabilization devices are known in the art. Such devices are sold under the name OCTOPUS by the MEDTRONIC company and AXIUS by the GUIDANT company. Particularly in Coronary Artery Bypass Graft (CABG) procedures, such devices are used to stabilize the surface of the beating heart muscle at the site where an anastomosis will be formed. The devices commonly have a malleable shaft of a certain length, with a stabilizer foot or other apparatus at a distal end of the shaft. The apparatus is positioned as required, then a lead screw at a proximal end of the shaft is turned by some manner of handle to secure the shaft rigidly in place. The turning of the lead screw commonly applies tension to a fiber, such as a metal wire or braided cable. Tensioning of the cable compresses the flexible shaft, and secures it rigidly into an intended straight or curved position. These devices are considered an improvement over other stabilizers, because the length of the shaft can be positioned away from the surgical field, as compared to fixed-arm stabilizers that may impede access and vision to the surgical site.
These devices are not without drawbacks, however. Among the drawbacks are difficulties with tensioning the fiber or cable that compresses the flexible shaft. It has also been observed that after the first actuation of the shaft in such devices, subsequent actuations with equal turning of the actuator as the first actuation did not achieve the desired or necessary stiffness to hold the intended straight or curved position of the shaft. Further, currently available shafts are often not conducive to convenient positioning of the distal end of the flexible shaft at the surgical site by the surgeon, even when the shaft is in the relaxed state. Further, still detrimental wearing and gall can occur at the cam of the tensioning mechanism, including the generation of metal particulate that may compromise an otherwise sterile surgical field. Turning of the handle to tension the fiber and position the shaft appropriately is also a time consuming and cumbersome task often requiring assistance from a second medical professional. A great deal of force is typically required to actuate the handles of known flexible shaft devices having high shaft stiffness.
In addition to the drawbacks of known flexible shaft devices, a surgical apparatus secured to a distal end of a flexible shaft, or even a rigid retractor, may have its own drawbacks. A suction device for grasping and manipulating tissue such as those sold by the MEDTRONIC company under the brands STARFISH or URCHIN, or those sold by the GUIDANT company under the brand XPOSE may be used with a flexible shaft. The former lack the ability to dynamically adapt to moving tissue, such as the beating heart, however, and rely instead on the resiliency of the material comprising the suction device to better conform to the targeted tissue. The latter, on the other hand, are awkward, difficult to manipulate, and prone to user error.
Another apparatus that may be used in conjunction with a flexible shaft, though also with other devices, is a bendable suction bridge. Suction bridge stabilizers are used to immobilize tissue at a surgical site, for example the surface of the beating heart. These bridge devices typically place a stabilizing arm on either side of the target vessel, and use downward pressure to immobilize the tissue. Suction may be provided to secure the tissue to the stabilizer. However, it is desirable to position the suction devices perpendicularly to the heart surface, which itself is curved, the particular curvature individual to each patient. Rigid devices cannot accommodate this curvature in the heart. Moreover, is cumbersome to provide a suction line individually to each arm, however, as is commonly done in such devices. Likewise, it is desirable to avoid obstructing the vessel between the arms of the bridge, as a flat transverse bridge of known bridge devices might do.
Some devices in the prior art, including those sold under the OCTOPUS and ACROBAT brands, do not present a bendable bridge, and are therefore less able to adapt to the variety of tissue configurations a surgeon finds in practice. Others, such as those sold under the FLEXITE brand, are bendable at the bridge but not at the pods surrounding the arms, and require multiple vacuum inlets to each arm. Accordingly, an improved suction foot device that better conforms to the targeted tissue is desirable in the art. |
from strictyaml import Regex, ScalarValidator
from re import compile
from path import Path
import prettystack
from jinja2.environment import Environment
from jinja2 import DictLoader
from slugify import slugify
SRC_DIR = Path(__file__).realpath().dirname()
TEMPLATE_DIR = SRC_DIR.joinpath("templates")
DEFAULT_STACK_TRACE = (
prettystack.PrettyStackTemplate()
.to_console()
.cut_calling_code(SRC_DIR.joinpath("story.py"))
)
PARAM_REGEX = r"^\(\((.*?)\)\)$"
YAML_Param = Regex(PARAM_REGEX)
class UnderscoredSlug(ScalarValidator):
def validate_scalar(self, chunk):
return slugify(chunk.contents, separator="_")
def is_parameter(text):
"""
Is the chunk of YAML data passed to us a parameter?
i.e. like so (( parametername ))
"""
return isinstance(text, str) and compile(PARAM_REGEX).match(text) is not None
def parameter_name(text):
"""
Return parameter name from parameter text.
e.g. (( param_name )) -> "param_name"
"""
return compile(PARAM_REGEX).match(text).group(1).strip()
def to_underscore_style(text):
"""Changes "Something like this" to "something_like_this"."""
text = text.lower().replace(" ", "_").replace("-", "_")
return "".join(x for x in text if x.isalpha() or x.isdigit() or x == "_")
def underscore_slugify(text):
"""Changes "Something like this" to "something_like_this"."""
return slugify(text, separator=u"_")
def render_template(templates_dict, template_name, parameters):
"""
Render a jinja2 template.
"""
env = Environment()
env.loader = DictLoader(templates_dict)
return env.get_template(template_name).render(**parameters)
|
# -*- coding: utf-8 -*-
from django.template import Variable, TemplateSyntaxError, VariableDoesNotExist
def resolve_string_or_variable(value, context, safe=False, default=None, capture_none_value=True):
"""
Resolve a template variable within the given context
If the variable is a string (detected with surrounded quotes or double-quotes) it is
directly returned, else the ``Variable(value).resolve(context)`` method will be used
to find the variable in the context.
As opposite to ``Variable().resolve()`` this method can silently work with ``None`` or
empty value.
The process is :
* Surrounded variable by single ou double quotes mean a string that is returned without
the surround quotes;
* Else try to resolve it in the context;
* If the resolve fail, raise an exception ``TemplateSyntaxError`` if ``safe`` is ``False``
else return the ``default`` value that is ``None`` by default.
:type value: string
:param value: Valeur à résoudre. C'est soit directement une chaîne de caractères,
soit un nom de variable à résoudre dans le context du template.
:type context: object `django.template.RequestContext`
:param context: Objet du contexte du template en cours ou sera recherché la valeur
de la variable si ce n'est pas un simple string.
:type safe: bool
:param safe: (optional) Indique que l'échec pour retrouver le contenu de la variable
doit être silencieux. Si activé, la valeur par défaut de ``default``
est renvoyée. False par défaut, l'échec remonte une exception
`django.template.TemplateSyntaxError`.
:type default: any
:param default: (optional) Valeur par défaut renvoyée en cas d'échec pour retrouver
la variable et si le mode silencieux est activé. Par défaut la
valeur est ``None``.
:type capture_none_value: bool
:param capture_none_value: (optional) Indique si l'on doit capturer une variable du
nom de "None" directement comme un ``None`` sans tenter de
la résoudre comme un nom de variable. Dans ce cas, "None"
deviendra un nom réservé pour le templatetag en cours. Si
cette argument vaut ``False``, la méthode essayera de
résoudre "None" comme un nom de variable dans le contexte.
Par défaut cette option est activé (``True``).
:rtype: any
:return: La valeur de la variable si retrouvée, sinon la valeur par défaut.
"""
# Capture du nom de variable "None" directement comme un ``None``
if capture_none_value and value == "None":
return None
if value != None:
# Ne résoud pas les chaînes de texte (toujours encerclés par des simples ou
# doubles quotes)
if not(value[0] == value[-1] and value[0] in ('"', "'")):
# Tente de résoudre le nom de variable dans le context donné
try:
value = Variable(value).resolve(context)
except VariableDoesNotExist:
# Échec qui remonte une exception de template
if not safe:
raise TemplateSyntaxError("Unable to resolve '%s'" % value)
# Échec silencieux qui renvoi la valeur par défaut sans lever d'exception
else:
return default
# Chaîne de texte dont on retire les quotes d'encerclement de la valeur
else:
value = value[1:-1]
return value
|
The CHARGE Association in a Male Newborn Infant a constellation of malformations with the mnemonic of CHARGE: C-coloboma, H-heart disease, Rretarded growth and/or development, G-genital hypoplasia, and E-ear anomalies and/or deafness. Gleft lip was subsequently added to this list. We report the case of a male infant with the CHARGE association diagnosed in the neonatal period to illustrate the diagnostic and therapeutic dilemmas posed by a newborn with this set of malformations. |
We introduced Major E. (Eric Egland) in “The straight story,” documenting Eric’s close encounter with Pepsi’s public relations department over the 2005 Columbia Business School commencement speech by current Pepsi chief executive officer Indra Nooyi. (At the time Nooyi was Pepsi’s chef financial officer.) After Eric returned from a six month tour in Iraq working in counterintelligence on IEDs, I met up with him in Washington while he was serving in the Pentagon. A 1992 graduate of the Air Force Academy, Eric struck me as an outstanding officer with an enormous contribution to make on the home front. |
def calc_standard_energy(self, steps, package, input_path=None):
if package is "vasp" and input_path is None:
print("Error: In vasp calculation, you must set path to POTCARs as input_path.")
return
structs = {}
for specie in self.species:
structs[specie] = pymatgen.Structure.from_str(
open(self.standard_struct_path+str(specie)+"/POSCAR").read(),
fmt="poscar"
)
standard_energy = PyHighThroughput(
input_path=input_path,
output_path=None,
**structs
)
standard_energy.run(steps=steps, package=package)
return standard_energy.results |
Identifying Gut Microbiota Associated With Colorectal Cancer Using a Zero-Inflated Lognormal Model Colorectal cancer (CRC) is the third most common cancer worldwide. Its incidence is still increasing, and the mortality rate is high. New therapeutic and prognostic strategies are urgently needed. It became increasingly recognized that the gut microbiota composition differs significantly between healthy people and CRC patients. Thus, identifying the difference between gut microbiota of the healthy people and CRC patients is fundamental to understand these microbes' functional roles in the development of CRC. We studied the microbial community structure of a CRC metagenomic dataset of 156 patients and healthy controls, and analyzed the diversity, differentially abundant bacteria, and co-occurrence networks. We applied a modified zero-inflated lognormal (ZIL) model for estimating the relative abundance. We found that the abundance of genera: Anaerostipes, Bilophila, Catenibacterium, Coprococcus, Desulfovibrio, Flavonifractor, Porphyromonas, Pseudoflavonifractor, and Weissella was significantly different between the healthy and CRC groups. We also found that bacteria such as Streptococcus, Parvimonas, Collinsella, and Citrobacter were uniquely co-occurring within the CRC patients. In addition, we found that the microbial diversity of healthy controls is significantly higher than that of the CRC patients, which indicated a significant negative correlation between gut microbiota diversity and the stage of CRC. Collectively, our results strengthened the view that individual microbes as well as the overall structure of gut microbiota were co-evolving with CRC. INTRODUCTION A large number of microbes colonize the human body. They form a complex microbial community, or microbiota (;;). Among them, the gut microbiota is the most diverse, with more than 1,000 species (;;). Those microbes are involved in maintaining intestinal homeostasis, through physiological processes such as metabolism, immune responses, and inflammation, all of which are essential for human health. Previous studies revealed a deliciated and dynamic balance between the microbial community and the host, which is likely the result of long term co-evolution. However, studies also observed that pathogenic changes in the structure, composition, and function of gut microbiota can lead to various diseases, often by causing the production of abnormal metabolites (a;a,b). Those diseases and conditions include irritable bowel syndrome (), Crohn's disease (Sommer and Bckhed, 2013), and colorectal cancer (CRC) (;). The mechanisms by which gut microbes influence the CRC tumorigenesis () were actively under study. For examples, researchers have recently learned that the gut microbiota plays a regulatory role in the tumor microenvironment and thus in tissue carcinogenesis (;;). Guo et al. also found that the microbiota structure and microbial metabolites can affect the body's susceptibility to CRC by directly inducing pathological conditions, such as adenoma (). However, to further understand such interactions, it is essential to characterize and compare the gut microbiota structure of healthy controls and cancer patients. And based on that, specific microbiota patterns or strain types need to be identified to provide new targets and strategies for cancer prevention and treatment ((Hu et al.,, 2018a,b,c). Therefore, in this paper, we aim to determine the microbes that are associated with CRC using a large-scale metagenomic data set. While the metagenomics research has provided enormous scientific data for investigating the role of the gut microbiota in the context of cancer development and progression (), appropriate bioinformatics and statistical analyses are also required to accurately identifying the differential microbes. Several algorithms using either parametric or non-parametric tests have been proposed to determine such species. For examples, Abusleme et al. combined the Kruskal-Wallis test with the Wilcoxon rank-sum test to analyze periodontitis data and used linear discriminant analysis to identify the species with significant differences between periodontitis patients and healthy controls. Nagy-Szakal et al. used the non-parametric Mann-Whitney U test with Benjamini-Hochberg correction to show that the microbial composition in the intestines of patients with chronic fatigue syndrome differed significantly from that of healthy individuals (). And Peng et al. conducted beta regression on the abundance of microbes to obtain regression coefficients (). One particular difficulty associated with the statistical testing of differential abundance is the under-sampling or dropout () of less abundant microbes caused by an insufficient sequencing depth. This fact creates many zeros in the abundance values and leads to inaccurate differential analysis when only conventional normalization was applied. This issue might be mitigated with the Zero-inflated Negative Binomial modeling (ZINB) (). The method is now widely adopted. For examples, Paulson et al. analyzed the differential abundance in sparse high-throughput large-scale microbial marker gene survey data by using a zero-inflated Gaussian distribution mixture model with cumulative-sum scaling normalization (). Zhang et al. identified differentially abundant taxa between two or more populations by using a ZINB regression method and estimated the model parameters by Expectation Maximization algorithm. Chen et al. proposed a zero-inflated Beta regression model which included two parts: a logistic regression component and a Beta regression component, for testing the association between microbial abundance and clinical covariates for longitudinal microbiome data (Chen and Li, 2016). Chen Jun et al. in 2017, proposed a robust and powerful framework of differential analysis of microbiome data based on a zero-inflated negative binomial (ZINB) regression model. They also proposed an omnibus test of all the parameters. Omnibus test was compared with previous methods by using simulated data. RAIDA had slightly worse FDR control at a high nominal level than omnibus test, but better FDR control than other methods. The performance of RAIDA was close to that of the omnibus test, and were higher than one of other methods. RAIDA is more effective at controlling FPR than other method including the omnibus test. In this study, we identified the differentially abundant gut microbes between CRC and healthy samples using the Ratio Approach for Identifying Differential Abundance (RAIDA) algorithm (). The algorithm fitted the distribution of observed data with a modified zero-inflated lognormal (ZIL) model and estimated the statistical significance of abundance difference by the T-test. Furthermore, we used the GRAMMy algorithm () to estimate and analyze the relative abundance of gut microbes and diversity of the microbial communities. Finally, we constructed and analyzed a microbial association network based on all healthy, small adenoma, large adenoma, and CRC samples. Two Metagenomics Datasets Our first gut metagenomics dataset was downloaded from the European Nucleotide Archive (ENA) database (accession number ERP005534) ( Table 1). The dataset () consists of 156 samples from France (61 healthy, 27 small adenoma, 15 large adenoma, and 53 CRC samples). Samples with an adenoma diameter smaller than 10 mm were classified as small adenoma while those with larger than 10 mm ones were classified as large adenoma. Our second gut metagenomics dataset was also downloaded from the ENA database (accession number ERP008729) (). The dataset included 156 samples from Austria, including 63 healthy samples, 47 adenoma patient samples, and 46 CRC patient samples. A Modified ZIL Model We estimated the relative abundance of gut microbes using the GRAMMy algorithm. We then identified differentially abundant microbes by the RAIDA algorithm which uses a modified ZIL model to account for ratios with zeros. Metagenomic data are typically sparse because of undersampling Let ij denote the observed count for microbes i and sample j, and let r ij denote the ratio of ij to kj, where k represents the microbe (or a set of microbes) used as a divisor and kj > 0 for all j. Here, i = 1, 2,..., n and j = 1, 2,..., m. The abundance ratio computed this way is denoted as R ij such that: In this study, we used = min(r ij r ij > 0) for all i and j. The parameters i = ( i, i, i ) were estimated by the following expectation-maximization (EM) algorithm. Given that a ratio R follows a lognormal distribution, thus: in which, by definition, Y = log R is normally distributed with mean and variance 2. Let y ij = log r ij, z ij is an unobservable latent variable that accounts for the probability of zero coming from the false state. Thus, the maximum-likelihood estimate of i for the modified ZIL model, i.e., Equation, can be obtained by solving where is the probability density function of a normal distribution. Diversity Analysis To analyze microbial diversity, alpha diversity was used to measure the differences in gut microbial structure in the following three stages: healthy, adenoma (small and large combined), and cancer. We used the Shannon diversity index to measure the alpha diversity of the gut community. The Shannon index is defined as where H represents the Shannon Index, N indicates the total number of microbial species detected, and a j indicates the relative abundance of the j th microorganism. Alpha Diversity of Gut Microbiota Predicts Colorectal Cancer Status We computed the alpha diversity of gut microbes of the healthy samples, adenoma samples and CRC samples using the Shannon index and compared them with the rank-sum Dunn test (Figure 1). We found that the alpha diversity was significantly lower in the CRC samples as compared to the healthy samples (two tailed, Dunn test, P < 0.0001) and adenoma samples (two tailed, Dunn test, P = 0.0021). However, the alpha diversity of the healthy and adenoma samples was not significantly different (two tailed, Dunn test, P = 0.0571). To study the relationship between the probability of cancer occurrence and the alpha diversity, we performed logit regression to associate CRC status with the Shannon index. The regression results showed that the Shannon index is a significant predictor of CRC status (univariate i.e., logit(P) = −4.563d + 17.546, where P is the probability of being CRC, and d is the Shannon diversity index. We provided the plot of the relationship of probability of cancer occurrence and Shannon index of adenoma patients as show in Figure S1. Our result suggested that the diversity of the microbial species in the human intestines decreases as colorectal malignancies grow, which was supported by literature (). Nine Genera Were Differentially Abundant in the Colorectal Cancer Gut Environment Using the RAIDA algorithm, we identified nine microbial genera that were significantly different in abundance between the CRC and the controls, which included Anaerostipes, Coprococcus, Pseudoflavonifractor, Bilophila, Flavonifractor, Desulfovibrio, Catenibacterium, Porphyromonas, and Weissella (Figure 2A). We first observed that the abundance of Coprococcus was higher in the healthy samples as compared to the CRC patients. As a validation, Shen et al. showed that colorectal adenomas had lower relative abundance of Bacteroides spp. and Coprococcus spp. than controls (). The metabolic activity of butyrateproducing bacteria is the major source of butyrate in human body. Coprococcus is among the essential butyrateproducing genera in human body, which promote colonic health by mediating anti-inflammatory and antitumor effects, as well as providing energy for colonocytes (). Also notable in our result were the genera Fusobacterium (Fusobacteriaceae) and Porphyromonas (Porphyromonadaceae), which were shown highly enriched in the CRC patients. So was the species Bibliophile wadsworthia. Those sulfidogenic bacteria, including Desulfovibrio, Fusobacterium, and Bilophila wadsworthia, likely participate in the development of CRC by producing hydrogen sulfide (;). Bilophila wadsworthia was additionally reported to cause systemic inflammatory response in a preclinical mice study (). Interestingly, we also observed that the abundance of Eubacterium hallii, Anaerostipes hadrus, and Eubacterium ventriosum ( Figure 2B) were significantly higher in the healthy samples than in the CRC samples. E. hallii and A. hadrus can utilize the glucose and fermentation intermediates acetate and lactate to form butyrate and hydrogen, which were considered important microbes in maintaining intestinal metabolic balance (). We also found that Flavonifractor was higher in the healthy samples than that in the CRC samples, which was in agreement with Anand et al.. We also observed that Anaerostipes had a significantly lower abundance in the CRC samples, which agreed with previous studies (;). We found that no Catenibacterium and Gardnerella (Bifidobacteriaceae) were present in CRC patient samples, which was supported by Chen et al.. We tested if the nine differentially abundant genera are viable biomarkers to distinguish healthy individuals from CRC patients. We trained a random forest classifier using a 5-fold crossvalidation (rotative using 80% data as the training set the rest 20% as the testing set) using the first metagenomic dataset. The classifier achieved an Area Under Curve (AUC) of 0.9333. Microbial Co-occurrence Network Evolves With CRC Development Sophie Weiss et al. compared 8 methods of establishing association networks, they recommend filtering out extremely rare OTUs prior to network construction (). According to Figure 7 in this paper, SparCC should be used when the inverse simpson n eff of microbes < 13, SparCC maintain high precision compared with predictions on abundance tables with low n eff. But the inverse simpson n eff of microbes is 27.9 (>13) in our paper, abundance of OTUs are more than 50% sparse. So we calculated the correlation between species by Pearson correlation coefficient. We further conducted an association network analysis to identify the cooccurring intestinal microbes under different CRC states. All significant co-occurrences (PCC > 0.5) were found to be within the same genera, such as Bifidobacterium, Bacteroides, and Bilophila (Figure 3). Furthermore, both Bifidobacterium and Bacteroides were previously identified by us to have significant differences in abundance between healthy controls and CRC patients ( Figure 3A). It is thus reasonable to assess that these bacteria were pathogenic as a group because the change of abundance in one them can result in changes of abundance in the entire clique. Our observation supported the theory that CRC ensues an interrupted balance between these bacteria (Brennan and Garrett, 2016;). Co-occurrence was also found among species of the genus Prevotella in the healthy, small adenoma, and large adenoma environments (Figures 3A-C), however, such co-occurrence was missing in the CRC environment ( Figure 3D). Conversely, several species of the genera Streptococcus, Parvimonas, Collinsella, and Citrobacter were only co-occurring in the cancer environment. Overall, we observed fewer microbial co-occurrences the healthy environment. While, in the adenoma environments, we found an increase of co-occurring pathogenic microbes. The number of co-occurring microbes was then reduced in the CRC environment. The total number of cooccurrence is relatively close between the healthy and the CRC environment, however, the microbes involved were distinct. The number of total co-occurrence might have peaked at the adenoma environments because of the co-existence of competing homeostatic and pathogenic microbial interactions in the intermediacy stage. CONCLUSIONS We analyzed the alpha diversity of the gut microbial community of 156 healthy, adenoma and CRC samples. We found the alpha diversity was significantly higher in healthy samples as compared to the CRC samples. We applied a modified ZIL model and identified nine significantly different genera between the healthy and CRC groups, i.e., Anaerostipes, Bilophila, Catenibacterium, Coprococcus, Desulfovibrio, Flavonifractor, Porphyromonas, Pseudoflavonifractor, and Weissella. We used these nine genera as input features for a random forest classifier and successfully predicted the CRC status with a high AUC score of 0.9333. Our results suggested that the community member and the overall structure of the gut microbiota are potential effective biomarkers of CRC stages. This avenue is being actively pursued by us and other computational researchers (Chen and Yan, 2013;bChen et al.,,c, 2018aChen and Huang, 2017), who may bring in novel strategies for preventing and curing CRC in the near future. AUTHOR CONTRIBUTIONS DA and YG conducted the analysis, summarized the result and drafted the manuscript. HP, XL, and GL assisted in the data analysis and contributed to the manuscript. DA and LX conceived the study. LX supervised the manuscript writing. All authors have read and approved the final manuscript. FUNDING This work was supported by grants from the National Natural Science Foundation of China. LX is supported by the Innovation in Cancer Informatics Fund, American Cancer Society (132922-PF-18-184-31301-TBG), the National Institutes of Health (HG006137-07), and funds from the Intermountain Healthcare. ACKNOWLEDGMENTS Both DA and LX thank Professor Fengzhu Sun at the University of Southern California and LX thanks Dr. Nancy Zhang at the University of Pennsylvania and Dr. Hanlee Ji at Stanford University for their support and helpful discussions. SUPPLEMENTARY MATERIAL The Supplementary Material for this article can be found online at: https://www.frontiersin.org/articles/10.3389/fmicb. 2019.00826/full#supplementary-material Figure S1 | Logit regression prediction results of the Shannon diversity index. The blue circle in the figure represents a large adenoma sample, and the red triangle represents a small adenoma sample. |
Parallel Frequency Function-Deep Neural Network for Efficient Approximation of Complex Broadband Signals In recent years, with the growing popularity of complex signal approximation via deep neural networks, people have begun to pay close attention to the spectral bias of neural networksa problem that occurs when a neural network is used to fit broadband signals. An important direction taken to overcome this problem is the use of frequency selection-based fitting techniques, of which the representative work is called the PhaseDNN method, whose core idea is the use of bandpass filters to extract frequency bands with high energy concentration and fit them by different neural networks. Despite the methods high accuracy, we found in a large number of experiments that the method is less efficient for fitting broadband signals with smooth spectrums. In order to substantially improve its efficiency, a novel candidatethe parallel frequency function-deep neural network (PFF-DNN)is proposed by utilizing frequency domain analysis of broadband signals and the spectral bias nature of neural networks. A substantial improvement in efficiency was observed in the extensive numerical experiments. Thus, the PFF-DNN method is expected to become an alternative solution for broadband signal fitting. Introduction An artificial neural network, also known as a neural network, refers to a mathematical model that imitates animal neural network behavior, which is essentially a high-dimensional complex mapping model wherein adjusting network weights allows for feature fitting. A neural network's basic building blocks are a neuron model, a parameterized model nested by a scalar linear function, and a monotonic nonlinear function (activation function), where the coefficients in the linear function are the connection weights between neurons. Neurons connecting according to a specific topology form a neural network. One of the primary networks is the single-layer network composed of multiple neurons in parallel. Multiple single-layer networks can be stacked to obtain a multi-layer network and further expanded into a deep neural network that contains multiple multilayer networks. Some advanced neural network models are designed to meet the needs of engineering practice. For example, convolutional neural networks (CNN) and their evolution models have achieved unprecedented success in computer vision due to their powerful feature extraction capabilities and are widely used in security monitoring, autonomous driving, human-computer interaction, augmented reality, and many other fields. Additionally, recurrent neural networks, especially the long-short-term memory (LSTM), have become mainstream tools in the fields of automatic translation, text gen ation, and video generation in just a few years. The related research of the universal approximation indicates that assumi sufficient neurons and suitable weights, the neural network could approximate any co tinuous signals on a compact subset of ℝ n with arbitrary precision. However, it is not ea to obtain these appropriate weights via training for a complex network with too ma neurons. The convergence speed of the neural network is related to the frequency sp trum of the fitted signal. As shown in Figure 1, the neural network first learns t low-frequency components during the training process. The relationship between the co vergence speed and the frequency of the fitted signal has been quantitatively analyz. When a network is applied to fit a signal, the required training time increases exp nentially as the component's central frequency increases. The spectral bias of the conv gence speed in network training leads to unbearable training times for fitting the hig frequency components in broadband signals. In recent years, differential equation solvi based on physical knowledge constraints has been successful in many applications, b multi-scale and multi-physics problems need further development. One of the core pro lems is that it is difficult for fully connected neural networks to learn high-frequency fun tions, that is, the spectral bias problem. Solving this problem has become one of t core bottlenecks for the further development of A.I. technology. To this end, Cai et al. proposed the PhaseDNN method for fitting complex sign with high-frequency components via the combination of parallel frequency band extr tion and frequency shifting techniques. Numerous numerical experimental resu have indicated that the PhaseDNN method successfully avoids the computational c disaster when fitting signals with high-frequency components. However, although t method has good approximation efficiency for broadband signals, we found in our n merical experiments that for a large number of typical signals, especially those w smooth frequency domain distribution, the operation of fitting the inverse transform signals can be further optimized, thus greatly improving the neural network fitting e ciency. To this end, Cai et al. proposed the PhaseDNN method for fitting complex signals with high-frequency components via the combination of parallel frequency band extraction and frequency shifting techniques. Numerous numerical experimental results have indicated that the PhaseDNN method successfully avoids the computational cost disaster when fitting signals with high-frequency components. However, although the method has good approximation efficiency for broadband signals, we found in our numerical experiments that for a large number of typical signals, especially those with smooth frequency domain distribution, the operation of fitting the inverse transformed signals can be further optimized, thus greatly improving the neural network fitting efficiency. Therefore, our paper is dedicated to investigating a more efficient candidate method for fitting complex signals-signals with smooth frequency domain distribution. To reach this goal, a parallel frequency function-deep neural network (PFF-DNN) is proposed by utilizing the fast Fourier analysis of broadband signals and the spectral bias nature of neural networks. The effectiveness and efficiency of the proposed method are verified based on detailed experiments for six typical broadband signals. The discussion shows how the neural network adaptively constructs low-frequency smooth curves to interpolate discrete signals. This adaptive low-frequency approximation makes it possible to fit discrete frequency domain signals accurately. The paper is organized as follows. Related works and the proposed method are introduced in Section 2. Extensive numerical experiments are presented in Section 3. Finally, the paper is concluded in Section 4. Recent PhaseDNN The research mentioned above indicates that it is difficult for neural networks to directly and accurately fit signals with high-frequency components. However, if we can transform the high-frequency components in the signal into smooth low-frequency signals convenient for neural network fitting, by some means such as the application of frequency shift technology, we can approximate the original signal via component-by-component fitting. Following this idea, in 2020, Cai et al. proposed the PhaseDNN method to implement a fitting scheme for signals with high-frequency components. As shown in Figure 2, the PhaseDNN method involves four steps: all high-frequency components in the original objective signal are extracted; each high-frequency component is converted into a low-frequency signal using frequency shift technology; different neural networks with identical structure are used to fit these low-frequency signals in parallel; and inverse frequency shift operations are performed for all network predictions to obtain approximated high-frequency components, which are further summed up to recover the original signal. Therefore, our paper is dedicated to investigating a more efficient candidate m for fitting complex signals-signals with smooth frequency domain distribution. To this goal, a parallel frequency function-deep neural network (PFF-DNN) is propos utilizing the fast Fourier analysis of broadband signals and the spectral bias nature o ral networks. The effectiveness and efficiency of the proposed method are verified on detailed experiments for six typical broadband signals. The discussion shows ho neural network adaptively constructs low-frequency smooth curves to interpolate di signals. This adaptive low-frequency approximation makes it possible to fit discret quency domain signals accurately. The paper is organized as follows. Related works and the proposed method a troduced in Section 2. Extensive numerical experiments are presented in Section 3. Fi the paper is concluded in Section 4. Recent PhaseDNN The research mentioned above indicates that it is difficult for neural networks rectly and accurately fit signals with high-frequency components. However, if w transform the high-frequency components in the signal into smooth low-frequenc nals convenient for neural network fitting, by some means such as the application o quency shift technology, we can approximate the original signal via component-by ponent fitting. Following this idea, in 2020, Cai et al. proposed the PhaseDNN meth implement a fitting scheme for signals with high-frequency components. As s in Figure 2, the PhaseDNN method involves four steps: all high-frequency compo in the original objective signal are extracted; each high-frequency component is verted into a low-frequency signal using frequency shift technology; different n networks with identical structure are used to fit these low-frequency signals in pa and inverse frequency shift operations are performed for all network predictio obtain approximated high-frequency components, which are further summed up cover the original signal. Figure 3 shows a comparison between the fitted results from the PhaseDNN method and those obtained via vanilla fitting. As shown in Figure 3a, vanilla fitting cannot recover high-frequency components well. If the signal oscillates even faster, the vanilla fitting becomes entirely ineffective. On the contrary, as shown in Figure 3c,d, the recent PhaseDNN method has shown obvious advantages in being able to completely characterize the information of all frequency bands of the signal. Sensors 2022, 22, x FOR PEER REVIEW 4 of becomes entirely ineffective. On the contrary, as shown in Figure 3c,d, the rece PhaseDNN method has shown obvious advantages in being able to completely characte ize the information of all frequency bands of the signal. It should be noted that the extracted frequency bandwidth needs to be minimized ensure fitting accuracy. On the one hand, the smaller the extracted frequency band's wid, the higher the fitting accuracy. On the other hand, a smaller indicates more fr quency bands are extracted, which directly leads to an increase in computational ove head. When using PhaseDNN for broadband signal fitting, it is often necessary to extra all frequency bands and fit them separately. Therefore, there is a balance between acc racy and computational overhead. For example, consider the task of performing neur network fitting on a signal with a bandwidth of 300 Hz. When = 10, considering t existence of both real and imaginary parts in the spectrum and the conjugate symmetr 30 2 groups of neural networks need to be trained, which is an acceptable computation overhead. However, for the task of neural network fitting on a signal with a bandwid of 3000 Hz, 3000 2 groups of neural networks need to be trained, which significant increases the computational overhead. The Proposed PFF-DNN Method It is preferable to determine a method that can ensure fitting accuracy without r quiring a large number of extracted frequency signals to be selected. Using the fast Fouri transformation (FFT) of broadband signals, the digital spectrum of the signal can obtained much more efficiently. It is conceivable that if we perform a piecewise fitting o a signal's digital spectrum, no computational overhead is required for frequency selectio or frequency shift. This avoids several redundant operations in the PhaseDNN metho It should be noted that the extracted frequency bandwidth needs to be minimized to ensure fitting accuracy. On the one hand, the smaller the extracted frequency band's width ∆, the higher the fitting accuracy. On the other hand, a smaller ∆ indicates more frequency bands are extracted, which directly leads to an increase in computational overhead. When using PhaseDNN for broadband signal fitting, it is often necessary to extract all frequency bands and fit them separately. Therefore, there is a balance between accuracy and computational overhead. For example, consider the task of performing neural network fitting on a signal with a bandwidth of 300 Hz. When ∆ = 10, considering the existence of both real and imaginary parts in the spectrum and the conjugate symmetry, 30 2 groups of neural networks need to be trained, which is an acceptable computational overhead. However, for the task of neural network fitting on a signal with a bandwidth of 3000 Hz, 3000 2 groups of neural networks need to be trained, which significantly increases the computational overhead. The Proposed PFF-DNN Method It is preferable to determine a method that can ensure fitting accuracy without requiring a large number of extracted frequency signals to be selected. Using the fast Fourier transformation (FFT) of broadband signals, the digital spectrum of the signal can be obtained much more efficiently. It is conceivable that if we perform a piecewise fitting on a signal's digital spectrum, no computational overhead is required for frequency selection or frequency shift. This avoids several redundant operations in the PhaseDNN method. In addition, when the frequency spectrum of the signal is not overcomplicated, the efficiency of fitting in the frequency domain will significantly improve. The method proposed here is abbreviated as the PFF-DNN method, and the details of its construction are as follows: The objective signal is denoted as a real-valued f (x) in the domain of . From a digital sampling system, one can obtain the discrete value of the signal f (x) at the sampling points {x 0, x 1,..., x n−1 }. Here, the sampling points are assumed to be uniformly distributed on the interval of , and the discrete value of the signal f (x) at the sampling points are denoted as f 0, f 1,..., f n−1. One can calculate the frequency spectrum F() as: where k = 0, 1,..., n -1, and k is evenly distributed. The adjacent interval between k depends on the sampling interval. F() is conjugate symmetric when the signal is real-valued. Here, {F k } is divided into m segments of length ∆ in order, in which n = m∆: where In the following, we define S i as the ith segment of F(). Considering the conjugate symmetry, only half of {F k } needs fitting. Further considering that the sampling frequency is much larger than the bandwidth of the signal ( b = b∆), Equation can be approximated by: where and in which * stands for the conjugate operation. For each slice S i, a neural network is used to approximate the information T i contained. More precisely: where i = 1, 2,..., b. One can see from Equation that, different from PhaseDNN, in the proposed method, each neural network T i is used to "memorize" the discrete data in the frequency domain. After obtaining these trained neural networks and their predictions {T i }, the following concatenation operation is used to obtain the approximation of F(): Finally, each sampling signals f j can be approximated using the following inverse FFT (IFFT): Let us compare the recent PhaseDNN method and the proposed PFF-DNN method in terms of ease of operation. In PhaseDNN, 2m convolutions are required to acquire all frequency-selected signals. Then, 2m frequency shifts and 2m inverse frequency shifts are also involved. In comparison, the proposed method is more straightforward, and only one FFT and one IFFT are required. No frequency selection, frequency shifts, nor inverse shifts are required. In the PhaseDNN method, DNNs are used to fit continuous signals in the time domain. On the contrary, in the proposed method, DNNs are used to "memorize" discrete data points in the frequency domain. For many commonly used signals (including the signals recommended in to demonstrate the effectiveness of the PhaseDNN method), detailed numerical comparisons are conducted to show that the neural network "memorizes" such discrete frequency values much faster. Experimental Setting Six typical signal analyses were performed to evaluate the fitting performance of our PFF-DNN method, accompanied by a comparison with the existing PhaseDNN method. The signals to be analyzed included some periodic and non-periodic analog signals in the form of explicit functions and complex signals described by the classical Mackey-Glass differential dynamic system. For each signal, detailed comparative evaluations were conducted to describe the effectiveness and efficiency of the different methods for fitting the broadband signals with high-frequency components. The detailed comparisons included convergence curves (the changes of the loss R concerning the number of updates N of the neural network weights); the convergence process of different frequency bands; the influence of different ∆ on the convergence speed; and the influence of different updating times N on the fitting accuracy. Before showing the experimental results, we first introduce the neural network model and training-related parameters for all subsequent experiments. The neural network structure used in this study was consistent with the network used in (i.e., the 1-40-40-40-40-1 fully connected neural network). Each layer (except the output layer) used the 'ELU' activation function. The neural network training adopted the Adam optimizer with a learning rate of 0.0002. The length of each training batch was 100. For the method in, 5000 training data and 5000 testing data were evenly distributed across the domain. For the method proposed in this paper, each slice's length of the training sample depended on the slice's length in the frequency domain. For both methods, we recorded the approximation error in the root mean square error (RMSE) when ∆ of the slice in the frequency domain was 11, 21, 31, 41, or 51, and when the total number of updates were from 1 to 10,000. The ∆ used in the literature was 11. Therefore, we gradually increased ∆ from this value. When ∆ increases to infinite, both methods will degenerate into the vanilla fitting method. Therefore, we set the upper limit of ∆ to 51. The numerical experiments were completed using a PC with an Intel-core-i9-9900X CPU @ 3.50 GHz with 128 GB-RAM and a Titan X GPU. Sine on Polynomial Signal Here, the signal of sine on polynomial was used to test the neural network's approximation accuracy, which is similar to the function used in the literature. It is described by Equation, whose shape and the corresponding frequency spectrum are shown in Figure 4. The signal consists of a high-frequency periodic component and a low-frequency non-periodic component. On the contrary, if the PhaseDNN or PFF-DNN method was used, the signal was fitted very well. As mentioned earlier, a larger indicates fewer neural networks used for fitting, which is desirable. For the current example, the bandwidth of the signal is 50 Hz. When = 11, to approximate the signal precisely, one needs to use at least five networks for fitting. In comparison, when = 51, one only needs two networks for fitting, which saves 80% of the computation resources. However, an increase in makes the fitting harder. Figure 6 shows how the convergence process of the PhaseDNN and PFF-DNN methods changed with. It was shown that both algorithms converged fast when was small. However, when increased, the convergence speed of both methods slowed down. Note that, compared with the PhaseDNN method, the PFF-DNN algorithm was less sensitive to the increase in. In detail, for the PhaseDNN method, when = 11, the network updated 10,000 times to reach convergence. However, when = 41, it was difficult to converge even if it was trained 100,000 times. In contrast, for the PFF-DNN method, when = 41, it converged within only 2000 updates. That is to say, when tripled, the convergence time only doubled. This is desirable in practical applications. On the contrary, if the PhaseDNN or PFF-DNN method was used, the signal was fitted very well. As mentioned earlier, a larger indicates fewer neural networks used for fitting, which is desirable. For the current example, the bandwidth of the signal is 50 Hz. When = 11, to approximate the signal precisely, one needs to use at least five networks for fitting. In comparison, when = 51, one only needs two networks for fitting, which saves 80% of the computation resources. However, an increase in makes the fitting harder. Figure 6 shows how the convergence process of the PhaseDNN and PFF-DNN methods changed with. It was shown that both algorithms converged fast when was small. However, when increased, the convergence speed of both methods slowed down. Note that, compared with the PhaseDNN method, the PFF-DNN algorithm was less sensitive to the increase in. In detail, for the PhaseDNN method, when = 11, the network updated 10,000 times to reach convergence. However, when = 41, it was difficult to converge even if it was trained 100,000 times. In contrast, for the PFF-DNN method, when = 41, it converged within only 2000 updates. That is to say, when tripled, the convergence time only doubled. This is desirable in practical applications. On the contrary, if the PhaseDNN or PFF-DNN method was used, the signal was fitted very well. As mentioned earlier, a larger ∆ indicates fewer neural networks used for fitting, which is desirable. For the current example, the bandwidth of the signal is 50 Hz. When ∆ = 11, to approximate the signal precisely, one needs to use at least five networks for fitting. In comparison, when ∆ = 51, one only needs two networks for fitting, which saves 80% of the computation resources. However, an increase in ∆ makes the fitting harder. Figure 6 shows how the convergence process of the PhaseDNN and PFF-DNN methods changed with ∆. It was shown that both algorithms converged fast when ∆ was small. However, when ∆ increased, the convergence speed of both methods slowed down. Note that, compared with the PhaseDNN method, the PFF-DNN algorithm was less sensitive to the increase in ∆. In detail, for the PhaseDNN method, when ∆ = 11, the network updated 10,000 times to reach convergence. However, when ∆ = 41, it was difficult to converge even if it was trained 100,000 times. In contrast, for the PFF-DNN method, when ∆ = 41, it converged within only 2000 updates. That is to say, when ∆ tripled, the convergence time only doubled. This is desirable in practical applications. Figure 7 shows the fitting results of different frequency bands. Since the fre spectrum for the neural network to approximate is not overcomplicated, the perfo of the PFF-DNN method was better than that of the PhaseDNN method. Figure 7 shows the fitting results of different frequency bands. Since the frequency spectrum for the neural network to approximate is not overcomplicated, the performance of the PFF-DNN method was better than that of the PhaseDNN method. Figure 7 shows the fitting results of different frequency bands. Since the frequency spectrum for the neural network to approximate is not overcomplicated, the performance of the PFF-DNN method was better than that of the PhaseDNN method. Figure 8 shows the influence of on the algorithm performance. As shown in Figure 8c,f, when = 11, both methods fit the signal well. However, when increased to 31, the PhaseDNN method began to show fitting errors. When = 51, the PhaseDNN method was hardly able to fit the signal effectively. In comparison, the PFF-DNN method was able to still accurately fit the signal. to 31, the PhaseDNN method began to show fitting errors. When ∆ = 51, the PhaseDNN method was hardly able to fit the signal effectively. In comparison, the PFF-DNN method was able to still accurately fit the signal. x FOR PEER REVIEW 9 of 22 Figure 9 shows how the number of updates N influences the algorithm performance. In the beginning, both algorithms were unable to fit the high-frequency components very well. The comparison between Figure 9b,e shows that the PFF-DNN method converged faster compared with the PhaseDNN method. The red curves in Figure 6 also confirm this point. Figure 9 shows how the number of updates N influences the algorithm performance. In the beginning, both algorithms were unable to fit the high-frequency components very well. The comparison between Figure 9b,e shows that the PFF-DNN method converged faster compared with the PhaseDNN method. The red curves in Figure 6 also confirm this point. ENSO Signal The signal determined by the following equation is often used to approximate the ENSO Signal The signal determined by the following equation is often used to approximate the ENSO data set : f (x) = 4.7 cos(2x/12) + 1.1 sin(2x/12) +0.2 cos(2x/1.7) + 2.7 sin(2x/1.7) +2.1 cos(2x/0.7) + 2.1 sin(2x/0.7) −0.5 This signal is more complicated than the one described by Equation. The shape of the signal and its corresponding frequency spectrum is shown in Figure 10. = + + + + + −, This signal is more complicated than the one described by Equation. The s of the signal and its corresponding frequency spectrum is shown in Figure 10. According to the trend of the solid red line and the red dashed line in Figure 11, it was shown that the convergence speed of the PFF-DNN method was about an order of magnitude larger. With the increase in ∆, the convergence time of the PFF-DNN method only doubled. Thus, the larger ∆, the more training time the PFF-DNN method saves as compared to the PhaseDNN method. Figures 12 and 13 visually show the convergence process of the two networks. This signal is more complicated than the one described by Equation. The shape of the signal and its corresponding frequency spectrum is shown in Figure 10. According to the trend of the solid red line and the red dashed line in Figure 11, it was shown that the convergence speed of the PFF-DNN method was about an order of magnitude larger. With the increase in, the convergence time of the PFF-DNN method only doubled. Thus, the larger, the more training time the PFF-DNN method saves as compared to the PhaseDNN method. Figures 12 and 13 visually show the convergence process of the two networks. Figure 11. The influence of on the convergence process. Figure 11. The influence of ∆ on the convergence process. Signal with Increasing Frequency Next, a signal with fast frequency changes was analyzed. This signal is often used in system identification, and its shape and frequency spectrum are shown in Figure 14. The explicit expression of the signal used here is: in which, T = 1, f 0 = 0.01, and f T = 50. Figure 14a shows that as x increases, the oscillation frequency of the signal increases sharply. Figure 14b shows that the amplitude and the oscillation frequency of the signal's spectrum gradually decrease. Signal with Increasing Frequency Next, a signal with fast frequency changes was analyzed. This signal is often used in system identification, and its shape and frequency spectrum are shown in Figure 14. The explicit expression of the signal used here is: in which, T = 1, f0 = 0.01, and fT = 50. Figure 14a shows that as x increases, the oscillation frequency of the signal increases sharply. Figure 14b shows that the amplitude and the oscillation frequency of the signal's spectrum gradually decrease. From the curve in Figure 15, it is shown that when = 11, the efficiency and accuracy of the PFF-DNN method were better than that of the PhaseDNN method. When increased, the convergence speed of both methods slowed down rapidly. Note that the convergence speed of the PFF-DNN network was relatively faster. Figures 16 and 17 visually compare the convergence process of the two methods. From the curve in Figure 15, it is shown that when ∆ = 11, the efficiency and accuracy of the PFF-DNN method were better than that of the PhaseDNN method. When ∆ increased, the convergence speed of both methods slowed down rapidly. Note that the convergence speed of the PFF-DNN network was relatively faster. Figures 16 and 17 visually compare the convergence process of the two methods. Next, a signal with fast frequency changes was analyzed. This signal is often used in system identification, and its shape and frequency spectrum are shown in Figure 14 The explicit expression of the signal used here is: (12 in which, T = 1, f0 = 0.01, and fT = 50. Figure 14a shows that as x increases, the oscillation frequency of the signal increases sharply. Figure 14b shows that the amplitude and the oscillation frequency of the signal's spectrum gradually decrease. From the curve in Figure 15, it is shown that when = 11, the efficiency and accu racy of the PFF-DNN method were better than that of the PhaseDNN method. When increased, the convergence speed of both methods slowed down rapidly. Note that the convergence speed of the PFF-DNN network was relatively faster. Figures 16 and 17 vis ually compare the convergence process of the two methods. Piecewise Signal The piecewise signal was used in to test the neural networks' performance. The shape and its corresponding frequency spectrum are shown in Figure 18. The signal is described by: Piecewise Signal The piecewise signal was used in to test the neural networks' performance. The shape and its corresponding frequency spectrum are shown in Figure 18. The signal is described by: Piecewise Signal The piecewise signal was used in to test the neural networks' performance. The shape and its corresponding frequency spectrum are shown in Figure 18. The signal is described by: The spectrum of this signal has several obvious spikes and many slight oscillations. Figure 19 shows that for such a signal, the accuracy of the proposed method was much less sensitive to changes in. Figures 20 and 21 visually compare the convergence process of the two networks. The spectrum of this signal has several obvious spikes and many slight oscillations. Figure 19 shows that for such a signal, the accuracy of the proposed method was much less sensitive to changes in ∆. Figures 20 and 21 visually compare the convergence process of the two networks. The spectrum of this signal has several obvious spikes and many slight osci Figure 19 shows that for such a signal, the accuracy of the proposed method wa less sensitive to changes in. Figures 20 and 21 visually compare the converge cess of the two networks. Square Wave Signal The following example was used to test the proposed method's approximation accuracy on discontinuous signals such as square waves. The shape and its corresponding frequency spectrum are shown in Figure 22. The signal is described by: Square Wave Signal The following example was used to test the proposed method's approximation accuracy on discontinuous signals such as square waves. The shape and its corresponding frequency spectrum are shown in Figure 22. The signal is described by: Square Wave Signal The following example was used to test the proposed method's approximation accuracy on discontinuous signals such as square waves. The shape and its corresponding frequency spectrum are shown in Figure 22. The signal is described by: The spectrum of this signal is composed of many irregular spikes. From Figure 23, it is shown that the increase in had a limited impact on the PFF-DNN method but had a significant impact on the PhaseDNN method. Figures 24 and 25 visually compare the convergence process of the two networks. The spectrum of this signal is composed of many irregular spikes. From Figure 23, it is shown that the increase in ∆ had a limited impact on the PFF-DNN method but had a significant impact on the PhaseDNN method. Figures 24 and 25 visually compare the convergence process of the two networks. Dynamic System The Mackey-Glass equation is a time-delayed differential equation first proposed to model white blood cell production. This equation has been used to test signal approximations in many related works. It is described by the solution of the following lagged differential equation: Dynamic System The Mackey-Glass equation is a time-delayed differential equation first proposed to model white blood cell production. This equation has been used to test signal approximations in many related works. It is described by the solution of the following lagged differential equation: Dynamic System The Mackey-Glass equation is a time-delayed differential equation first proposed to model white blood cell production. This equation has been used to test signal approximations in many related works. It is described by the solution of the following lagged differential equation:. The shape of the signal and its corresponding frequency spectrum is shown in Figure 26. The shape of the signal and its corresponding frequency spectrum is shown in Figure 26. As shown, this signal's frequency spectrum is more complicated. It is distributed irregularly within the interval of. Thus, this problem is relatively hard for both the PhaseDNN and PFF-DNN method. Figure 27 shows that when = 21 and = 41, the training advantage of the PFF-DNN over the PhaseDNN method was relatively obvious. However, when = 11 and = 51, the advantage was less obvious. Figures 28 and 29 show that in the middle of training, the convergence speed of the PFF-DNN method was also slightly better. As shown, this signal's frequency spectrum is more complicated. It is distributed irregularly within the interval of. Thus, this problem is relatively hard for both the PhaseDNN and PFF-DNN method. Figure 27 shows that when ∆ = 21 and ∆ = 41, the training advantage of the PFF-DNN over the PhaseDNN method was relatively obvious. However, when ∆ = 11 and ∆ = 51, the advantage was less obvious. Figures 28 and 29 show that in the middle of training, the convergence speed of the PFF-DNN method was also slightly better. The shape of the signal and its corresponding frequency spectrum is shown in Figure 26. As shown, this signal's frequency spectrum is more complicated. It is distributed ir regularly within the interval of. Thus, this problem is relatively hard for both the PhaseDNN and PFF-DNN method. Figure 27 shows that when = 21 and = 41, the training advantage of the PFF DNN over the PhaseDNN method was relatively obvious. However, when = 11 and = 51, the advantage was less obvious. Figures 28 and 29 show that in the middle o training, the convergence speed of the PFF-DNN method was also slightly better. From this example, it is observed that when the signal's frequency spectrum is relatively complicated, the performance gain of the PFF-DNN method was not significant. From this example, it is observed that when the signal's frequency spectrum is relatively complicated, the performance gain of the PFF-DNN method was not significant. From this example, it is observed that when the signal's frequency spectrum is relatively complicated, the performance gain of the PFF-DNN method was not significant. Therefore, we believe that the PFF-DNN and PhaseDNN methods may have their advantages for different applications. Further Discussions From the above experiments of fitting a large number of typical signals of different categories, it was observed that the proposed method had two advantages when the frequency domain distribution of the signal is smoother: the proposed method had obvious training efficiency advantages without losing accuracy; the proposed method was less sensitive to the choice of bandwidth. On the surface, this was due to the smoothness of the signal frequency domain distribution, but the deeper reason comes from the difference in complexity of the same segment of the signal in different domains. In the following, we explain why the PFF-DNN method performed better in the above examples from the perspective of the spectral bias of neural networks. To this end, Figure 30 shows how the PhaseDNN and PFF-DNN methods approximated the third frequency band when ∆ = 11 during the training process of the example in Section 3.2.3. Figure 30a,b shows that the PhaseDNN method essentially handled a continuous signal in the time domain, while the PFF-DNN method essentially interpolated a frequency domain discrete signal. Figure 30d,f shows the approximated results from the PFF-DNN method as a continuous function, which means that the PFF-DNN method interpolated the discrete spectrum with a smooth curve. Compared with Figure 30c,e, it is observed that the curve approximated by the PhaseDNN method oscillated more frequently in the time domain. Thus, it was more difficult for the neural network to learn the signals in the time domain by considering the spectral bias. This discussion may explain why the PFF-DNN method performed better than the PhaseDNN method for these examples. Therefore, we believe that the PFF-DNN and PhaseDNN methods may have their advantages for different applications. Further Discussions From the above experiments of fitting a large number of typical signals of different categories, it was observed that the proposed method had two advantages when the frequency domain distribution of the signal is smoother: the proposed method had obvious training efficiency advantages without losing accuracy; the proposed method was less sensitive to the choice of bandwidth. On the surface, this was due to the smoothness of the signal frequency domain distribution, but the deeper reason comes from the difference in complexity of the same segment of the signal in different domains. In the following, we explain why the PFF-DNN method performed better in the above examples from the perspective of the spectral bias of neural networks. To this end, Figure 30 shows how the PhaseDNN and PFF-DNN methods approximated the third frequency band when = 11 during the training process of the example in Section 3.2.3. Figure 30a,b shows that the PhaseDNN method essentially handled a continuous signal in the time domain, while the PFF-DNN method essentially interpolated a frequency domain discrete signal. Figure 30d,f shows the approximated results from the PFF-DNN method as a continuous function, which means that the PFF-DNN method interpolated the discrete spectrum with a smooth curve. Compared with Figure 30c,e, it is observed that the curve approximated by the PhaseDNN method oscillated more frequently in the time domain. Thus, it was more difficult for the neural network to learn the signals in the time domain by considering the spectral bias. This discussion may explain why the PFF-DNN method performed better than the PhaseDNN method for these examples. Conclusions Due to the existence of spectral bias, problems occur when a neural network is used for the approximation of broadband signals. That is, the high-frequency parts are hard to fit. For this reason, people often use frequency-selective filters to extract signals in different frequency bands and then use different neural networks to fit them. However, we found in a large number of numerical experiments that this method is inefficient for fitting signals with broad and smooth spectrums. For this reason, this paper proposed a novel alternative method based on parallel fitting in the frequency domain by utilizing frequency domain analysis of broadband signals and the spectral bias nature of neural networks. A substantial improvement in efficiency was observed in extensive numerical experiments. Thus, the PFF-DNN method is expected to become an alternative solution for broadband signal fitting. In the future, we will further investigate how to determine whether the same signal is easier to fit by a neural network in the time domain or frequency domain and extend our findings to more complex representation spaces. Funding: This research was funded by the National Natural Science Foundation of China, grant numbers 61805185, 11802225, and 51805397. |
In a possible first in the country, HarperCollins Publishers India (HCI) will be granting "pawternity leave" to employees who are adopting a pet. Starting this year, they will be entitled to a week's — or 5 working days' — paid leave if they have just adopted a cat, dog or other type of pet they fancy.
Such a policy may be unheard of in India, but a few companies in the West have been offering it to their employees to allow them time to bond with their new pet. The idea, obviously inspired by maternity and paternity leaves, is meant to encourage responsible adoption of pets. India recently revised the terms and privileges of maternity leave allotted to women in the workforce. HCI takes a step further.
"At HarperCollins we want the very best of work-life balance for our colleagues, and that includes being mindful about their family needs," Ananth Padmanabhan, Chief Executive Officer of HCI, told HuffPost India. "Pet children need as much attention [as human children], if not more. We don't want colleagues to worry about the number of leaves they have before deciding to start a family."
In addition to pawternity leave, HCI will allow employees who find it difficult to leave their pets at home to bring them to office, which is based in Noida. The animals will be kept in a designated area for the day.
The policy aims at ensuring a healthier work-life balance for employees who might need time off to tend to their pets. The initiative is aimed at transforming HCI into an employee-friendly company, with a human resources (HR) department that is progressive in its outlook.
"We are always thinking of ways to make HarperCollins the best place to work for, in every respect. In fact, in the UK, we just won an award for diversity in the work place," said Manjula Sreekumaran, head of HR at HCI.
"It felt great not just to know that the concept of pawternity leave exists, but also that HarperCollins is implementing it. I became the first employee to experience it, and it allowed me to be there for Luna, when we got her, without feeling torn or worried about work. It was such a comfort," said Subhashree Das, digital marketing manager at HCI, who recently adopted a puppy.
HCI, a wholly owned subsidiary of HarperCollins Worldwide, is the second largest trade publisher in India with a 25-year-old presence in the market. It employs more than 200 people in its Noida office.
Also on HuffPost |
<reponame>VictorKayk/JavaScript<filename>node/courses/course02/mod-03/api/src/modules/cars/useCases/specification/importSpecificationControl/ImportSpecificationControl.ts
import { Request, Response } from "express";
import ImportSpecificationUseCase from "./ImportSpecificationUseCase";
export default class ImportSpecificationControl {
constructor(private importSpecificationUseCase: ImportSpecificationUseCase) {}
async handle(req: Request, res: Response) {
const { file } = req;
const msg = await this.importSpecificationUseCase.execute(file);
return res.json(await Promise.all(msg));
}
} |
/**
* Constructor with a log stream.
*/
Exception::Exception(LogStream* ls,
const char* fileName, const int lineNumber, bool doReport, bool printHelp)
{
initialize(ls->getMessage(), false, printHelp);
} |
#include <iostream>
void swap_in_place_diff(int& a, int& b) {
a -= b;
b += a;
a = b - a;
return;
}
// benefit of this solution is that it workd for more data type than just integers
// xor returns 1 if x != y, otherwise 0
void swap_in_place_xor(int& a, int& b) {
a ^= b; // bit in a are set to 1 if those bits are different for a and b, otherwise 0
b ^= a; // b is equal to old value of a
a ^= b; // a is equal to old value of b
return;
}
/**
* Number Swapper: Write a function to swap two numbers in place (that is, without
* temporary variables)
*/
int main() {
int a(5);
int b(2);
std::cout << "Before swap: " << "a = " << a << ", b = " << b << '\n';
std::cout << "Enter 1 to swap in place using diff or any other number to swap using xor.\n";
int method;
std::cin >> method;
if(method == 1) {
swap_in_place_diff(a, b);
} else {
swap_in_place_xor(a, b);
}
std::cout << "After swap: " << "a = " << a << ", b = " << b << '\n';
} |
<reponame>xu5343/ffmpegtoolkit_CentOS7
/*
* GPAC Multimedia Framework
*
* Authors: <NAME>, <NAME>
* Copyright (c) Telecom ParisTech 2004-2012
* All rights reserved
*
* This file is part of GPAC / SVG Loader module
*
* GPAC 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, or (at your option)
* any later version.
*
* GPAC 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 this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/base_coding.h>
#include <gpac/color.h>
#include <gpac/events.h>
#include <gpac/nodes_svg.h>
#ifndef GPAC_DISABLE_SVG
#include <gpac/internal/scenegraph_dev.h>
#define DUMP_COORDINATES 1
static const struct dom_event_def {
GF_EventType event;
const char *name;
GF_DOMEventCategory category;
} defined_dom_events [] =
{
{ GF_EVENT_ABORT, "abort", GF_DOM_EVENT_DOM },
{ GF_EVENT_ERROR, "error", GF_DOM_EVENT_DOM },
{ GF_EVENT_LOAD, "load", GF_DOM_EVENT_DOM },
{ GF_EVENT_UNLOAD, "unload", GF_DOM_EVENT_DOM },
/*focus - we differentiate from UI/key events to avoid browing focus if no listener is on place*/
{ GF_EVENT_FOCUSIN, "DOMFocusIn", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_FOCUSIN, "focusin", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_FOCUSOUT, "DOMFocusOut", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_FOCUSOUT, "focusout", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_CHANGE, "change", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_FOCUS, "focus", GF_DOM_EVENT_FOCUS },
{ GF_EVENT_BLUR, "blur", GF_DOM_EVENT_FOCUS },
/*key events*/
{ GF_EVENT_KEYDOWN, "keydown", GF_DOM_EVENT_KEY },
{ GF_EVENT_KEYDOWN, "accesskey", GF_DOM_EVENT_KEY },
{ GF_EVENT_KEYDOWN, "keypress", GF_DOM_EVENT_KEY },
{ GF_EVENT_KEYUP, "keyup", GF_DOM_EVENT_KEY },
{ GF_EVENT_LONGKEYPRESS, "longaccesskey", GF_DOM_EVENT_KEY },
{ GF_EVENT_CLICK, "click", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_DBLCLICK, "dblclick", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEDOWN, "mousedown", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEMOVE, "mousemove", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEOUT, "mouseout", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEOVER, "mouseover", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEUP, "mouseup", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEWHEEL, "wheel", GF_DOM_EVENT_MOUSE },
{ GF_EVENT_MOUSEWHEEL, "SVGMousewheel", GF_DOM_EVENT_MOUSE },
/*activate is not a basic DOM but a MOUSE and KEY event*/
{ GF_EVENT_ACTIVATE, "activate", GF_DOM_EVENT_MOUSE | GF_DOM_EVENT_KEY },
{ GF_EVENT_ACTIVATE, "DOMActivate", GF_DOM_EVENT_MOUSE | GF_DOM_EVENT_KEY },
/*text events*/
{ GF_EVENT_TEXTINPUT, "textInput", GF_DOM_EVENT_TEXT },
{ GF_EVENT_TEXTSELECT, "select", GF_DOM_EVENT_TEXT },
/*SMIL events*/
{ GF_EVENT_BEGIN, "begin", GF_DOM_EVENT_FAKE },
{ GF_EVENT_BEGIN_EVENT, "beginEvent", GF_DOM_EVENT_SMIL },
{ GF_EVENT_END, "end", GF_DOM_EVENT_FAKE },
{ GF_EVENT_END_EVENT, "endEvent", GF_DOM_EVENT_SMIL },
{ GF_EVENT_REPEAT, "repeat", GF_DOM_EVENT_FAKE },
{ GF_EVENT_REPEAT_EVENT, "repeatEvent", GF_DOM_EVENT_SMIL },
/*all SVG/HTML/... UI events*/
{ GF_EVENT_RESIZE, "resize", GF_DOM_EVENT_UI },
{ GF_EVENT_SCROLL, "scroll", GF_DOM_EVENT_UI },
{ GF_EVENT_ZOOM, "zoom", GF_DOM_EVENT_UI },
{ GF_EVENT_LOAD, "SVGLoad", GF_DOM_EVENT_DOM },
{ GF_EVENT_RESIZE, "SVGResize", GF_DOM_EVENT_UI },
{ GF_EVENT_SCROLL, "SVGScroll", GF_DOM_EVENT_UI },
{ GF_EVENT_ZOOM, "SVGZoom", GF_DOM_EVENT_UI },
/*mutation events and DCCI*/
{ GF_EVENT_TREE_MODIFIED, "DOMSubtreeModified", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_NODE_INSERTED, "DOMNodeInserted", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_NODE_REMOVED, "DOMNodeRemoved", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_NODE_REMOVED_DOC, "DOMNodeRemovedFromDocument", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_NODE_INSERTED_DOC, "DOMNodeInsertedIntoDocument", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_ATTR_MODIFIED, "DOMAttrModified", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_CHAR_DATA_MODIFIED, "DOMCharacterDataModified", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_NODE_NAME_CHANGED, "DOMElementNameChanged", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_ATTR_NAME_CHANGED, "DOMAttributeNameChanged", GF_DOM_EVENT_MUTATION },
{ GF_EVENT_DCCI_PROP_CHANGE, "DCCI-prop-change", GF_DOM_EVENT_MUTATION },
/*LASeR events - some events are attached to other categorues*/
{ GF_EVENT_ACTIVATED, "activatedEvent", GF_DOM_EVENT_LASER },
{ GF_EVENT_DEACTIVATED, "deactivatedEvent", GF_DOM_EVENT_LASER },
{ GF_EVENT_EXECUTION_TIME, "executionTime", GF_DOM_EVENT_FAKE },
{ GF_EVENT_PAUSE, "pause", GF_DOM_EVENT_SMIL },
{ GF_EVENT_PAUSED_EVENT, "pausedEvent", GF_DOM_EVENT_SMIL },
{ GF_EVENT_PLAY, "play", GF_DOM_EVENT_SMIL },
{ GF_EVENT_RESUME_EVENT, "resumedEvent", GF_DOM_EVENT_SMIL },
{ GF_EVENT_REPEAT_KEY, "repeatKey", GF_DOM_EVENT_KEY },
{ GF_EVENT_SHORT_ACCESSKEY, "shortAccessKey", GF_DOM_EVENT_KEY },
/*LASeR unofficial events*/
{ GF_EVENT_BATTERY, "battery", GF_DOM_EVENT_LASER },
{ GF_EVENT_CPU, "cpu", GF_DOM_EVENT_LASER },
{ GF_EVENT_MEDIA_SETUP_BEGIN, "setupbegin", GF_DOM_EVENT_MEDIA},
{ GF_EVENT_MEDIA_SETUP_DONE, "setupdone", GF_DOM_EVENT_MEDIA},
{ GF_EVENT_MEDIA_LOAD_START, "loadstart", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_LOAD_DONE, "loaddone", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_PROGRESS, "progress", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_SUSPEND, "suspend", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_ABORT, "abort", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_ERROR, "error", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_EMPTIED, "emptied", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_STALLED, "stalled", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_LOADED_METADATA, "loadedmetadata", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_LODADED_DATA, "loadeddata", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_CANPLAY, "canplay", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_CANPLAYTHROUGH, "canplaythrough", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_PLAYING, "playing", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_WAITING, "waiting", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_SEEKING, "seeking", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_SEEKED, "seeked", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_ENDED, "ended", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_DURATION_CHANGED, "durationchanged", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_TIME_UPDATE, "timeupdate", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_PLAY, "play", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_PAUSE, "pause", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_RATECHANGE, "ratechange", GF_DOM_EVENT_MEDIA },
{ GF_EVENT_MEDIA_VOLUME_CHANGED, "volumechange", GF_DOM_EVENT_MEDIA },
/* Media Source Events */
{ GF_EVENT_HTML_MSE_SOURCE_OPEN, "sourceopen", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_SOURCE_ENDED, "sourceended", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_SOURCE_CLOSE, "sourceclose", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_UPDATE_START, "updatestart", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_UPDATE, "update", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_UPDATE_END, "updateend", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_UPDATE_ERROR, "error", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_UPDATE_ABORT, "abort", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_ADD_SOURCE_BUFFER, "addsourcebuffer", GF_DOM_EVENT_MEDIASOURCE },
{ GF_EVENT_HTML_MSE_REMOVE_SOURCE_BUFFER, "removesourcebuffer", GF_DOM_EVENT_MEDIASOURCE },
/*GPAC internals*/
{ GF_EVENT_SCENE_ATTACHED, "gpac_scene_attached", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SCENE_SIZE, "gpac_scene_size", GF_DOM_EVENT_GPAC},
{ GF_EVENT_VP_RESIZE, "gpac_vp_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_ADDON_DETECTED, "gpac_addon_found", GF_DOM_EVENT_GPAC},
{ GF_EVENT_MAIN_ADDON_STATE, "gpac_main_addon_state", GF_DOM_EVENT_GPAC},
{ GF_EVENT_STREAMLIST, "gpac_streamlist_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_TIMESHIFT_DEPTH, "gpac_timeshift_depth_changed", GF_DOM_EVENT_GPAC},
#if 0
{ GF_EVENT_DBLCLICK, "gpac_dbl_click", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SIZE, "gpac_size_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SCENE_SIZE, "gpac_scene_size", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SHOWHIDE, "gpac_show_hide", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SET_CURSOR, "gpac_set_cursor", GF_DOM_EVENT_GPAC},
{ GF_EVENT_SET_CAPTION, "gpac_set_caption", GF_DOM_EVENT_GPAC},
{ GF_EVENT_MOVE, "gpac_move", GF_DOM_EVENT_GPAC},
{ GF_EVENT_REFRESH, "gpac_move", GF_DOM_EVENT_GPAC},
{ GF_EVENT_QUIT, "gpac_quit", GF_DOM_EVENT_GPAC},
{ GF_EVENT_PASTE_TEXT, "gpac_paste", GF_DOM_EVENT_GPAC},
{ GF_EVENT_COPY_TEXT, "gpac_copy", GF_DOM_EVENT_GPAC},
{ GF_EVENT_CONNECT, "gpac_on_connect", GF_DOM_EVENT_GPAC},
{ GF_EVENT_DURATION, "gpac_on_duration", GF_DOM_EVENT_GPAC},
{ GF_EVENT_EOS, "gpac_eos", GF_DOM_EVENT_GPAC},
{ GF_EVENT_AUTHORIZATION, "gpac_authorization", GF_DOM_EVENT_GPAC},
{ GF_EVENT_NAVIGATE, "gpac_navigate", GF_DOM_EVENT_GPAC},
{ GF_EVENT_NAVIGATE_INFO, "gpac_navigate_info", GF_DOM_EVENT_GPAC},
{ GF_EVENT_MESSAGE, "gpac_on_message", GF_DOM_EVENT_GPAC},
{ GF_EVENT_PROGRESS, "gpac_on_progress", GF_DOM_EVENT_GPAC},
{ GF_EVENT_VIEWPOINTS, "gpac_viewpoints_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_STREAMLIST, "gpac_streamlist_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_METADATA, "gpac_metadata_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_MIGRATE, "gpac_session_migrate", GF_DOM_EVENT_GPAC},
{ GF_EVENT_DISCONNECT, "gpac_request_disconnect", GF_DOM_EVENT_GPAC},
{ GF_EVENT_RESOLUTION, "gpac_resolution_changed", GF_DOM_EVENT_GPAC},
{ GF_EVENT_DROPFILE, "gpac_dropfile", GF_DOM_EVENT_GPAC},
{ GF_EVENT_TEXT_EDITING_START, "gpac_textedit_start", GF_DOM_EVENT_GPAC},
{ GF_EVENT_TEXT_EDITING_END, "gpac_textedit_end", GF_DOM_EVENT_GPAC},
{ GF_EVENT_QUALITY_SWITCHED, "gpac_quality_switch", GF_DOM_EVENT_GPAC},
{ GF_EVENT_TIMESHIFT_OVERFLOW, "gpac_timeshift_overflow", GF_DOM_EVENT_GPAC},
{ GF_EVENT_TIMESHIFT_UPDATE, "gpac_timeshift_update", GF_DOM_EVENT_GPAC}
#endif
};
GF_EXPORT
GF_EventType gf_dom_event_type_by_name(const char *name)
{
u32 i, count;
count = sizeof(defined_dom_events) / sizeof(struct dom_event_def);
if (!name) return GF_EVENT_UNKNOWN;
if ((name[0]=='o') && (name[1]=='n')) name += 2;
for (i=0; i<count; i++) {
if (!strcmp(name, defined_dom_events[i].name))
return defined_dom_events[i].event;
}
return GF_EVENT_UNKNOWN;
}
GF_EXPORT
const char *gf_dom_event_get_name(GF_EventType type)
{
u32 i, count;
count = sizeof(defined_dom_events) / sizeof(struct dom_event_def);
for (i=0; i<count; i++) {
if (defined_dom_events[i].event == type)
return defined_dom_events[i].name;
}
return "unknown";
}
GF_DOMEventCategory gf_dom_event_get_category(GF_EventType type)
{
u32 i, count;
count = sizeof(defined_dom_events) / sizeof(struct dom_event_def);
for (i=0; i<count; i++) {
if (defined_dom_events[i].event == type)
return defined_dom_events[i].category;
}
return GF_DOM_EVENT_UNKNOWN_CATEGORY;
}
static const struct predef_keyid {
GF_KeyCode key_code;
const char *name;
} predefined_key_identifiers[] =
{
{ GF_KEY_ACCEPT, "Accept" },
{ GF_KEY_AGAIN, "Again" },
{ GF_KEY_ALLCANDIDATES, "AllCandidates" },
{ GF_KEY_ALPHANUM, "Alphanumeric" },
{ GF_KEY_ALT, "Alt" },
{ GF_KEY_ALTGRAPH, "AltGraph" },
{ GF_KEY_APPS, "Apps" },
{ GF_KEY_ATTN, "Attn" },
{ GF_KEY_BROWSERBACK, "BrowserBack" },
{ GF_KEY_BROWSERFAVORITES, "BrowserFavorites" },
{ GF_KEY_BROWSERFORWARD, "BrowserForward" },
{ GF_KEY_BROWSERHOME, "BrowserHome" },
{ GF_KEY_BROWSERREFRESH, "BrowserRefresh" },
{ GF_KEY_BROWSERSEARCH, "BrowserSearch" },
{ GF_KEY_BROWSERSTOP, "BrowserStop" },
{ GF_KEY_CAPSLOCK, "CapsLock" },
{ GF_KEY_CLEAR, "Clear" },
{ GF_KEY_CODEINPUT, "CodeInput" },
{ GF_KEY_COMPOSE, "Compose" },
{ GF_KEY_CONTROL, "Control" },
{ GF_KEY_CRSEL, "Crsel" },
{ GF_KEY_CONVERT, "Convert" },
{ GF_KEY_COPY, "Copy" },
{ GF_KEY_CUT, "Cut" },
{ GF_KEY_DOWN, "Down" },
{ GF_KEY_END, "End" },
{ GF_KEY_ENTER, "Enter" },
{ GF_KEY_ERASEEOF, "EraseEof" },
{ GF_KEY_EXECUTE, "Execute" },
{ GF_KEY_EXSEL, "Exsel" },
{ GF_KEY_F1, "F1" },
{ GF_KEY_F2, "F2" },
{ GF_KEY_F3, "F3" },
{ GF_KEY_F4, "F4" },
{ GF_KEY_F5, "F5" },
{ GF_KEY_F6, "F6" },
{ GF_KEY_F7, "F7" },
{ GF_KEY_F8, "F8" },
{ GF_KEY_F9, "F9" },
{ GF_KEY_F10, "F10" },
{ GF_KEY_F11, "F11" },
{ GF_KEY_F12, "F12" },
{ GF_KEY_F13, "F13" },
{ GF_KEY_F14, "F14" },
{ GF_KEY_F15, "F15" },
{ GF_KEY_F16, "F16" },
{ GF_KEY_F17, "F17" },
{ GF_KEY_F18, "F18" },
{ GF_KEY_F19, "F19" },
{ GF_KEY_F20, "F20" },
{ GF_KEY_F21, "F21" },
{ GF_KEY_F22, "F22" },
{ GF_KEY_F23, "F23" },
{ GF_KEY_F24, "F24" },
{ GF_KEY_FINALMODE, "FinalMode" },
{ GF_KEY_FIND, "Find" },
{ GF_KEY_FULLWIDTH, "FullWidth" },
{ GF_KEY_HALFWIDTH, "HalfWidth" },
{ GF_KEY_HANGULMODE, "HangulMode" },
{ GF_KEY_HANJAMODE, "HanjaMode" },
{ GF_KEY_HELP, "Help" },
{ GF_KEY_HIRAGANA, "Hiragana" },
{ GF_KEY_HOME, "Home" },
{ GF_KEY_INSERT, "Insert" },
{ GF_KEY_JAPANESEHIRAGANA, "JapaneseHiragana" },
{ GF_KEY_JAPANESEKATAKANA, "JapaneseKatakana" },
{ GF_KEY_JAPANESEROMAJI, "JapaneseRomaji" },
{ GF_KEY_JUNJAMODE, "JunjaMode" },
{ GF_KEY_KANAMODE, "KanaMode" },
{ GF_KEY_KANJIMODE, "KanjiMode" },
{ GF_KEY_KATAKANA, "Katakana" },
{ GF_KEY_LAUNCHAPPLICATION1, "LaunchApplication1" },
{ GF_KEY_LAUNCHAPPLICATION2, "LaunchApplication2" },
{ GF_KEY_LAUNCHMAIL, "LaunchMail" },
{ GF_KEY_LEFT, "Left" },
{ GF_KEY_META, "Meta" },
{ GF_KEY_MEDIANEXTTRACK, "MediaNextTrack" },
{ GF_KEY_MEDIAPLAYPAUSE, "MediaPlayPause" },
{ GF_KEY_MEDIAPREVIOUSTRACK, "MediaPreviousTrack" },
{ GF_KEY_MEDIASTOP, "MediaStop" },
{ GF_KEY_MODECHANGE, "ModeChange" },
{ GF_KEY_NONCONVERT, "Nonconvert" },
{ GF_KEY_NUMLOCK, "NumLock" },
{ GF_KEY_PAGEDOWN, "PageDown" },
{ GF_KEY_PAGEUP, "PageUp" },
{ GF_KEY_PASTE, "Paste" },
{ GF_KEY_PAUSE, "Pause" },
{ GF_KEY_PLAY, "Play" },
{ GF_KEY_PREVIOUSCANDIDATE, "PreviousCandidate" },
{ GF_KEY_PRINTSCREEN, "PrintScreen" },
{ GF_KEY_PROCESS, "Process" },
{ GF_KEY_PROPS, "Props" },
{ GF_KEY_RIGHT, "Right" },
{ GF_KEY_ROMANCHARACTERS, "RomanCharacters" },
{ GF_KEY_SCROLL, "Scroll" },
{ GF_KEY_SELECT, "Select" },
{ GF_KEY_SELECTMEDIA, "SelectMedia" },
{ GF_KEY_SHIFT, "Shift" },
{ GF_KEY_STOP, "Stop" },
{ GF_KEY_UP, "Up" },
{ GF_KEY_UNDO, "Undo" },
{ GF_KEY_VOLUMEDOWN, "VolumeDown" },
{ GF_KEY_VOLUMEMUTE, "VolumeMute" },
{ GF_KEY_VOLUMEUP, "VolumeUp" },
{ GF_KEY_WIN, "Win" },
{ GF_KEY_ZOOM, "Zoom" },
{ GF_KEY_BACKSPACE, "U+0008" },
{ GF_KEY_TAB, "U+0009" },
{ GF_KEY_CANCEL, "U+0018" },
{ GF_KEY_ESCAPE, "U+001B" },
{ GF_KEY_SPACE, "U+0020" },
{ GF_KEY_EXCLAMATION, "U+0021" },
{ GF_KEY_QUOTATION, "U+0022" },
{ GF_KEY_NUMBER, "U+0023" },
{ GF_KEY_DOLLAR, "U+0024" },
{ GF_KEY_AMPERSAND, "U+0026" },
{ GF_KEY_APOSTROPHE, "U+0027" },
{ GF_KEY_LEFTPARENTHESIS, "U+0028" },
{ GF_KEY_RIGHTPARENTHESIS, "U+0029" },
{ GF_KEY_STAR, "U+002A" },
{ GF_KEY_PLUS, "U+002B" },
{ GF_KEY_COMMA, "U+002C" },
{ GF_KEY_HYPHEN, "U+002D" },
{ GF_KEY_FULLSTOP, "U+002E" },
{ GF_KEY_SLASH, "U+002F" },
{ GF_KEY_0, "U+0030" },
{ GF_KEY_1, "U+0031" },
{ GF_KEY_2, "U+0032" },
{ GF_KEY_3, "U+0033" },
{ GF_KEY_4, "U+0034" },
{ GF_KEY_5, "U+0035" },
{ GF_KEY_6, "U+0036" },
{ GF_KEY_7, "U+0037" },
{ GF_KEY_8, "U+0038" },
{ GF_KEY_9, "U+0039" },
{ GF_KEY_COLON, "U+003A" },
{ GF_KEY_SEMICOLON, "U+003B" },
{ GF_KEY_LESSTHAN, "U+003C" },
{ GF_KEY_EQUALS, "U+003D" },
{ GF_KEY_GREATERTHAN, "U+003E" },
{ GF_KEY_QUESTION, "U+003F" },
{ GF_KEY_AT, "U+0040" },
{ GF_KEY_A, "U+0041" },
{ GF_KEY_B, "U+0042" },
{ GF_KEY_C, "U+0043" },
{ GF_KEY_D, "U+0044" },
{ GF_KEY_E, "U+0045" },
{ GF_KEY_F, "U+0046" },
{ GF_KEY_G, "U+0047" },
{ GF_KEY_H, "U+0048" },
{ GF_KEY_I, "U+0049" },
{ GF_KEY_J, "U+004A" },
{ GF_KEY_K, "U+004B" },
{ GF_KEY_L, "U+004C" },
{ GF_KEY_M, "U+004D" },
{ GF_KEY_N, "U+004E" },
{ GF_KEY_O, "U+004F" },
{ GF_KEY_P, "U+0050" },
{ GF_KEY_Q, "U+0051" },
{ GF_KEY_R, "U+0052" },
{ GF_KEY_S, "U+0053" },
{ GF_KEY_T, "U+0054" },
{ GF_KEY_U, "U+0055" },
{ GF_KEY_V, "U+0056" },
{ GF_KEY_W, "U+0057" },
{ GF_KEY_X, "U+0058" },
{ GF_KEY_Y, "U+0059" },
{ GF_KEY_Z, "U+005A" },
{ GF_KEY_LEFTSQUAREBRACKET, "U+005B" },
{ GF_KEY_BACKSLASH, "U+005C" },
{ GF_KEY_RIGHTSQUAREBRACKET, "U+005D" },
{ GF_KEY_CIRCUM, "U+005E" },
{ GF_KEY_UNDERSCORE, "U+005F" },
{ GF_KEY_GRAVEACCENT, "U+0060" },
{ GF_KEY_LEFTCURLYBRACKET, "U+007B" },
{ GF_KEY_PIPE, "U+007C" },
{ GF_KEY_RIGHTCURLYBRACKET, "U+007D" },
{ GF_KEY_DEL, "U+007F" },
{ GF_KEY_INVERTEXCLAMATION, "U+00A1" },
{ GF_KEY_DEADGRAVE, "U+0300" },
{ GF_KEY_DEADEACUTE, "U+0301" },
{ GF_KEY_DEADCIRCUM, "U+0302" },
{ GF_KEY_DEADTILDE, "U+0303" },
{ GF_KEY_DEADMACRON, "U+0304" },
{ GF_KEY_DEADBREVE, "U+0306" },
{ GF_KEY_DEADABOVEDOT, "U+0307" },
{ GF_KEY_DEADDIARESIS, "U+0308" },
{ GF_KEY_DEADRINGABOVE, "U+030A" },
{ GF_KEY_DEADDOUBLEACUTE, "U+030B" },
{ GF_KEY_DEADCARON, "U+030C" },
{ GF_KEY_DEADCEDILLA, "U+0327" },
{ GF_KEY_DEADOGONEK, "U+0328" },
{ GF_KEY_DEADIOTA, "U+0345" },
{ GF_KEY_EURO, "U+20AC" },
{ GF_KEY_DEADVOICESOUND, "U+3099" },
{ GF_KEY_DEADSEMIVOICESOUND, "U+309A" },
{ GF_KEY_CHANNELUP, "ChannelUp" },
{ GF_KEY_CHANNELDOWN, "ChannelDown" },
{ GF_KEY_TEXT, "Text" },
{ GF_KEY_INFO, "Info" },
{ GF_KEY_EPG, "EPG" },
{ GF_KEY_RECORD, "Record" },
{ GF_KEY_BEGINPAGE, "BeginPage" }
};
GF_EXPORT
const char *gf_dom_get_key_name(GF_KeyCode key_identifier)
{
u32 count = sizeof(predefined_key_identifiers) / sizeof(struct predef_keyid);
if (!key_identifier || count<= (u32) key_identifier) return "Unknown";
return predefined_key_identifiers[key_identifier-1].name;
}
GF_EXPORT
GF_KeyCode gf_dom_get_key_type(char *key_name)
{
if (strlen(key_name) == 1) {
char c[2];
c[0] = key_name[0];
c[1] = 0;
strupr(c);
if (c[0] >= 'A' && c[0] <= 'Z')
return (GF_KEY_A + (c[0] - 'A') );
if (c[0] >= '0' && c[0] <= '9')
return ( GF_KEY_0 + (c[0] - '0') );
switch ((u8) c[0]) {
case '@':
return GF_KEY_AT;
case '*':
return GF_KEY_STAR;
case '#':
return GF_KEY_NUMBER;
case ' ':
return GF_KEY_SPACE;
case '!':
return GF_KEY_EXCLAMATION;
case '"':
return GF_KEY_QUOTATION;
case '$':
return GF_KEY_DOLLAR;
case '&':
return GF_KEY_AMPERSAND;
case '\'':
return GF_KEY_APOSTROPHE;
case '(':
return GF_KEY_LEFTPARENTHESIS;
case ')':
return GF_KEY_RIGHTPARENTHESIS;
case '+':
return GF_KEY_PLUS;
case ',':
return GF_KEY_COMMA;
case '-':
return GF_KEY_HYPHEN;
case '.':
return GF_KEY_FULLSTOP;
case '/':
return GF_KEY_SLASH;
case ':':
return GF_KEY_COLON;
case ';':
return GF_KEY_SEMICOLON;
case '<':
return GF_KEY_LESSTHAN;
case '=':
return GF_KEY_EQUALS;
case '>':
return GF_KEY_GREATERTHAN;
case '?':
return GF_KEY_QUESTION;
case '[':
return GF_KEY_LEFTSQUAREBRACKET;
case '\\':
return GF_KEY_BACKSLASH;
case ']':
return GF_KEY_RIGHTSQUAREBRACKET;
case '^':
return GF_KEY_CIRCUM;
case '_':
return GF_KEY_UNDERSCORE;
case '`':
return GF_KEY_GRAVEACCENT;
case '{':
return GF_KEY_LEFTCURLYBRACKET;
case '|':
return GF_KEY_PIPE;
case '}':
return GF_KEY_RIGHTCURLYBRACKET;
case 0xA1:
return GF_KEY_INVERTEXCLAMATION;
default:
return GF_KEY_UNIDENTIFIED;
}
} else {
u32 i, count;
count = sizeof(predefined_key_identifiers) / sizeof(struct predef_keyid);
for (i=0; i<count; i++) {
if (!stricmp(key_name, predefined_key_identifiers[i].name)) {
return predefined_key_identifiers[i].key_code;
}
}
return GF_KEY_UNIDENTIFIED;
}
}
/* Basic SVG datatype parsing functions */
/* Basic SVG datatype parsing functions */
static const struct sys_col {
const char *name;
u8 type;
} system_colors[] =
{
{"ActiveBorder", SVG_COLOR_ACTIVE_BORDER},
{"ActiveCaption", SVG_COLOR_ACTIVE_CAPTION},
{"AppWorkspace", SVG_COLOR_APP_WORKSPACE},
{"Background", SVG_COLOR_BACKGROUND},
{"ButtonFace", SVG_COLOR_BUTTON_FACE},
{"ButtonHighlight", SVG_COLOR_BUTTON_HIGHLIGHT},
{"ButtonShadow", SVG_COLOR_BUTTON_SHADOW},
{"ButtonText", SVG_COLOR_BUTTON_TEXT},
{"CaptionText", SVG_COLOR_CAPTION_TEXT},
{"GrayText", SVG_COLOR_GRAY_TEXT},
{"Highlight", SVG_COLOR_HIGHLIGHT},
{"HighlightText", SVG_COLOR_HIGHLIGHT_TEXT},
{"InactiveBorder", SVG_COLOR_INACTIVE_BORDER},
{"InactiveCaption", SVG_COLOR_INACTIVE_CAPTION},
{"InactiveCaptionText", SVG_COLOR_INACTIVE_CAPTION_TEXT},
{"InfoBackground", SVG_COLOR_INFO_BACKGROUND},
{"InfoText", SVG_COLOR_INFO_TEXT},
{"Menu", SVG_COLOR_MENU},
{"MenuText", SVG_COLOR_MENU_TEXT},
{"Scrollbar", SVG_COLOR_SCROLLBAR},
{"ThreeDDarkShadow", SVG_COLOR_3D_DARK_SHADOW},
{"ThreeDFace", SVG_COLOR_3D_FACE},
{"ThreeDHighlight", SVG_COLOR_3D_HIGHLIGHT},
{"ThreeDLightShadow", SVG_COLOR_3D_LIGHT_SHADOW},
{"ThreeDShadow", SVG_COLOR_3D_SHADOW},
{"Window", SVG_COLOR_WINDOW},
{"WindowFrame", SVG_COLOR_WINDOW_FRAME},
{"WindowText", SVG_COLOR_WINDOW_TEXT},
};
/* parses an color from a named color HTML or CSS 2 */
static void svg_parse_named_color(SVG_Color *col, char *attribute_content)
{
u32 i, count, val;
val = gf_color_parse(attribute_content);
if (val) {
col->red = INT2FIX((val>>16) & 0xFF) / 255;
col->green = INT2FIX((val>>8) & 0xFF) / 255;
col->blue = INT2FIX(val & 0xFF) / 255;
col->type = SVG_COLOR_RGBCOLOR;
return;
}
count = sizeof(system_colors) / sizeof(struct sys_col);
for (i=0; i<count; i++) {
if (!strcmp(attribute_content, system_colors[i].name)) {
col->type = system_colors[i].type;
return;
}
}
}
const char *gf_svg_get_system_paint_server_name(u32 paint_type)
{
u32 i, count;
count = sizeof(system_colors) / sizeof(struct sys_col);
for (i=0; i<count; i++) {
if (paint_type == system_colors[i].type) return system_colors[i].name;
}
return "undefined";
}
u32 gf_svg_get_system_paint_server_type(const char *name)
{
u32 i, count;
count = sizeof(system_colors) / sizeof(struct sys_col);
for (i=0; i<count; i++) {
if (!strcmp(name, system_colors[i].name)) return system_colors[i].type;
}
return 0;
}
/* Reads an SVG Color
either #RRGGBB, #RGB, rgb(r,g,b) in [0,255] , colorname, or 'r g b' in [0,1]
ignores any space, comma, semi-column before and any space after
TODO:
transform the char into char and duplicate the input, instead of modifying it
be more robust to errors in color description ex rgb(0 0 0)
*/
static void svg_parse_color(SVG_Color *col, char *attribute_content)
{
char *str = attribute_content;
while (str[strlen(attribute_content)-1] == ' ') str[strlen(attribute_content)-1] = 0;
while (*str != 0 && (*str == ' ' || *str == ',' || *str == ';')) str++;
if (!strcmp(str, "currentColor")) {
col->type = SVG_COLOR_CURRENTCOLOR;
return;
} else if (!strcmp(str, "inherit")) {
col->type = SVG_COLOR_INHERIT;
return;
} else if (str[0]=='#') {
u32 val;
sscanf(str+1, "%x", &val);
if (strlen(str) == 7) {
col->red = INT2FIX((val>>16) & 0xFF) / 255;
col->green = INT2FIX((val>>8) & 0xFF) / 255;
col->blue = INT2FIX(val & 0xFF) / 255;
} else {
col->red = INT2FIX((val>>8) & 0xF) / 15;
col->green = INT2FIX((val>>4) & 0xF) / 15;
col->blue = INT2FIX(val & 0xF) / 15;
}
col->type = SVG_COLOR_RGBCOLOR;
} else if (strstr(str, "rgb(") || strstr(str, "RGB(")) {
Float _val;
u8 is_percentage= 0;
if (strstr(str, "%")) is_percentage = 1;
str = strstr(str, "(");
str++;
sscanf(str, "%f", &_val);
col->red = FLT2FIX(_val);
str = strstr(str, ",");
if (!str) {
/* space separated colors/percentages are not allowed neither in SVG 1.1 nor in SVG T1.2 */
col->red = col->green = col->blue = 0;
return;
}
str++;
sscanf(str, "%f", &_val);
col->green = FLT2FIX(_val);
str = strstr(str, ",");
if (!str) {
/* space separated colors/percentages are not allowed neither in SVG 1.1 nor in SVG T1.2 */
col->red = col->green = col->blue = 0;
return;
}
str++;
sscanf(str, "%f", &_val);
col->blue = FLT2FIX(_val);
if (is_percentage) {
col->red /= 100;
col->green /= 100;
col->blue /= 100;
} else {
col->red /= 255;
col->green /= 255;
col->blue /= 255;
}
col->type = SVG_COLOR_RGBCOLOR;
} else if ((str[0] >= 'a' && str[0] <= 'z')
|| (str[0] >= 'A' && str[0] <= 'Z')) {
svg_parse_named_color(col, str);
} else {
Float _r, _g, _b;
sscanf(str, "%f %f %f", &_r, &_g, &_b);
col->red = FLT2FIX(_r);
col->green = FLT2FIX(_g);
col->blue = FLT2FIX(_b);
col->type = SVG_COLOR_RGBCOLOR;
}
}
/*
Reads a number (i.e. without unit) according to the CSS syntax (same as SVG paths and transforms)
trims any space, comma, semi-column before or after (TODO: fix this)
reads an optional + or -
then reads a digit between 0 and 9
optionally followed by an '.' and digits between 0 and 9
optionally followed by e or E and digits between 0 and 9
Returns the number of chars read in d
*/
static u32 svg_parse_number(char *d, Fixed *f, Bool is_angle)
{
u32 nb_digit_before = 0;
u32 nb_digit_after = 0;
Bool has_fractional = 0;
Bool is_negative = 0;
Float _val = 0;
u32 i = 0;
/* warning the comma and semicolumn should not be there when parsing a number in a path */
while ((d[i] != 0) && strchr(" ,;\r\n\t", d[i])) i++;
if (!d[i]) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Parsing] Parsing number with empty string or only spaces: %s\n", d));
return 0;
}
if (d[i] == '+') {
i++;
} else if (d[i] == '-') {
is_negative = 1;
i++;
}
/* Warning: this is not normal, should be detected somehow by checking the BNF */
/* if ((d[i]=='N') && (d[i+1]=='a') && (d[i+2]=='N')) {
i+= 3;
_val = 0;
goto end;
}*/
/* read the digit-sequence token of the BNF */
while (d[i] >= '0' && d[i] <= '9' && d[i] != 0) {
_val = _val*10 + (d[i]-'0');
nb_digit_before++;
i++;
}
if (d[i] == '.') {
has_fractional = 1;
i++;
while (d[i] >= '0' && d[i] <= '9' && d[i] != 0) {
_val = _val*10 + (d[i]-'0');
nb_digit_after++;
i++;
}
if (nb_digit_after) {
_val /= (Float)pow(10,nb_digit_after);
} else if (nb_digit_before == 0) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error in parsing number (expecting digits before or after a '.': %s\n", d));
return 0;
} else {
/* dangling '.' without digits after. This is allowed by the BNF */
}
}
if ((nb_digit_before == 0) && (has_fractional == 0)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error in parsing number (expecting digits):%s\n", d));
return 0;
}
/* reading the exponent */
if (d[i] == 'e' || d[i] == 'E') {
Bool neg_exp = 0;
u32 nb_exp_digits = 0;
s32 exp = 0;
i++;
if (d[i] == '+') i++;
else if (d[i] == '-') {
i++;
neg_exp=1;
}
while (d[i] >= '0' && d[i] <= '9' && d[i] != 0) {
exp = exp*10 + (d[i]-'0');
nb_exp_digits++;
i++;
}
if (nb_exp_digits) {
_val *= (Float)pow(10, neg_exp ? -exp : exp);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error in parsing exponent, 'e' or 'E' should be followed by digits: %s\n", d));
return 0;
}
}
/* We can now produce the final number */
if (is_negative) _val *= -1;
if (is_angle) {
_val/=180;
(*f) = gf_mulfix(FLT2FIX(_val), GF_PI);
} else {
(*f) = FLT2FIX(_val);
}
/* warning the comma and semicolumn should not be there when parsing a path number */
while (d[i] != 0 && (d[i] == ' ' || d[i] == ',' || d[i] == ';')) i++;
return i;
}
/*
Parse an Offset Value, i.e +/- Clock Value
*/
static GF_Err svg_parse_clock_value(char *d, Double *clock_value)
{
char *tmp;
s32 sign = 1;
if (!d) return GF_BAD_PARAM;
if (!d[0]) return GF_BAD_PARAM;
if (d[0] == '+') d++;
else if (d[0] == '-') {
sign = -1;
d++;
}
if (!d[0]) return GF_BAD_PARAM;
/* According to SVG, the following are invalid syntaxes (see animate-elem-225-t.svg)
'+-2s'
'1++s' even though sscanf returns the right values
*/
if (strchr(d, '+') || strchr(d, '-')) return GF_BAD_PARAM;
/* No embedded white space is allowed in clock values,
although leading and trailing white space characters will be ignored.*/
while (*d == ' ') d++;
if ((tmp = strchr(d, ':'))) {
/* Full or Partial Clock value */
tmp++;
if ((tmp = strchr(tmp, ':'))) {
/* Full Clock value : hh:mm:ss(.frac) */
u32 hours;
u32 minutes;
Float seconds;
if (sscanf(d, "%u:%u:%f", &hours, &minutes, &seconds) < 3) return GF_BAD_PARAM;
*clock_value = hours*3600 + minutes*60 + seconds;
} else {
/* Partial Clock value : mm:ss(.frac) */
s32 minutes;
Float seconds;
if (sscanf(d, "%d:%f", &minutes, &seconds) < 2) return GF_BAD_PARAM;
*clock_value = minutes*60 + seconds;
}
} else if ((tmp = strstr(d, "h"))) {
Float f;
if (sscanf(d, "%fh", &f) == 0) return GF_BAD_PARAM;
*clock_value = 3600*f;
} else if (strstr(d, "min")) {
Float f;
if (sscanf(d, "%fmin", &f) == 0) return GF_BAD_PARAM;
*clock_value = 60*f;
} else if ((tmp = strstr(d, "ms"))) {
Float f;
if (sscanf(d, "%fms", &f) == 0) return GF_BAD_PARAM;
*clock_value = f/1000;
} else if (strchr(d, 's')) {
Float f;
if (sscanf(d, "%fs", &f) == 0) return GF_BAD_PARAM;
*clock_value = f;
} else {
Float f;
if (sscanf(d, "%f", &f) == 0) return GF_BAD_PARAM;
*clock_value = f;
}
*clock_value *= sign;
return GF_OK;
}
/* Parses one SVG time value:
indefinite,
element_id.event_name
wallclock,
accessKey,
events,
clock value.
*/
static GF_Err smil_parse_time(GF_Node *elt, SMIL_Time *v, char *d)
{
GF_Err e = GF_OK;
char *tmp;
/* Offset Values */
if ((d[0] >= '0' && d[0] <= '9') || d[0] == '+' || d[0] == '-') {
v->type = GF_SMIL_TIME_CLOCK;
return svg_parse_clock_value(d, &(v->clock));
}
/* Indefinite Values */
else if (!strcmp(d, "indefinite")) {
v->type = GF_SMIL_TIME_INDEFINITE;
return GF_OK;
}
/* Wallclock Values */
else if ((tmp = strstr(d, "wallclock("))) {
u32 year, month, day;
u32 hours, minutes;
u32 nhours, nminutes;
Float seconds;
char *tmp1, *tmp2;
v->type = GF_SMIL_TIME_WALLCLOCK;
tmp += 10;
if ((tmp1 = strchr(tmp, 'T')) ) {
/* From tmp to wallStartTime, we parse a date */
sscanf(tmp, "%u-%u-%dT", &year, &month, &day);
tmp1++;
tmp = tmp1;
}
if ((tmp1 = strchr(tmp, ':')) ) {
if ((tmp2 = strchr(tmp1, ':')) ) {
/* HHMMSS */
sscanf(tmp, "%u:%u:%f", &hours, &minutes, &seconds);
} else {
/* HHMM */
sscanf(tmp, "%u:%u", &hours, &minutes);
}
}
if (strchr(tmp, 'Z')) {
return GF_OK;
} else {
if ( (tmp1 = strchr(tmp, '+')) ) {
sscanf(tmp1, "%u:%u", &nhours, &nminutes);
} else if ( (tmp1 = strchr(tmp, '-')) ) {
sscanf(tmp1, "%u:%u", &nhours, &nminutes);
}
}
return GF_OK;
}
/* AccessKey Values */
else if ((tmp = strstr(d, "accessKey("))) {
char *sep;
v->type = GF_SMIL_TIME_EVENT;
v->event.type = GF_EVENT_KEYDOWN;
v->element = elt->sgprivate->scenegraph->RootNode;
tmp+=10;
sep = strchr(d, ')');
sep[0] = 0;
v->event.parameter = gf_dom_get_key_type(tmp);
sep++;
if ((tmp = strchr(sep, '+')) || (tmp = strchr(sep, '-'))) {
char c = *tmp;
tmp++;
e = svg_parse_clock_value(tmp, &(v->clock));
if (c == '-') v->clock *= -1;
}
return e;
}
else {
Bool had_param = 0;
char *tmp2;
v->type = GF_SMIL_TIME_EVENT;
if ((tmp = strchr(d, '.'))) {
tmp[0] = 0;
if (strlen(d) == 0) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] expecting an id before '.' in SMIL Time .%s\n", tmp+1));
return GF_BAD_PARAM;
}
v->element_id = gf_strdup(d);
tmp[0] = '.';
tmp++;
} else {
tmp = d;
}
if ((tmp2 = strchr(tmp, '('))) {
tmp2[0] = 0;
v->event.type = gf_dom_event_type_by_name(tmp);
tmp2[0] = '(';
tmp2++;
had_param = 1;
v->event.parameter = atoi(tmp2);
tmp = strchr(tmp2, ')');
if (!tmp) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] expecting ')' in SMIL Time %s\n", d));
return GF_BAD_PARAM;
}
tmp++;
}
if ((tmp2 = strchr(tmp, '+')) || (tmp2 = strchr(tmp, '-'))) {
char c = *tmp2;
char *tmp3 = tmp2;
tmp2[0] = 0;
tmp3--;
while (*tmp3==' ') {
*tmp3=0;
tmp3--;
}
if (v->event.type == 0) v->event.type = gf_dom_event_type_by_name(tmp);
if (!had_param && (v->event.type == GF_EVENT_REPEAT || v->event.type == GF_EVENT_REPEAT_EVENT))
v->event.parameter = 1;
tmp2[0] = c;
tmp2++;
e = svg_parse_clock_value(tmp2, &(v->clock));
if (c == '-') v->clock *= -1;
return e;
} else {
if (v->event.type == 0) v->event.type = gf_dom_event_type_by_name(tmp);
if (!had_param && (v->event.type == GF_EVENT_REPEAT || v->event.type == GF_EVENT_REPEAT_EVENT))
v->event.parameter = 1;
}
}
return GF_OK;
}
/* Parses a list of SVG transformations and collapses them in the given matrix */
Bool gf_svg_parse_transformlist(GF_Matrix2D *mat, char *attribute_content)
{
GF_Matrix2D tmp;
char *str;
u32 read_chars;
u32 i;
gf_mx2d_init(*mat);
str = attribute_content;
i = 0;
while (str[i] != 0) {
while (str[i] == ' ') i++;
if (str[i] == ',') i++;
while (str[i] == ' ') i++;
if (strstr(str+i, "scale")==str+i) {
i += 5;
while(str[i] == ' ') i++;
if (str[i] == '(') {
Fixed sx, sy;
i++;
read_chars = svg_parse_number(&(str[i]), &sx, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading sx component in scale: %s\n", attribute_content));
return 0;
}
i += read_chars;
if (str[i] == ')') {
sy = sx;
} else {
read_chars = svg_parse_number(&(str[i]), &sy, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading sy component in scale: %s\n", attribute_content));
return 0;
}
i += read_chars;
}
gf_mx2d_init(tmp);
gf_mx2d_add_scale(&tmp, sx, sy);
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else if (strstr(str+i, "translate")==str+i) {
i += 9;
while(str[i] == ' ') i++;
if (str[i] == '(') {
Fixed tx, ty;
i++;
read_chars = svg_parse_number(&(str[i]), &tx, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading tx component in translate: %s\n", attribute_content));
return 0;
}
i += read_chars;
if (str[i] == ')') {
ty = 0;
} else {
read_chars = svg_parse_number(&(str[i]), &ty, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading ty component in translate: %s\n", attribute_content));
return 0;
}
i += read_chars;
}
gf_mx2d_init(tmp);
gf_mx2d_add_translation(&tmp, tx, ty);
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else if (strstr(str+i, "rotate")==str+i) {
i += 6;
while(str[i] == ' ') i++;
if (str[i] == '(') {
Fixed angle, cx, cy;
i++;
read_chars = svg_parse_number(&(str[i]), &angle, 1);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading angle component in rotate: %s\n", attribute_content));
return 0;
}
i += read_chars;
if (str[i] == ')') {
cx = cy = 0;
} else {
read_chars = svg_parse_number(&(str[i]), &cx, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading cx component in rotate: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &cy, 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading cy component in rotate: %s\n", attribute_content));
return 0;
}
i += read_chars;
}
gf_mx2d_init(tmp);
gf_mx2d_add_rotation(&tmp, cx, cy, angle);
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else if (strstr(str+i, "skewX")==str+i) {
i += 5;
while(str[i] == ' ') i++;
if (str[i] == '(') {
Fixed angle;
i++;
read_chars = svg_parse_number(&(str[i]), &angle, 1);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading angle in skewX: %s\n", attribute_content));
return 0;
}
i += read_chars;
gf_mx2d_init(tmp);
gf_mx2d_add_skew_x(&tmp, angle);
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else if (strstr(str+i, "skewY")==str+i) {
i += 5;
while(str[i] == ' ') i++;
if (str[i] == '(') {
Fixed angle;
i++;
read_chars = svg_parse_number(&(str[i]), &angle, 1);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading angle component in skewY: %s\n", attribute_content));
return 0;
}
i += read_chars;
gf_mx2d_init(tmp);
gf_mx2d_add_skew_y(&tmp, angle);
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else if (strstr(str+i, "matrix")==str+i) {
i+=6;
while(str[i] == ' ') i++;
if (str[i] == '(') {
i++;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[0]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient a in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[3]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient b in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[1]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient c in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[4]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient d in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[2]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient e in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(tmp.m[5]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient f in matrix: %s\n", attribute_content));
return 0;
}
i += read_chars;
gf_mx2d_add_matrix(&tmp, mat);
gf_mx2d_copy(*mat, tmp);
while(str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in transform attribute: %s\n", attribute_content));
return 0;
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Unrecognized transofrm type in attribute %s\n", attribute_content));
return 0;
}
/*for svgView parsing*/
if (str[i] == ')') i++;
}
return 1;
}
/* Parses an SVG transform attribute and collapses all in the given matrix */
static GF_Err svg_parse_transform(SVG_Transform *t, char *attribute_content)
{
char *str;
u32 i;
u32 read_chars;
i = 0;
if ((str = strstr(attribute_content, "ref"))) {
t->is_ref = 1;
gf_mx2d_init(t->mat);
str+=2;
while (str[i] == ' ') i++;
if (str[i] == '(') {
i++;
while (str[i] == ' ') i++;
if (str[i] == 's' && str[i+1] == 'v' && str[i+2] == 'g') {
i+=3;
while (str[i] == ' ') i++;
if (str[i] == ',') {
i++;
} else if (str[i] == ')') {
i++;
return GF_OK;
}
read_chars = svg_parse_number(&(str[i]), &(t->mat.m[2]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient tx in ref transform: %s\n", attribute_content));
return GF_BAD_PARAM;
}
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(t->mat.m[5]), 0);
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error reading coefficient ty in ref transform: %s\n", attribute_content));
return GF_BAD_PARAM;
}
i += read_chars;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Unsupported syntax for ref transform attribute"));
}
while (str[i] == ' ') i++;
if (str[i] == ')') i++;
else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing closing parenthesis in transform attribute: %s\n", attribute_content));
}
return GF_OK;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Missing opening parenthesis in ref transform attribute: %s\n", attribute_content));
return GF_BAD_PARAM;
}
} else {
Bool res = gf_svg_parse_transformlist(&t->mat, attribute_content);
if (!res) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error parsing transform list: %s\n", attribute_content));
return GF_BAD_PARAM;
}
}
return GF_OK;
}
#undef REMOVE_ALLOC
#if USE_GF_PATH
//#define PARSE_PATH_ONLY
static void svg_parse_path(SVG_PathData *path, char *attribute_content)
{
char *d = attribute_content;
/* used to detect end of BNF production:
"The processing of the BNF must consume as much of a given BNF production as possible,
stopping at the point when a character is encountered which no longer satisfies the production." */
u32 read_chars = 0;
/* Point used to start a new subpath when the previous subpath is closed */
SVG_Point prev_m_pt;
/* Point used to convert relative 'lower-case commands' into absolute */
SVG_Point rel_ref_pt;
/* Points used to convert S, T commands into C, Q */
SVG_Point orig, ct_orig, ct_end, end;
/* Used by elliptical arcs */
Fixed x_axis_rotation, large_arc_flag, sweep_flag;
char c, prev_c;
u32 i;
if (*d == 0) return;
i = 0;
prev_c = 'M';
orig.x = orig.y = ct_orig.x = ct_orig.y = prev_m_pt.x = prev_m_pt.y = rel_ref_pt.x = rel_ref_pt.y = end.x = end.y = 0;
while(1) {
while ( (d[i]==' ') || (d[i] =='\t') || (d[i] =='\r') || (d[i] =='\n') ) i++;
c = d[i];
if (! c) break;
next_command:
switch (c) {
case 'm':
case 'M':
i++;
read_chars = svg_parse_number(&(d[i]), &(orig.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(orig.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'm') {
orig.x += rel_ref_pt.x;
orig.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_move_to(path, orig.x, orig.y);
#endif
rel_ref_pt = orig;
prev_m_pt = orig;
/*provision for nextCurveTo when no curve is specified:
"If there is no previous command or if the previous command was not an C, c, S or s,
assume the first control point is coincident with the current point.
*/
ct_orig = orig;
prev_c = c;
break;
case 'L':
case 'l':
i++;
read_chars = svg_parse_number(&(d[i]), &(orig.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(orig.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'l') {
orig.x += rel_ref_pt.x;
orig.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_line_to(path, orig.x, orig.y);
#endif
rel_ref_pt = orig;
orig = end;
/*cf above*/
ct_orig = orig;
prev_c = c;
break;
case 'H':
case 'h':
i++;
read_chars = svg_parse_number(&(d[i]), &(orig.x), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'h') {
orig.x += rel_ref_pt.x;
}
orig.y = rel_ref_pt.y;
#ifndef PARSE_PATH_ONLY
gf_path_add_line_to(path, orig.x, orig.y);
#endif
rel_ref_pt.x = orig.x;
orig = end;
/*cf above*/
ct_orig = orig;
prev_c = c;
break;
case 'V':
case 'v':
i++;
read_chars = svg_parse_number(&(d[i]), &(orig.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'v') {
orig.y += rel_ref_pt.y;
}
orig.x = rel_ref_pt.x;
#ifndef PARSE_PATH_ONLY
gf_path_add_line_to(path, orig.x, orig.y);
#endif
rel_ref_pt.y = orig.y;
orig = end;
/*cf above*/
ct_orig = orig;
prev_c = c;
break;
case 'C':
case 'c':
i++;
read_chars = svg_parse_number(&(d[i]), &(ct_orig.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(ct_orig.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'c') {
ct_orig.x += rel_ref_pt.x;
ct_orig.y += rel_ref_pt.y;
}
read_chars = svg_parse_number(&(d[i]), &(ct_end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(ct_end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'c') {
ct_end.x += rel_ref_pt.x;
ct_end.y += rel_ref_pt.y;
}
read_chars = svg_parse_number(&(d[i]), &(end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'c') {
end.x += rel_ref_pt.x;
end.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_cubic_to(path, ct_orig.x, ct_orig.y, ct_end.x, ct_end.y, end.x, end.y);
#endif
rel_ref_pt = end;
ct_orig = ct_end;
orig = end;
prev_c = c;
break;
case 'S':
case 's':
i++;
ct_orig.x = 2*orig.x - ct_orig.x;
ct_orig.y = 2*orig.y - ct_orig.y;
read_chars = svg_parse_number(&(d[i]), &(ct_end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(ct_end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 's') {
ct_end.x += rel_ref_pt.x;
ct_end.y += rel_ref_pt.y;
}
read_chars = svg_parse_number(&(d[i]), &(end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 's') {
end.x += rel_ref_pt.x;
end.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_cubic_to(path, ct_orig.x, ct_orig.y, ct_end.x, ct_end.y, end.x, end.y);
#endif
rel_ref_pt = end;
ct_orig = ct_end;
orig = end;
prev_c = c;
break;
case 'Q':
case 'q':
i++;
read_chars = svg_parse_number(&(d[i]), &(ct_orig.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(ct_orig.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'q') {
ct_orig.x += rel_ref_pt.x;
ct_orig.y += rel_ref_pt.y;
}
read_chars = svg_parse_number(&(d[i]), &(end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'q') {
end.x += rel_ref_pt.x;
end.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_quadratic_to(path, ct_orig.x, ct_orig.y, end.x, end.y);
#endif
rel_ref_pt = end;
orig = end;
prev_c = c;
break;
case 'T':
case 't':
i++;
ct_orig.x = 2*orig.x - ct_orig.x;
ct_orig.y = 2*orig.y - ct_orig.y;
read_chars = svg_parse_number(&(d[i]), &(end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 't') {
end.x += rel_ref_pt.x;
end.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_quadratic_to(path, ct_orig.x, ct_orig.y, end.x, end.y);
#endif
rel_ref_pt = end;
orig = end;
prev_c = c;
break;
case 'A':
case 'a':
i++;
read_chars = svg_parse_number(&(d[i]), &(orig.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(orig.y), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(x_axis_rotation), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(large_arc_flag), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(sweep_flag), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(d[i]), &(end.y), 0);
if (!read_chars) return;
i += read_chars;
if (c == 'a') {
end.x += rel_ref_pt.x;
end.y += rel_ref_pt.y;
}
#ifndef PARSE_PATH_ONLY
gf_path_add_svg_arc_to(path, end.x, end.y, orig.x, orig.y, x_axis_rotation , (large_arc_flag == FIX_ONE ? 1 : 0), (sweep_flag == FIX_ONE ? 1 : 0));
#endif
rel_ref_pt = end;
ct_orig = end;
prev_c = c;
break;
case 'Z':
case 'z':
i++;
#ifndef PARSE_PATH_ONLY
gf_path_close(path);
#endif
prev_c = c;
rel_ref_pt = prev_m_pt;
break;
default:
i--;
switch (prev_c) {
case 'M':
c = 'L';
break;
case 'm':
c = 'l';
break;
default:
c = prev_c;
}
goto next_command;
}
}
}
#else
/* TODO: Change the function to handle elliptical arcs, requires changing data structure */
static void svg_parse_path(SVG_PathData *d_attribute, char *attribute_content)
{
GF_List *d_commands = d_attribute->commands;
GF_List *d_points = d_attribute->points;
char *d = attribute_content;
if (strlen(d)) {
SVG_Point *pt, cur_pt, prev_m_pt;
u8 *command;
u32 i, k;
char c, prev_c = 'M';
#ifdef REMOVE_ALLOC
GF_SAFEALLOC(pt, SVG_Point)
#endif
i = 0;
cur_pt.x = cur_pt.y = 0;
prev_m_pt.x = prev_m_pt.y = 0;
while(1) {
while ( (d[i]==' ') || (d[i] =='\t') ) i++;
c = d[i];
if (! c) break;
next_command:
switch (c) {
case 'm':
case 'M':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_M;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'm') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_m_pt = cur_pt;
prev_c = c;
break;
case 'L':
case 'l':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_L;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'l') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'H':
case 'h':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_L;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
if (c == 'h') {
pt->x += cur_pt.x;
}
pt->y = cur_pt.y;
cur_pt.x = pt->x;
prev_c = c;
break;
case 'V':
case 'v':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_L;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'v') {
pt->y += cur_pt.y;
}
pt->x = cur_pt.x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'C':
case 'c':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_C;
#endif
for (k=0; k<3; k++) {
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'c') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'S':
case 's':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_S;
#endif
for (k=0; k<2; k++) {
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 's') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'Q':
case 'q':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_Q;
#endif
for (k=0; k<2; k++) {
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'q') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'T':
case 't':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_T;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 't') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
prev_c = c;
break;
case 'A':
case 'a':
{
Fixed tmp;
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_A;
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
i += svg_parse_number(&(d[i]), &(tmp), 0);
i += svg_parse_number(&(d[i]), &(tmp), 0);
i += svg_parse_number(&(d[i]), &(tmp), 0);
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(pt, SVG_Point)
gf_list_add(d_points, pt);
#endif
i += svg_parse_number(&(d[i]), &(pt->x), 0);
i += svg_parse_number(&(d[i]), &(pt->y), 0);
if (c == 'a') {
pt->x += cur_pt.x;
pt->y += cur_pt.y;
}
cur_pt.x = pt->x;
cur_pt.y = pt->y;
}
prev_c = c;
break;
case 'Z':
case 'z':
i++;
#ifndef REMOVE_ALLOC
GF_SAFEALLOC(command, u8)
gf_list_add(d_commands, command);
*command = SVG_PATHCOMMAND_Z;
#endif
prev_c = c;
cur_pt = prev_m_pt;
break;
default:
i--;
switch (prev_c) {
case 'M':
c = 'L';
break;
case 'm':
c = 'l';
break;
default:
c = prev_c;
}
goto next_command;
}
}
}
}
#endif
static void svg_parse_iri(GF_Node *elt, XMLRI *iri, char *attribute_content)
{
if (iri->string) {
gf_free(iri->string);
iri->string = NULL;
}
/* TODO: Handle xpointer(id()) syntax */
if (attribute_content[0] == '#') {
iri->string = gf_strdup(attribute_content);
iri->target = gf_sg_find_node_by_name(elt->sgprivate->scenegraph, attribute_content + 1);
if (!iri->target) {
iri->type = XMLRI_STRING;
} else {
iri->type = XMLRI_ELEMENTID;
gf_node_register_iri(elt->sgprivate->scenegraph, iri);
}
} else {
iri->type = XMLRI_STRING;
iri->string = gf_strdup(attribute_content);
}
}
static void svg_parse_idref(GF_Node *elt, XML_IDREF *iri, char *attribute_content)
{
iri->type = XMLRI_ELEMENTID;
iri->target = gf_sg_find_node_by_name(elt->sgprivate->scenegraph, attribute_content);
if (!iri->target) {
iri->string = gf_strdup(attribute_content);
} else {
gf_node_register_iri(elt->sgprivate->scenegraph, iri);
}
}
/* Parses a paint attribute: none, inherit or color */
static void svg_parse_paint(GF_Node *n, SVG_Paint *paint, char *attribute_content)
{
if (!strcmp(attribute_content, "none")) {
paint->type = SVG_PAINT_NONE;
} else if (!strcmp(attribute_content, "inherit")) {
paint->type = SVG_PAINT_INHERIT;
} else if (!strncmp(attribute_content, "url(", 4) ) {
char *ext = strrchr(attribute_content, ')');
paint->type = SVG_PAINT_URI;
if (ext) ext[0] = 0;
svg_parse_iri(n, &paint->iri, attribute_content+4);
if (ext) ext[0] = ')';
} else {
paint->type = SVG_PAINT_COLOR;
svg_parse_color(&paint->color, attribute_content);
}
}
/* Parses a length which is a number with a unit */
static u32 svg_parse_length(SVG_Number *number, char *value_string, Bool clamp0to1)
{
char c = '\0';
char *unit = NULL;
u32 len = 0;
u32 unit_pos = 0;
u32 unit_len = 0;
u32 read_chars;
if (!number || !value_string) return 0;
if (!strcmp(value_string, "inherit")) {
number->type = SVG_NUMBER_INHERIT;
return 7;
} else if (!strcmp(value_string, "auto")) {
number->type = SVG_NUMBER_AUTO;
return 4;
} else if (!strcmp(value_string, "auto-reverse")) {
number->type = SVG_NUMBER_AUTO_REVERSE;
return 12;
} else if ((unit = strstr(value_string, "%")) ) {
number->type = SVG_NUMBER_PERCENTAGE;
unit_len = 1;
} else if ((unit = strstr(value_string, "em"))) {
number->type = SVG_NUMBER_EMS;
} else if ((unit = strstr(value_string, "ex"))) {
number->type = SVG_NUMBER_EXS;
} else if ((unit = strstr(value_string, "px"))) {
number->type = SVG_NUMBER_PX;
} else if ((unit = strstr(value_string, "cm"))) {
number->type = SVG_NUMBER_CM;
} else if ((unit = strstr(value_string, "mm"))) {
number->type = SVG_NUMBER_MM;
} else if ((unit = strstr(value_string, "in"))) {
number->type = SVG_NUMBER_IN;
} else if ((unit = strstr(value_string, "pt"))) {
number->type = SVG_NUMBER_PT;
} else if ((unit = strstr(value_string, "pc"))) {
number->type = SVG_NUMBER_PC;
} else {
number->type = SVG_NUMBER_VALUE;
}
if (unit) {
if (!unit_len) unit_len = 2;
unit_pos = (u32) (unit - value_string);
/* setting the first unit character to 0 for the svg_parse_number method to finish */
c = value_string[unit_pos];
value_string[unit_pos] = 0;
}
read_chars = svg_parse_number(value_string, &(number->value), 0);
if (unit) {
value_string[unit_pos] = c;
}
if (!read_chars) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Error in parsing: %s\n", value_string));
len = 0;
} else {
len = unit_len + read_chars;
}
if (clamp0to1) number->value = MAX(0, MIN(1, number->value));
return len;
}
static void svg_parse_visibility(SVG_Visibility *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_VISIBILITY_INHERIT;
} else if (!strcmp(value_string, "visible")) {
*value = SVG_VISIBILITY_VISIBLE;
} else if (!strcmp(value_string, "hidden")) {
*value = SVG_VISIBILITY_HIDDEN;
} else if (!strcmp(value_string, "collapse")) {
*value = SVG_VISIBILITY_COLLAPSE;
}
}
static void svg_parse_display(SVG_Display *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_DISPLAY_INHERIT;
} else if (!strcmp(value_string, "none")) {
*value = SVG_DISPLAY_NONE;
} else if (!strcmp(value_string, "inline")) {
*value = SVG_DISPLAY_INLINE;
} else if (!strcmp(value_string, "block")) {
*value = SVG_DISPLAY_BLOCK;
} else if (!strcmp(value_string, "list-item")) {
*value = SVG_DISPLAY_LIST_ITEM;
} else if (!strcmp(value_string, "run-in")) {
*value = SVG_DISPLAY_RUN_IN;
} else if (!strcmp(value_string, "compact")) {
*value = SVG_DISPLAY_COMPACT;
} else if (!strcmp(value_string, "marker")) {
*value = SVG_DISPLAY_MARKER;
} else if (!strcmp(value_string, "table")) {
*value = SVG_DISPLAY_TABLE;
} else if (!strcmp(value_string, "inline-table")) {
*value = SVG_DISPLAY_INLINE_TABLE;
} else if (!strcmp(value_string, "table-row-group")) {
*value = SVG_DISPLAY_TABLE_ROW_GROUP;
} else if (!strcmp(value_string, "table-header-group")) {
*value = SVG_DISPLAY_TABLE_HEADER_GROUP;
} else if (!strcmp(value_string, "table-footer-group")) {
*value = SVG_DISPLAY_TABLE_FOOTER_GROUP;
} else if (!strcmp(value_string, "table-row")) {
*value = SVG_DISPLAY_TABLE_ROW;
} else if (!strcmp(value_string, "table-column-group")) {
*value = SVG_DISPLAY_TABLE_COLUMN_GROUP;
} else if (!strcmp(value_string, "table-column")) {
*value = SVG_DISPLAY_TABLE_COLUMN;
} else if (!strcmp(value_string, "table-cell")) {
*value = SVG_DISPLAY_TABLE_CELL;
} else if (!strcmp(value_string, "table-caption")) {
*value = SVG_DISPLAY_TABLE_CAPTION;
}
}
static void svg_parse_displayalign(SVG_DisplayAlign *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_DISPLAYALIGN_INHERIT;
} else if (!strcmp(value_string, "auto")) {
*value = SVG_DISPLAYALIGN_AUTO;
} else if (!strcmp(value_string, "before")) {
*value = SVG_DISPLAYALIGN_BEFORE;
} else if (!strcmp(value_string, "center")) {
*value = SVG_DISPLAYALIGN_CENTER;
} else if (!strcmp(value_string, "after")) {
*value = SVG_DISPLAYALIGN_AFTER;
}
}
static void svg_parse_textalign(SVG_TextAlign *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_TEXTALIGN_INHERIT;
} else if (!strcmp(value_string, "start")) {
*value = SVG_TEXTALIGN_START;
} else if (!strcmp(value_string, "center")) {
*value = SVG_TEXTALIGN_CENTER;
} else if (!strcmp(value_string, "end")) {
*value = SVG_TEXTALIGN_END;
}
}
static void svg_parse_pointerevents(SVG_PointerEvents *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_POINTEREVENTS_INHERIT;
} else if (!strcmp(value_string, "visiblePainted")) {
*value = SVG_POINTEREVENTS_VISIBLEPAINTED;
} else if (!strcmp(value_string, "visibleFill")) {
*value = SVG_POINTEREVENTS_VISIBLEFILL;
} else if (!strcmp(value_string, "visibleStroke")) {
*value = SVG_POINTEREVENTS_VISIBLESTROKE;
} else if (!strcmp(value_string, "visible")) {
*value = SVG_POINTEREVENTS_VISIBLE;
} else if (!strcmp(value_string, "painted")) {
*value = SVG_POINTEREVENTS_PAINTED;
} else if (!strcmp(value_string, "fill")) {
*value = SVG_POINTEREVENTS_FILL;
} else if (!strcmp(value_string, "stroke")) {
*value = SVG_POINTEREVENTS_STROKE;
} else if (!strcmp(value_string, "all")) {
*value = SVG_POINTEREVENTS_ALL;
} else if (!strcmp(value_string, "boundingBox")) {
*value = SVG_POINTEREVENTS_BOUNDINGBOX;
} else if (!strcmp(value_string, "none")) {
*value = SVG_POINTEREVENTS_NONE;
}
}
static void svg_parse_renderinghint(SVG_RenderingHint *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_RENDERINGHINT_INHERIT;
} else if (!strcmp(value_string, "auto")) {
*value = SVG_RENDERINGHINT_AUTO;
} else if (!strcmp(value_string, "optimizeQuality")) {
*value = SVG_RENDERINGHINT_OPTIMIZEQUALITY;
} else if (!strcmp(value_string, "optimizeSpeed")) {
*value = SVG_RENDERINGHINT_OPTIMIZESPEED;
} else if (!strcmp(value_string, "optimizeLegibility")) {
*value = SVG_RENDERINGHINT_OPTIMIZELEGIBILITY;
} else if (!strcmp(value_string, "crispEdges")) {
*value = SVG_RENDERINGHINT_CRISPEDGES;
} else if (!strcmp(value_string, "geometricPrecision")) {
*value = SVG_RENDERINGHINT_GEOMETRICPRECISION;
}
}
static void svg_parse_vectoreffect(SVG_VectorEffect *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_VECTOREFFECT_INHERIT;
} else if (!strcmp(value_string, "none")) {
*value = SVG_VECTOREFFECT_NONE;
} else if (!strcmp(value_string, "non-scaling-stroke")) {
*value = SVG_VECTOREFFECT_NONSCALINGSTROKE;
}
}
static void svg_parse_playbackorder(SVG_VectorEffect *value, char *value_string)
{
if (!strcmp(value_string, "forwardOnly")) {
*value = SVG_PLAYBACKORDER_FORWARDONLY;
} else if (!strcmp(value_string, "all")) {
*value = SVG_PLAYBACKORDER_ALL;
}
}
static void svg_parse_timelinebegin(SVG_TimelineBegin *value, char *value_string)
{
if (!strcmp(value_string, "onStart")) {
*value = SVG_TIMELINEBEGIN_ONSTART;
} else if (!strcmp(value_string, "onLoad")) {
*value = SVG_TIMELINEBEGIN_ONLOAD;
}
}
static void svg_parse_xmlspace(XML_Space *value, char *value_string)
{
if (!strcmp(value_string, "default")) {
*value = XML_SPACE_DEFAULT;
} else if (!strcmp(value_string, "preserve")) {
*value = XML_SPACE_PRESERVE;
}
}
static void svg_parse_xmlev_propagate(XMLEV_Propagate *value, char *value_string)
{
if (!strcmp(value_string, "continue")) {
*value = XMLEVENT_PROPAGATE_CONTINUE;
} else if (!strcmp(value_string, "stop")) {
*value = XMLEVENT_PROPAGATE_STOP;
}
}
static void svg_parse_xmlev_defaultAction(XMLEV_DefaultAction *value, char *value_string)
{
if (!strcmp(value_string, "cancel")) {
*value = XMLEVENT_DEFAULTACTION_CANCEL;
} else if (!strcmp(value_string, "perform")) {
*value = XMLEVENT_DEFAULTACTION_PERFORM;
}
}
static void svg_parse_xmlev_phase(XMLEV_Phase *value, char *value_string)
{
if (!strcmp(value_string, "default")) {
*value = XMLEVENT_PHASE_DEFAULT;
} else if (!strcmp(value_string, "capture")) {
*value = XMLEVENT_PHASE_CAPTURE;
}
}
static void svg_parse_overflow(SVG_Overflow *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_OVERFLOW_INHERIT;
} else if (!strcmp(value_string, "visible")) {
*value = SVG_OVERFLOW_VISIBLE;
} else if (!strcmp(value_string, "hidden")) {
*value = SVG_OVERFLOW_HIDDEN;
} else if (!strcmp(value_string, "scroll")) {
*value = SVG_OVERFLOW_SCROLL;
} else if (!strcmp(value_string, "auto")) {
*value = SVG_OVERFLOW_AUTO;
}
}
static void svg_parse_textanchor(SVG_TextAnchor *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_TEXTANCHOR_INHERIT;
} else if (!strcmp(value_string, "start")) {
*value = SVG_TEXTANCHOR_START;
} else if (!strcmp(value_string, "middle")) {
*value = SVG_TEXTANCHOR_MIDDLE;
} else if (!strcmp(value_string, "end")) {
*value = SVG_TEXTANCHOR_END;
}
}
static void svg_parse_clipfillrule(SVG_FillRule *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_FILLRULE_INHERIT;
} else if (!strcmp(value_string, "nonzero")) {
*value = SVG_FILLRULE_NONZERO;
} else if (!strcmp(value_string, "evenodd")) {
*value = SVG_FILLRULE_EVENODD;
}
}
static void svg_parse_strokelinejoin(SVG_StrokeLineJoin *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_STROKELINEJOIN_INHERIT;
} else if (!strcmp(value_string, "miter")) {
*value = SVG_STROKELINEJOIN_MITER;
} else if (!strcmp(value_string, "round")) {
*value = SVG_STROKELINEJOIN_ROUND;
} else if (!strcmp(value_string, "bevel")) {
*value = SVG_STROKELINEJOIN_BEVEL;
}
}
static void svg_parse_strokelinecap(SVG_StrokeLineCap *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_STROKELINECAP_INHERIT;
} else if (!strcmp(value_string, "butt")) {
*value = SVG_STROKELINECAP_BUTT;
} else if (!strcmp(value_string, "round")) {
*value = SVG_STROKELINECAP_ROUND;
} else if (!strcmp(value_string, "square")) {
*value = SVG_STROKELINECAP_SQUARE;
}
}
static void svg_parse_fontfamily(SVG_FontFamily *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
value->type = SVG_FONTFAMILY_INHERIT;
} else {
value->type = SVG_FONTFAMILY_VALUE;
value->value = gf_strdup(value_string);
}
}
static void svg_parse_fontstyle(SVG_FontStyle *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_FONTSTYLE_INHERIT;
} else if (!strcmp(value_string, "normal")) {
*value = SVG_FONTSTYLE_NORMAL;
} else if (!strcmp(value_string, "italic")) {
*value = SVG_FONTSTYLE_ITALIC;
} else if (!strcmp(value_string, "oblique")) {
*value = SVG_FONTSTYLE_OBLIQUE;
}
}
static void svg_parse_fontweight(SVG_FontWeight *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_FONTWEIGHT_INHERIT;
} else if (!strcmp(value_string, "normal")) {
*value = SVG_FONTWEIGHT_NORMAL;
} else if (!strcmp(value_string, "bold")) {
*value = SVG_FONTWEIGHT_BOLD;
} else if (!strcmp(value_string, "bolder")) {
*value = SVG_FONTWEIGHT_BOLDER;
} else if (!strcmp(value_string, "lighter")) {
*value = SVG_FONTWEIGHT_LIGHTER;
} else if (!strcmp(value_string, "100")) {
*value = SVG_FONTWEIGHT_100;
} else if (!strcmp(value_string, "200")) {
*value = SVG_FONTWEIGHT_200;
} else if (!strcmp(value_string, "300")) {
*value = SVG_FONTWEIGHT_300;
} else if (!strcmp(value_string, "400")) {
*value = SVG_FONTWEIGHT_400;
} else if (!strcmp(value_string, "500")) {
*value = SVG_FONTWEIGHT_500;
} else if (!strcmp(value_string, "600")) {
*value = SVG_FONTWEIGHT_600;
} else if (!strcmp(value_string, "700")) {
*value = SVG_FONTWEIGHT_700;
} else if (!strcmp(value_string, "800")) {
*value = SVG_FONTWEIGHT_800;
} else if (!strcmp(value_string, "900")) {
*value = SVG_FONTWEIGHT_900;
}
}
static void svg_parse_fontvariant(SVG_FontVariant *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SVG_FONTVARIANT_INHERIT;
} else if (!strcmp(value_string, "normal")) {
*value = SVG_FONTVARIANT_NORMAL;
} else if (!strcmp(value_string, "small-caps")) {
*value = SVG_FONTVARIANT_SMALLCAPS;
}
}
static void svg_parse_boolean(SVG_Boolean *value, char *value_string)
{
/*simple for text editable*/
if (!strcmp(value_string, "1") || !strcmp(value_string, "true") || !strcmp(value_string, "simple"))
*value = 1;
else
*value = 0;
}
static void smil_parse_time_list(GF_Node *e, GF_List *values, char *begin_or_end_list)
{
SMIL_Time *value;
char value_string[500];
char *str = begin_or_end_list, *tmp;
u32 len;
/* get rid of leading spaces */
while (*str == ' ') str++;
while (1) {
tmp = strchr(str, ';');
if (tmp) len = (u32) (tmp-str);
else len = (u32) strlen(str);
memcpy(value_string, str, len);
while (value_string[len - 1] == ' ' && len > 0) len--;
value_string[len] = 0;
GF_SAFEALLOC(value, SMIL_Time)
gf_list_add(values, value);
if (smil_parse_time(e, value, value_string) != GF_OK) goto err;
if (!tmp) break;
str = tmp + 1;
while (*str == ' ') str++;
}
/* sorting timing values */
if (gf_list_count(values) > 1) {
SMIL_Time *v, *sv;
GF_List *sorted = gf_list_new();
u32 i, count;
u8 added = 0;
do {
v = (SMIL_Time*)gf_list_get(values, 0);
gf_list_rem(values, 0);
added = 0;
count = gf_list_count(sorted);
for (i=0; i<count; i++) {
sv = (SMIL_Time*)gf_list_get(sorted, i);
if (v->type >= GF_SMIL_TIME_EVENT) {
/* unresolved or indefinite so add at the end of the sorted list */
gf_list_add(sorted, v);
added = 1;
break;
} else {
if (sv->type >= GF_SMIL_TIME_EVENT) {
gf_list_insert(sorted, v, i);
added = 1;
break;
} else {
if (v->clock <= sv->clock) {
gf_list_insert(sorted, v, i);
added = 1;
break;
}
}
}
}
if (!added) gf_list_add(sorted, v);
} while (gf_list_count(values) > 0);
count = gf_list_count(sorted);
for (i = 0; i < count; i++) {
gf_list_add(values, gf_list_get(sorted, i));
}
gf_list_del(sorted);
}
return;
err:
/* See SVG spec:
"If the 'begin' attribute is
syntactically invalid, in the list itself or in any of the individual
list values, it is equivalent to a single 'begin' value of 'indefinite'."*/
len = gf_list_count(values);
while (len) {
SMIL_Time *v = (SMIL_Time*)gf_list_get(values, 0);
if (v->element_id) gf_free(v->element_id);
gf_list_rem(values, 0);
gf_free(v);
len--;
}
GF_SAFEALLOC(value, SMIL_Time)
if (!value) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Fail to allocate SMIL time\n"));
return;
}
gf_list_add(values, value);
switch (e->sgprivate->tag) {
case TAG_SVG_discard:
value->type = GF_SMIL_TIME_CLOCK;
value->clock = 0;
break;
default:
value->type = GF_SMIL_TIME_INDEFINITE;
break;
}
return;
}
static void smil_parse_attributeType(SMIL_AttributeType *value, char *value_string)
{
if (!strcmp(value_string, "auto")) {
*value = SMIL_ATTRIBUTETYPE_AUTO;
} else if (!strcmp(value_string, "XML")) {
*value = SMIL_ATTRIBUTETYPE_XML;
} else if (!strcmp(value_string, "CSS")) {
*value = SMIL_ATTRIBUTETYPE_CSS;
}
}
static void smil_parse_min_max_dur_repeatdur(SMIL_Duration *value, char *value_string)
{
if (!strcmp(value_string, "indefinite")) {
value->type = SMIL_DURATION_INDEFINITE;
} else if (!strcmp(value_string, "media")) {
value->type = SMIL_DURATION_MEDIA;
} else {
Double ftime;
if ((svg_parse_clock_value(value_string, &ftime) == GF_OK) && (ftime >= 0)) {
value->clock_value = ftime;
value->type = SMIL_DURATION_DEFINED;
} else {
/* WARNING: Should this attribute in error be removed ? */
value->type = SMIL_DURATION_INDEFINITE;
}
}
}
static void smil_parse_repeatcount(SMIL_RepeatCount *value, char *value_string)
{
if (!strcmp(value_string, "indefinite")) {
value->type = SMIL_REPEATCOUNT_INDEFINITE;
} else {
Float _val;
sscanf(value_string, "%f", &_val);
value->type = SMIL_REPEATCOUNT_DEFINED;
value->count = FLT2FIX(_val);
}
}
static void smil_parse_fill(SMIL_Fill *value, char *value_string)
{
if (!strcmp(value_string, "freeze")) {
*value = SMIL_FILL_FREEZE;
} else if (!strcmp(value_string, "remove")) {
*value = SMIL_FILL_REMOVE;
}
}
static void smil_parse_restart(SMIL_Restart *value, char *value_string)
{
if (!strcmp(value_string, "always")) {
*value = SMIL_RESTART_ALWAYS;
} else if (!strcmp(value_string, "whenNotActive")) {
*value = SMIL_RESTART_WHENNOTACTIVE;
} else if (!strcmp(value_string, "never")) {
*value = SMIL_RESTART_NEVER;
}
}
static void smil_parse_calcmode(SMIL_CalcMode *value, char *value_string)
{
if (!strcmp(value_string, "discrete")) {
*value = SMIL_CALCMODE_DISCRETE;
} else if (!strcmp(value_string, "linear")) {
*value = SMIL_CALCMODE_LINEAR;
} else if (!strcmp(value_string, "paced")) {
*value = SMIL_CALCMODE_PACED;
} else if (!strcmp(value_string, "spline")) {
*value = SMIL_CALCMODE_SPLINE;
}
}
static void smil_parse_additive(SMIL_Additive *value, char *value_string)
{
if (!strcmp(value_string, "replace")) {
*value = SMIL_ADDITIVE_REPLACE;
} else if (!strcmp(value_string, "sum")) {
*value = SMIL_ADDITIVE_SUM;
}
}
static void smil_parse_accumulate(SMIL_Accumulate *value, char *value_string)
{
if (!strcmp(value_string, "none")) {
*value = SMIL_ACCUMULATE_NONE;
} else if (!strcmp(value_string, "sum")) {
*value = SMIL_ACCUMULATE_SUM;
}
}
static void smil_parse_syncBehaviorOrDefault(SMIL_SyncBehavior *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
*value = SMIL_SYNCBEHAVIOR_INHERIT;
} else if (!strcmp(value_string, "default")) {
*value = SMIL_SYNCBEHAVIOR_DEFAULT;
} else if (!strcmp(value_string, "locked")) {
*value = SMIL_SYNCBEHAVIOR_LOCKED;
} else if (!strcmp(value_string, "canSlip")) {
*value = SMIL_SYNCBEHAVIOR_CANSLIP;
} else if (!strcmp(value_string, "independent")) {
*value = SMIL_SYNCBEHAVIOR_INDEPENDENT;
}
}
static void smil_parse_syncToleranceOrDefault(SMIL_SyncTolerance *value, char *value_string)
{
if (!strcmp(value_string, "inherit")) {
value->type = SMIL_SYNCTOLERANCE_INHERIT;
} else if (!strcmp(value_string, "default")) {
value->type = SMIL_SYNCTOLERANCE_DEFAULT;
} else {
value->type = SMIL_SYNCBEHAVIOR_LOCKED;
svg_parse_clock_value(value_string, &(value->value));
}
}
static void svg_parse_viewbox(SVG_ViewBox *value, char *value_string)
{
u32 read_chars;
char *str = value_string;
if (!strcmp(str, "none")) {
value->is_set = 0;
} else {
u32 i = 0;
value->is_set = 1;
read_chars = svg_parse_number(&(str[i]), &(value->x), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(value->y), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(value->width), 0);
if (!read_chars) return;
i += read_chars;
read_chars = svg_parse_number(&(str[i]), &(value->height), 0);
if (!read_chars) return;
// i += read_chars;
}
}
/* Parses a list of coordinates or a list of lengths (in SVG, length and coordinate is the same type )*/
static void svg_parse_coordinates(GF_List *values, char *value_string)
{
SVG_Coordinate *c;
u32 i = 0;
char *str = value_string;
u32 len = (u32) strlen(str);
while (gf_list_count(values)) {
c = (SVG_Coordinate*)gf_list_get(values, 0);
gf_list_rem(values, 0);
gf_free(c);
}
while (i < len) {
u32 sub;
GF_SAFEALLOC(c, SVG_Coordinate)
sub = svg_parse_length(c, &(str[i]), 0);
if (!sub) {
gf_free(c);
return;
}
i+=sub;
gf_list_add(values, c);
}
}
/* Parse a point as a pair of number without units */
u32 svg_parse_point(SVG_Point *p, char *value_string)
{
u32 i = 0, j = 0;
i = svg_parse_number(&(value_string[i]), &(p->x), 0);
/* TODO: handle cases where a point has an invalid syntax */
j = svg_parse_number(&(value_string[i]), &(p->y), 0);
/* we need to detect an odd number of coordinates in polygon points list
cf. http://www.w3.org/TR/SVGMobile12/shapes.html#PolygonElement
see svg_parse_points */
if (j == 0) return 0;
else return i+j;
}
static u32 svg_parse_point_into_matrix(GF_Matrix2D *p, char *value_string)
{
u32 i = 0, j = 0;
gf_mx2d_init(*p);
i = svg_parse_number(&(value_string[i]), &(p->m[2]), 0);
if (i == 0) return 0;
j = svg_parse_number(&(value_string[i]), &(p->m[5]), 0);
if (j == 0) return 0;
return i+j;
}
/* Parses the points attribute of a polygon or polyline element */
static void svg_parse_points(GF_List *values, char *value_string)
{
u32 i = 0, j;
char *str = value_string;
u32 len = (u32) strlen(str);
while (i < len) {
SVG_Point *p;
GF_SAFEALLOC(p, SVG_Point)
j = svg_parse_point(p, &str[i]);
if (j == 0) {
/* cf. http://www.w3.org/TR/SVGMobile12/shapes.html#PolygonElement
If an odd number of coordinates is provided, then the element
is treated as if the attribute had not been specified.*/
while (gf_list_count(values)) {
p = (SVG_Point *)gf_list_get(values, 0);
gf_free(p);
gf_list_rem(values, 0);
}
return;
}
i += j;
gf_list_add(values, p);
}
}
/* Parses a list of numbers */
static void svg_parse_numbers(GF_List *values, char *value_string, Bool is_angle)
{
u32 read_chars;
u32 i = 0;
char *str = value_string;
u32 len = (u32) strlen(str);
while (i < len) {
Fixed *f;
GF_SAFEALLOC(f, Fixed)
read_chars = svg_parse_number(&(str[i]), f, is_angle);
if (!read_chars) {
gf_free(f);
return;
}
i += read_chars;
gf_list_add(values, f);
}
}
static void svg_string_list_add(GF_List *values, char *string, u32 string_type)
{
XMLRI *iri;
switch (string_type) {
case 1:
iri = (XMLRI*)gf_malloc(sizeof(XMLRI));
iri->type = XMLRI_STRING;
iri->string = gf_strdup(string);
gf_list_add(values, iri);
break;
default:
gf_list_add(values, gf_strdup(string));
break;
}
}
static void svg_parse_strings(GF_List *values, char *value_string, u32 string_type)
{
char *next, *sep = value_string;
while (gf_list_count(values)) {
next = (char*)gf_list_last(values);
gf_list_rem_last(values);
gf_free(next);
}
while (1) {
while (sep && sep[0]==' ') sep++;
if (!sep) break;
next = sep+1;
while (next[0]) {
if (strchr(" ;,", next[0])) break;
next++;
}
if (!next[0]) {
svg_string_list_add(values, sep, string_type);
break;
}
next[0]=0;
svg_string_list_add(values, sep, string_type);
next[0]=';';
sep = next+1;
while (strchr(" ,;", sep[0])) sep++;
}
}
static void svg_parse_strokedasharray(SVG_StrokeDashArray *value, char *value_string)
{
u32 read_chars;
if (!strcmp(value_string, "none")) {
value->type = SVG_STROKEDASHARRAY_NONE;
} else if (!strcmp(value_string, "inherit")) {
value->type = SVG_STROKEDASHARRAY_INHERIT;
} else {
UnitArray *vals = &(value->array);
GF_List *values = gf_list_new();
u32 i = 0;
u32 len = (u32) strlen(value_string);
char *str = value_string;
while (i < len) {
SVG_Length *f;
GF_SAFEALLOC(f, SVG_Length)
read_chars = svg_parse_length(f, &(str[i]), 0);
if (!read_chars) {
gf_free(f);
return;
}
i += read_chars;
gf_list_add(values, f);
}
vals->count = gf_list_count(values);
vals->units = (u8 *) gf_malloc(sizeof(u8)*vals->count);
vals->vals = (Fixed *) gf_malloc(sizeof(Fixed)*vals->count);
for (i = 0; i < vals->count; i++) {
SVG_Length *f = (SVG_Length *)gf_list_get(values, i);
vals->vals[i] = f->value;
vals->units[i] = f->type;
gf_free(f);
}
gf_list_del(values);
value->type = SVG_STROKEDASHARRAY_ARRAY;
}
}
static void svg_parse_zoomandpan(SVG_ZoomAndPan *value, char *value_string)
{
if (!strcmp(value_string, "disable")) {
*value = SVG_ZOOMANDPAN_DISABLE;
} else if (!strcmp(value_string, "magnify")) {
*value = SVG_ZOOMANDPAN_MAGNIFY;
}
}
static void svg_parse_preserveaspectratio(SVG_PreserveAspectRatio *par, char *attribute_content)
{
char *content = attribute_content;
while (*content == ' ') content++;
if (strstr(content, "defer")) {
par->defer = 1;
content += 4;
} else {
content = attribute_content;
}
while (*content == ' ') content++;
if (strstr(content, "none")) {
par->align = SVG_PRESERVEASPECTRATIO_NONE;
content+=4;
} else if (strstr(content, "xMinYMin")) {
par->align = SVG_PRESERVEASPECTRATIO_XMINYMIN;
content+=8;
} else if (strstr(content, "xMidYMin")) {
par->align = SVG_PRESERVEASPECTRATIO_XMIDYMIN;
content+=8;
} else if (strstr(content, "xMaxYMin")) {
par->align = SVG_PRESERVEASPECTRATIO_XMAXYMIN;
content+=8;
} else if (strstr(content, "xMinYMid")) {
par->align = SVG_PRESERVEASPECTRATIO_XMINYMID;
content+=8;
} else if (strstr(content, "xMidYMid")) {
par->align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
content+=8;
} else if (strstr(content, "xMaxYMid")) {
par->align = SVG_PRESERVEASPECTRATIO_XMAXYMID;
content+=8;
} else if (strstr(content, "xMinYMax")) {
par->align = SVG_PRESERVEASPECTRATIO_XMINYMAX;
content+=8;
} else if (strstr(content, "xMidYMax")) {
par->align = SVG_PRESERVEASPECTRATIO_XMIDYMAX;
content+=8;
} else if (strstr(content, "xMaxYMax")) {
par->align = SVG_PRESERVEASPECTRATIO_XMAXYMAX;
content+=8;
}
while (*content == ' ') content++;
if (*content == 0) return;
if (strstr(content, "meet")) {
par->meetOrSlice = SVG_MEETORSLICE_MEET;
} else if (strstr(content, "slice")) {
par->meetOrSlice = SVG_MEETORSLICE_SLICE;
}
}
static void svg_parse_animatetransform_type(SVG_TransformType *anim_transform_type, char *attribute_content)
{
*anim_transform_type = SVG_TRANSFORM_MATRIX;
if (!strcmp(attribute_content, "scale")) {
*anim_transform_type = SVG_TRANSFORM_SCALE;
} else if (!strcmp(attribute_content, "rotate")) {
*anim_transform_type = SVG_TRANSFORM_ROTATE;
} else if (!strcmp(attribute_content, "translate")) {
*anim_transform_type = SVG_TRANSFORM_TRANSLATE;
} else if (!strcmp(attribute_content, "skewX")) {
*anim_transform_type = SVG_TRANSFORM_SKEWX;
} else if (!strcmp(attribute_content, "skewY")) {
*anim_transform_type = SVG_TRANSFORM_SKEWY;
}
}
static void svg_parse_focushighlight(SVG_FocusHighlight *fh, char *attribute_content)
{
if (!strcmp(attribute_content, "auto")) {
*fh = SVG_FOCUSHIGHLIGHT_AUTO;
} else if (!strcmp(attribute_content, "none")) {
*fh = SVG_FOCUSHIGHLIGHT_NONE;
}
}
static void svg_parse_focusable(SVG_Focusable *f, char *attribute_content)
{
if (!strcmp(attribute_content, "true")) {
*f = SVG_FOCUSABLE_TRUE;
} else if (!strcmp(attribute_content, "false")) {
*f = SVG_FOCUSABLE_FALSE;
} else {
*f = SVG_FOCUSABLE_AUTO;
}
}
static void svg_parse_initialvisibility(SVG_InitialVisibility *iv, char *attribute_content)
{
if (!strcmp(attribute_content, "whenStarted")) {
*iv = SVG_INITIALVISIBILTY_WHENSTARTED;
} else if (!strcmp(attribute_content, "always")) {
*iv = SVG_INITIALVISIBILTY_ALWAYS;
}
}
static void svg_parse_overlay(SVG_Overlay *o, char *attribute_content)
{
if (!strcmp(attribute_content, "none")) {
*o = SVG_OVERLAY_NONE;
} else if (!strcmp(attribute_content, "top")) {
*o = SVG_OVERLAY_TOP;
}
}
static void svg_parse_transformbehavior(SVG_TransformBehavior *tb, char *attribute_content)
{
if (!strcmp(attribute_content, "geometric")) {
*tb = SVG_TRANSFORMBEHAVIOR_GEOMETRIC;
} else if (!strcmp(attribute_content, "pinned")) {
*tb = SVG_TRANSFORMBEHAVIOR_PINNED;
} else if (!strcmp(attribute_content, "pinned90")) {
*tb = SVG_TRANSFORMBEHAVIOR_PINNED90;
} else if (!strcmp(attribute_content, "pinned180")) {
*tb = SVG_TRANSFORMBEHAVIOR_PINNED180;
} else if (!strcmp(attribute_content, "pinned270")) {
*tb = SVG_TRANSFORMBEHAVIOR_PINNED270;
}
}
static void svg_parse_focus(GF_Node *e, SVG_Focus *o, char *attribute_content)
{
if (o->target.string) gf_free(o->target.string);
o->target.string = NULL;
o->target.target = NULL;
if (!strcmp(attribute_content, "self")) o->type = SVG_FOCUS_SELF;
else if (!strcmp(attribute_content, "auto")) o->type = SVG_FOCUS_AUTO;
else if (!strnicmp(attribute_content, "url(", 4)) {
char *sep = strrchr(attribute_content, ')');
if (sep) sep[0] = 0;
o->type = SVG_FOCUS_IRI;
svg_parse_iri(e, &o->target, attribute_content+4);
if (sep) sep[0] = ')';
}
}
/* end of Basic SVG datatype parsing functions */
void svg_parse_one_anim_value(GF_Node *n, SMIL_AnimateValue *anim_value, char *attribute_content, u8 anim_value_type)
{
GF_FieldInfo info;
info.fieldType = anim_value_type;
info.far_ptr = gf_svg_create_attribute_value(anim_value_type);
if (info.far_ptr) gf_svg_parse_attribute(n, &info, attribute_content, 0);
anim_value->value = info.far_ptr;
anim_value->type = anim_value_type;
}
void svg_parse_anim_values(GF_Node *n, SMIL_AnimateValues *anim_values, char *anim_values_string, u8 anim_value_type)
{
u32 i = 0;
char *str;
s32 psemi = -1;
GF_FieldInfo info;
info.fieldType = anim_value_type;
anim_values->type = anim_value_type;
str = anim_values_string;
while (1) {
if (str[i] == ';' || str[i] == 0) {
u32 single_value_len = 0;
char c;
single_value_len = i - (psemi+1);
c = str [ (psemi+1) + single_value_len];
str [ (psemi+1) + single_value_len] = 0;
info.far_ptr = gf_svg_create_attribute_value(anim_value_type);
if (info.far_ptr) {
gf_svg_parse_attribute(n, &info, str + (psemi+1), anim_value_type);
gf_list_add(anim_values->values, info.far_ptr);
}
str [ (psemi+1) + single_value_len] = c;
psemi = i;
if (!str[i]) return;
}
i++;
}
}
GF_Err laser_parse_choice(LASeR_Choice *choice, char *attribute_content)
{
if (!strcmp(attribute_content, "none")) {
choice->type = LASeR_CHOICE_NONE;
} else if (!strcmp(attribute_content, "all")) {
choice->type = LASeR_CHOICE_ALL;
} else {
choice->type = LASeR_CHOICE_N;
choice->choice_index = atoi(attribute_content);
}
return GF_OK;
}
GF_Err laser_parse_size(LASeR_Size *size, char *attribute_content)
{
char *str = attribute_content;
u32 i = 0;
i+=svg_parse_number(&(str[i]), &(size->width), 0);
/*i+=*/ svg_parse_number(&(str[i]), &(size->height), 0);
return GF_OK;
}
GF_Err gf_svg_parse_element_id(GF_Node *n, const char *nodename, Bool warning_if_defined)
{
GF_SceneGraph *sg = gf_node_get_graph((GF_Node *)n);
u32 id = gf_sg_get_max_node_id(sg) + 1;
gf_node_set_id(n, id, nodename);
return GF_OK;
}
/* Parse an SVG attribute */
GF_EXPORT
GF_Err gf_svg_parse_attribute(GF_Node *n, GF_FieldInfo *info, char *attribute_content, u8 anim_value_type)
{
/* for all attributes, except strings, apply some sort of white space normalization*/
if (info->fieldType != DOM_String_datatype && strlen(attribute_content)) {
u32 i, len;
/*remove spaces at the beginning*/
while (attribute_content[0] && (strchr("\r\n\t ", attribute_content[0])))
attribute_content++;
/*change all special chars in spaces*/
i=0;
len = (u32) strlen(attribute_content);
while (i<len) {
if (strchr("\r\n\t", attribute_content[i]))
attribute_content[i] = ' ';
i++;
}
/*remove spaces in the end*/
while (len && attribute_content[len-1]==' ') {
attribute_content[len-1] = 0;
len--;
}
}
switch (info->fieldType) {
case SVG_Boolean_datatype:
svg_parse_boolean((SVG_Boolean *)info->far_ptr, attribute_content);
break;
case SVG_Color_datatype:
svg_parse_color((SVG_Color *)info->far_ptr, attribute_content);
break;
case SVG_Paint_datatype:
svg_parse_paint(n, (SVG_Paint *)info->far_ptr, attribute_content);
break;
/* beginning of keyword type parsing */
case SVG_FillRule_datatype:
svg_parse_clipfillrule((SVG_FillRule *)info->far_ptr, attribute_content);
break;
case SVG_StrokeLineJoin_datatype:
svg_parse_strokelinejoin((SVG_StrokeLineJoin *)info->far_ptr, attribute_content);
break;
case SVG_StrokeLineCap_datatype:
svg_parse_strokelinecap((SVG_StrokeLineCap *)info->far_ptr, attribute_content);
break;
case SVG_FontStyle_datatype:
svg_parse_fontstyle((SVG_FontStyle *)info->far_ptr, attribute_content);
break;
case SVG_FontWeight_datatype:
svg_parse_fontweight((SVG_FontWeight *)info->far_ptr, attribute_content);
break;
case SVG_FontVariant_datatype:
svg_parse_fontvariant((SVG_FontVariant *)info->far_ptr, attribute_content);
break;
case SVG_TextAnchor_datatype:
svg_parse_textanchor((SVG_TextAnchor *)info->far_ptr, attribute_content);
break;
case SVG_Display_datatype:
svg_parse_display((SVG_Display *)info->far_ptr, attribute_content);
break;
case SVG_Visibility_datatype:
svg_parse_visibility((SVG_Visibility *)info->far_ptr, attribute_content);
break;
case SVG_Overflow_datatype:
svg_parse_overflow((SVG_Overflow *)info->far_ptr, attribute_content);
break;
case SVG_ZoomAndPan_datatype:
svg_parse_zoomandpan((SVG_ZoomAndPan *)info->far_ptr, attribute_content);
break;
case SVG_DisplayAlign_datatype:
svg_parse_displayalign((SVG_DisplayAlign *)info->far_ptr, attribute_content);
break;
case SVG_TextAlign_datatype:
svg_parse_textalign((SVG_TextAlign *)info->far_ptr, attribute_content);
break;
case SVG_PointerEvents_datatype:
svg_parse_pointerevents((SVG_PointerEvents *)info->far_ptr, attribute_content);
break;
case SVG_RenderingHint_datatype:
svg_parse_renderinghint((SVG_RenderingHint *)info->far_ptr, attribute_content);
break;
case SVG_VectorEffect_datatype:
svg_parse_vectoreffect((SVG_VectorEffect *)info->far_ptr, attribute_content);
break;
case SVG_PlaybackOrder_datatype:
svg_parse_playbackorder((SVG_PlaybackOrder *)info->far_ptr, attribute_content);
break;
case SVG_TimelineBegin_datatype:
svg_parse_timelinebegin((SVG_TimelineBegin *)info->far_ptr, attribute_content);
break;
case XML_Space_datatype:
svg_parse_xmlspace((XML_Space *)info->far_ptr, attribute_content);
break;
case XMLEV_Propagate_datatype:
svg_parse_xmlev_propagate((XMLEV_Propagate *)info->far_ptr, attribute_content);
break;
case XMLEV_DefaultAction_datatype:
svg_parse_xmlev_defaultAction((XMLEV_DefaultAction *)info->far_ptr, attribute_content);
break;
case XMLEV_Phase_datatype:
svg_parse_xmlev_phase((XMLEV_Phase *)info->far_ptr, attribute_content);
break;
case SMIL_SyncBehavior_datatype:
smil_parse_syncBehaviorOrDefault((SMIL_SyncBehavior *)info->far_ptr, attribute_content);
break;
case SMIL_SyncTolerance_datatype:
smil_parse_syncToleranceOrDefault((SMIL_SyncTolerance *)info->far_ptr, attribute_content);
break;
case SMIL_AttributeType_datatype:
smil_parse_attributeType((SMIL_AttributeType *)info->far_ptr, attribute_content);
break;
case SMIL_CalcMode_datatype:
smil_parse_calcmode((SMIL_CalcMode *)info->far_ptr, attribute_content);
break;
case SMIL_Additive_datatype:
smil_parse_additive((SMIL_CalcMode *)info->far_ptr, attribute_content);
break;
case SMIL_Accumulate_datatype:
smil_parse_accumulate((SMIL_Accumulate *)info->far_ptr, attribute_content);
break;
case SMIL_Restart_datatype:
smil_parse_restart((SMIL_Restart *)info->far_ptr, attribute_content);
break;
case SMIL_Fill_datatype:
smil_parse_fill((SMIL_Fill *)info->far_ptr, attribute_content);
break;
case SVG_GradientUnit_datatype:
*((SVG_GradientUnit *)info->far_ptr) = !strcmp(attribute_content, "userSpaceOnUse") ? SVG_GRADIENTUNITS_USER : SVG_GRADIENTUNITS_OBJECT;
break;
case SVG_FocusHighlight_datatype:
svg_parse_focushighlight((SVG_FocusHighlight*)info->far_ptr, attribute_content);
break;
case SVG_Focusable_datatype:
svg_parse_focusable((SVG_Focusable*)info->far_ptr, attribute_content);
break;
case SVG_InitialVisibility_datatype:
svg_parse_initialvisibility((SVG_InitialVisibility*)info->far_ptr, attribute_content);
break;
case SVG_Overlay_datatype:
svg_parse_overlay((SVG_Overlay*)info->far_ptr, attribute_content);
break;
case SVG_TransformBehavior_datatype:
svg_parse_transformbehavior((SVG_TransformBehavior*)info->far_ptr, attribute_content);
break;
case SVG_SpreadMethod_datatype:
if (!strcmp(attribute_content, "reflect")) *(u8*)info->far_ptr = SVG_SPREAD_REFLECT;
else if (!strcmp(attribute_content, "repeat")) *(u8*)info->far_ptr = SVG_SPREAD_REPEAT;
else *(u8*)info->far_ptr = SVG_SPREAD_PAD;
break;
case SVG_Filter_TransferType_datatype:
if (!strcmp(attribute_content, "table")) *(u8*)info->far_ptr = SVG_FILTER_TRANSFER_TABLE;
else if (!strcmp(attribute_content, "discrete")) *(u8*)info->far_ptr = SVG_FILTER_TRANSFER_DISCRETE;
else if (!strcmp(attribute_content, "linear")) *(u8*)info->far_ptr = SVG_FILTER_TRANSFER_LINEAR;
else if (!strcmp(attribute_content, "gamma")) *(u8*)info->far_ptr = SVG_FILTER_TRANSFER_GAMMA;
else *(u8*)info->far_ptr = SVG_FILTER_TRANSFER_IDENTITY;
break;
/* end of keyword type parsing */
/* keyword | numbers (with possibly units) */
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_FontSize_datatype:
case SVG_Rotate_datatype:
case SVG_Number_datatype:
svg_parse_length((SVG_Number*)info->far_ptr, attribute_content, 0);
break;
case SMIL_AnimateValue_datatype:
svg_parse_one_anim_value(n, (SMIL_AnimateValue*)info->far_ptr, attribute_content, anim_value_type);
break;
case SMIL_AnimateValues_datatype:
svg_parse_anim_values(n, (SMIL_AnimateValues*)info->far_ptr, attribute_content, anim_value_type);
break;
case XMLRI_datatype:
svg_parse_iri(n, (XMLRI*)info->far_ptr, attribute_content);
break;
case XML_IDREF_datatype:
svg_parse_idref(n, (XMLRI*)info->far_ptr, attribute_content);
break;
case SMIL_AttributeName_datatype:
((SMIL_AttributeName *)info->far_ptr)->name = gf_strdup(attribute_content);
break;
case SMIL_Times_datatype:
smil_parse_time_list(n, *(GF_List **)info->far_ptr, attribute_content);
break;
case SMIL_Duration_datatype:
smil_parse_min_max_dur_repeatdur((SMIL_Duration*)info->far_ptr, attribute_content);
break;
case SMIL_RepeatCount_datatype:
smil_parse_repeatcount((SMIL_RepeatCount*)info->far_ptr, attribute_content);
break;
case SVG_PathData_datatype:
svg_parse_path((SVG_PathData*)info->far_ptr, attribute_content);
break;
case SVG_Points_datatype:
svg_parse_points(*(GF_List **)(info->far_ptr), attribute_content);
break;
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
case SVG_Numbers_datatype:
svg_parse_numbers(*(GF_List **)(info->far_ptr), attribute_content, 0);
break;
case SVG_Coordinates_datatype:
svg_parse_coordinates(*(GF_List **)(info->far_ptr), attribute_content);
break;
case SVG_ViewBox_datatype:
svg_parse_viewbox((SVG_ViewBox*)info->far_ptr, attribute_content);
break;
case SVG_StrokeDashArray_datatype:
svg_parse_strokedasharray((SVG_StrokeDashArray*)info->far_ptr, attribute_content);
break;
case SVG_FontFamily_datatype:
svg_parse_fontfamily((SVG_FontFamily*)info->far_ptr, attribute_content);
break;
case SVG_Motion_datatype:
svg_parse_point_into_matrix((GF_Matrix2D*)info->far_ptr, attribute_content);
break;
case SVG_Transform_datatype:
svg_parse_transform((SVG_Transform*)info->far_ptr, attribute_content);
break;
case SVG_Transform_Translate_datatype:
{
u32 i = 0;
SVG_Point *p = (SVG_Point *)info->far_ptr;;
i+=svg_parse_number(&(attribute_content[i]), &(p->x), 0);
if (attribute_content[i] == 0) {
p->y = 0;
} else {
/*i+=*/svg_parse_number(&(attribute_content[i]), &(p->y), 0);
}
}
break;
case SVG_Transform_Scale_datatype:
{
u32 i = 0;
SVG_Point *p = (SVG_Point *)info->far_ptr;;
i+=svg_parse_number(&(attribute_content[i]), &(p->x), 0);
if (attribute_content[i] == 0) {
p->y = p->x;
} else {
/*i+=*/svg_parse_number(&(attribute_content[i]), &(p->y), 0);
}
}
break;
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
{
Fixed *p = (Fixed *)info->far_ptr;
svg_parse_number(attribute_content, p, 1);
}
break;
case SVG_Transform_Rotate_datatype:
{
u32 i = 0;
SVG_Point_Angle *p = (SVG_Point_Angle *)info->far_ptr;;
i+=svg_parse_number(&(attribute_content[i]), &(p->angle), 1);
if (attribute_content[i] == 0) {
p->y = p->x = 0;
} else {
i+=svg_parse_number(&(attribute_content[i]), &(p->x), 0);
/*i+=*/svg_parse_number(&(attribute_content[i]), &(p->y), 0);
}
}
break;
case SVG_PreserveAspectRatio_datatype:
svg_parse_preserveaspectratio((SVG_PreserveAspectRatio*)info->far_ptr, attribute_content);
break;
case SVG_TransformType_datatype:
svg_parse_animatetransform_type((SVG_TransformType*)info->far_ptr, attribute_content);
break;
case SVG_ID_datatype:
case DOM_String_datatype:
case SVG_ContentType_datatype:
case SVG_LanguageID_datatype:
if (*(SVG_String *)info->far_ptr) gf_free(*(SVG_String *)info->far_ptr);
*(SVG_String *)info->far_ptr = gf_strdup(attribute_content);
break;
case DOM_StringList_datatype:
svg_parse_strings(*(GF_List **)info->far_ptr, attribute_content, 0);
break;
case XMLRI_List_datatype:
svg_parse_strings(*(GF_List **)info->far_ptr, attribute_content, 1);
break;
case XMLEV_Event_datatype:
{
XMLEV_Event *xml_ev = (XMLEV_Event *)info->far_ptr;
char *sep = strchr(attribute_content, '(');
if (sep) {
sep[0] = 0;
xml_ev->type = gf_dom_event_type_by_name(attribute_content);
sep[0] = '(';
if ((xml_ev->type == GF_EVENT_REPEAT) || (xml_ev->type == GF_EVENT_REPEAT_EVENT)) {
char _v;
sscanf(sep, "(%c)", &_v);
xml_ev->parameter = _v;
} else { /* key events ... */
char *sep2 = strchr(attribute_content, ')');
sep2[0] = 0;
xml_ev->parameter = gf_dom_get_key_type(sep+1);
sep2[0] = ')';
}
} else {
xml_ev->parameter = 0;
xml_ev->type = gf_dom_event_type_by_name(attribute_content);
}
}
break;
case SVG_Focus_datatype:
svg_parse_focus(n, (SVG_Focus*)info->far_ptr, attribute_content);
break;
case LASeR_Choice_datatype:
laser_parse_choice((LASeR_Choice*)info->far_ptr, attribute_content);
break;
case LASeR_Size_datatype:
laser_parse_size((LASeR_Size*)info->far_ptr, attribute_content);
break;
case SVG_Clock_datatype:
svg_parse_clock_value(attribute_content, (SVG_Clock*)info->far_ptr);
break;
case SVG_Unknown_datatype:
if (*(SVG_String *)info->far_ptr) gf_free(*(SVG_String *)info->far_ptr);
*(SVG_String *)info->far_ptr = gf_strdup(attribute_content);
break;
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Parsing] Cannot parse attribute %s\n", info->name, gf_svg_attribute_type_to_string(info->fieldType)));
break;
}
return GF_OK;
}
void svg_parse_one_style(GF_Node *n, char *one_style)
{
GF_FieldInfo info;
char *c, sep;
u32 attributeNameLen;
while (*one_style == ' ') one_style++;
c = strchr(one_style, ':');
if (!c) return;
attributeNameLen = (u32) (c - one_style);
sep = one_style[attributeNameLen];
one_style[attributeNameLen] = 0;
while (strchr("\r\n\t ", one_style[0]))
one_style++;
if (!gf_node_get_field_by_name(n, one_style, &info)) {
c++;
gf_svg_parse_attribute(n, &info, c, 0);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Attribute %s does not belong to element %s.\n", one_style, gf_node_get_class_name(n)));
}
one_style[attributeNameLen] = sep;
}
void gf_svg_parse_style(GF_Node *n, char *style)
{
u32 i = 0;
char *str = style;
s32 psemi = -1;
while (1) {
if (str[i] == ';' || str[i] == 0) {
u32 single_value_len = 0;
single_value_len = i - (psemi+1);
if (single_value_len) {
char c = str[psemi+1 + single_value_len];
str[psemi+1 + single_value_len] = 0;
svg_parse_one_style(n, str + psemi+1);
str[psemi+1 + single_value_len] = c;
psemi = i;
}
if (!str[i]) return;
}
i++;
}
}
GF_EXPORT
void *gf_svg_create_attribute_value(u32 attribute_type)
{
switch (attribute_type) {
case SVG_Boolean_datatype:
{
SVG_Boolean *b;
GF_SAFEALLOC(b, SVG_Boolean)
return b;
}
break;
case SVG_Color_datatype:
{
SVG_Color *color;
GF_SAFEALLOC(color, SVG_Color)
return color;
}
break;
case SVG_Paint_datatype:
{
SVG_Paint *paint;
GF_SAFEALLOC(paint, SVG_Paint)
return paint;
}
break;
/* keyword types */
case SVG_FillRule_datatype:
case SVG_StrokeLineJoin_datatype:
case SVG_StrokeLineCap_datatype:
case SVG_FontStyle_datatype:
case SVG_FontWeight_datatype:
case SVG_FontVariant_datatype:
case SVG_TextAnchor_datatype:
case SVG_Display_datatype:
case SVG_Visibility_datatype:
case SVG_Overflow_datatype:
case SVG_ZoomAndPan_datatype:
case SVG_DisplayAlign_datatype:
case SVG_TextAlign_datatype:
case SVG_PointerEvents_datatype:
case SVG_RenderingHint_datatype:
case SVG_VectorEffect_datatype:
case SVG_PlaybackOrder_datatype:
case SVG_TimelineBegin_datatype:
case XML_Space_datatype:
case XMLEV_Propagate_datatype:
case XMLEV_DefaultAction_datatype:
case XMLEV_Phase_datatype:
case SMIL_SyncBehavior_datatype:
case SMIL_AttributeType_datatype:
case SMIL_CalcMode_datatype:
case SMIL_Additive_datatype:
case SMIL_Accumulate_datatype:
case SMIL_Restart_datatype:
case SMIL_Fill_datatype:
case SVG_TransformType_datatype:
case SVG_FocusHighlight_datatype:
case SVG_InitialVisibility_datatype:
case SVG_GradientUnit_datatype:
case SVG_Overlay_datatype:
case SVG_TransformBehavior_datatype:
case SVG_SpreadMethod_datatype:
case SVG_Focusable_datatype:
case SVG_Filter_TransferType_datatype:
{
u8 *keyword;
GF_SAFEALLOC(keyword, u8)
return keyword;
}
break;
case SMIL_SyncTolerance_datatype:
{
SMIL_SyncTolerance *st;
GF_SAFEALLOC(st, SMIL_SyncTolerance)
return st;
}
break;
/* inheritable floats */
case SVG_FontSize_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_Rotate_datatype:
case SVG_Number_datatype:
{
SVG_Number *number;
GF_SAFEALLOC(number, SVG_Number)
return number;
}
break;
case SVG_StrokeDashArray_datatype:
{
SVG_StrokeDashArray *array;
GF_SAFEALLOC(array, SVG_StrokeDashArray)
return array;
}
break;
case SVG_Motion_datatype:
{
GF_Matrix2D *p;
GF_SAFEALLOC(p, GF_Matrix2D)
gf_mx2d_init(*p);
return p;
}
break;
case SVG_Transform_datatype:
{
SVG_Transform *p;
GF_SAFEALLOC(p, SVG_Transform)
gf_mx2d_init(p->mat);
return p;
}
break;
case SVG_Transform_Translate_datatype:
case SVG_Transform_Scale_datatype:
{
SVG_Point *p;
GF_SAFEALLOC(p, SVG_Point)
return p;
}
break;
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
{
Fixed *p;
GF_SAFEALLOC(p, Fixed)
return p;
}
break;
case SVG_Transform_Rotate_datatype:
{
SVG_Point_Angle *p;
GF_SAFEALLOC(p, SVG_Point_Angle)
return p;
}
break;
case SVG_ViewBox_datatype:
{
SVG_ViewBox *viewbox;
GF_SAFEALLOC(viewbox, SVG_ViewBox)
return viewbox;
}
break;
case XMLRI_datatype:
case XML_IDREF_datatype:
{
XMLRI *iri;
GF_SAFEALLOC(iri, XMLRI)
return iri;
}
break;
case SVG_FontFamily_datatype:
{
SVG_FontFamily *fontfamily;
GF_SAFEALLOC(fontfamily, SVG_FontFamily)
return fontfamily;
}
break;
case DOM_String_datatype:
case SVG_ContentType_datatype:
case SVG_LanguageID_datatype:
case SVG_ID_datatype:
{
SVG_String *string;
GF_SAFEALLOC(string, SVG_String)
return string;
}
break;
case DOM_StringList_datatype:
case XMLRI_List_datatype:
case SVG_Points_datatype:
case SVG_Coordinates_datatype:
case SMIL_Times_datatype:
case SMIL_KeySplines_datatype:
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SVG_Numbers_datatype:
{
ListOfXXX *list;
GF_SAFEALLOC(list, ListOfXXX)
if (list) *list = gf_list_new();
return list;
}
break;
case SVG_PreserveAspectRatio_datatype:
{
SVG_PreserveAspectRatio *par;
GF_SAFEALLOC(par, SVG_PreserveAspectRatio)
return par;
}
break;
case SVG_PathData_datatype:
{
SVG_PathData *path;
GF_SAFEALLOC(path, SVG_PathData);
if (!path) return NULL;
#if USE_GF_PATH
gf_path_reset(path);
path->fineness = FIX_ONE;
#else
path->commands = gf_list_new();
path->points = gf_list_new();
#endif
return path;
}
break;
case LASeR_Choice_datatype:
{
LASeR_Choice *ch;
GF_SAFEALLOC(ch, LASeR_Choice)
return ch;
}
case SVG_Focus_datatype:
{
SVG_Focus *foc;
GF_SAFEALLOC(foc, SVG_Focus)
return foc;
}
case SMIL_AttributeName_datatype:
{
SMIL_AttributeName *an;
GF_SAFEALLOC(an, SMIL_AttributeName)
return an;
}
case SMIL_RepeatCount_datatype:
{
SMIL_RepeatCount *rc;
GF_SAFEALLOC(rc, SMIL_RepeatCount)
return rc;
}
case SMIL_Duration_datatype:
{
SMIL_Duration *sd;
GF_SAFEALLOC(sd, SMIL_Duration)
return sd;
}
case SMIL_AnimateValue_datatype:
{
SMIL_AnimateValue *av;
GF_SAFEALLOC(av, SMIL_AnimateValue)
return av;
}
break;
case SMIL_AnimateValues_datatype:
{
SMIL_AnimateValues *av;
GF_SAFEALLOC(av, SMIL_AnimateValues)
if (!av) return NULL;
av->values = gf_list_new();
return av;
}
break;
case SVG_Clock_datatype:
{
SVG_Clock *ck;
GF_SAFEALLOC(ck, SVG_Clock)
return ck;
}
break;
case XMLEV_Event_datatype:
{
XMLEV_Event *e;
GF_SAFEALLOC(e, XMLEV_Event);
return e;
}
break;
case LASeR_Size_datatype:
{
LASeR_Size *s;
GF_SAFEALLOC(s, LASeR_Size);
return s;
}
break;
case 0:
{
SVG_String *string;
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Attributes] Unspecified attribute type - defaulting to string.\n"));
GF_SAFEALLOC(string, SVG_String);
return string;
}
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Attributes] Cannot create attribute value: Type %s not supported.\n", gf_svg_attribute_type_to_string(attribute_type)));
break;
}
return NULL;
}
static char *svg_dump_color(SVG_Color *col)
{
char *res;
if (col->type == SVG_COLOR_CURRENTCOLOR) return gf_strdup("currentColor");
else if (col->type == SVG_COLOR_INHERIT) return gf_strdup("inherit");
else if (col->type !=SVG_COLOR_RGBCOLOR) {
u32 i, count;
count = sizeof(system_colors) / sizeof(struct sys_col);
for (i=0; i<count; i++) {
if (col->type == system_colors[i].type) {
return gf_strdup(system_colors[i].name);
}
}
} else {
u8 r, g, b;
const char *name;
r = FIX2INT(255*col->red);
g = FIX2INT(255*col->green);
b = FIX2INT(255*col->blue);
name = gf_color_get_name( GF_COL_ARGB(0xFF, r, g, b) );
if (name) return gf_strdup(name);
res = gf_malloc(sizeof(char)*8);
sprintf(res, "#%02X%02X%02X", r, g, b);
/*compress it...*/
if ( (res[1]==res[2]) && (res[3]==res[4]) && (res[5]==res[6]) )
sprintf(res, "#%c%c%c", res[1], res[3], res[5]);
return res;
}
return NULL;
}
static char *svg_dump_number(SVG_Number *l)
{
char tmp[100];
if (l->type==SVG_NUMBER_INHERIT) return gf_strdup("inherit");
else if (l->type == SVG_NUMBER_AUTO) return gf_strdup("auto");
else if (l->type == SVG_NUMBER_AUTO_REVERSE) return gf_strdup("auto-reverse");
else {
sprintf(tmp, "%g", FIX2FLT(l->value) );
if (l->type == SVG_NUMBER_PERCENTAGE) strcat(tmp, "%");
else if (l->type == SVG_NUMBER_EMS) strcat(tmp, "em");
else if (l->type == SVG_NUMBER_EXS) strcat(tmp, "ex");
else if (l->type == SVG_NUMBER_PX) strcat(tmp, "px");
else if (l->type == SVG_NUMBER_CM) strcat(tmp, "cm");
else if (l->type == SVG_NUMBER_MM) strcat(tmp, "mm");
else if (l->type == SVG_NUMBER_IN) strcat(tmp, "in");
else if (l->type == SVG_NUMBER_PT) strcat(tmp, "pt");
else if (l->type == SVG_NUMBER_PC) strcat(tmp, "pc");
return gf_strdup(tmp);
}
}
static char *svg_dump_iri(XMLRI*iri)
{
if (iri->type == XMLRI_ELEMENTID) {
const char *name;
char *res;
name = gf_node_get_name((GF_Node *)iri->target);
if (name) {
res = gf_malloc(sizeof(char)*(strlen(name)+2));
sprintf(res, "#%s", name);
} else if (iri->target) {
res = gf_malloc(sizeof(char)*32);
sprintf(res, "#N%d", gf_node_get_id((GF_Node *)iri->target) - 1);
} else {
res = gf_strdup("");
}
return res;
}
else if ((iri->type == XMLRI_STRING) && iri->string)
return gf_strdup(iri->string);
else
return gf_strdup("");
}
static char *svg_dump_idref(XMLRI*iri)
{
const char *name;
if (iri->target) {
name = gf_node_get_name((GF_Node *)iri->target);
if (name) return gf_strdup(name);
else {
char tmp[50];
sprintf(tmp, "N%d", gf_node_get_id((GF_Node *)iri->target) - 1);
return gf_strdup(tmp);
}
}
if (iri->string) return gf_strdup(iri->string);
return gf_strdup("");
}
#if USE_GF_PATH
static char *svg_dump_path(SVG_PathData *path)
{
char szT[1000];
GF_Point2D *pt, last_pt, *ct1, *ct2, *end;
u32 i, *contour;
char *res = gf_malloc(sizeof(char));
res[0] = 0;
contour = path->contours;
last_pt.x = last_pt.y = 0;
for (i=0; i<path->n_points; ) {
szT[0] = 0;
switch (path->tags[i]) {
case GF_PATH_CURVE_ON:
case GF_PATH_CLOSE:
pt = &path->points[i];
if (!i || (*contour == i-1) ) {
sprintf(szT, "M%g %g", FIX2FLT(pt->x), FIX2FLT(pt->y));
if (i) contour++;
} else if (path->tags[i]==GF_PATH_CLOSE) {
sprintf(szT, "z");
} else {
if (i && (last_pt.x==pt->x)) sprintf(szT, "V%g", FIX2FLT(pt->y));
else if (i && (last_pt.y==pt->y)) sprintf(szT, "H%g", FIX2FLT(pt->x));
else sprintf(szT, "L%g %g", FIX2FLT(pt->x), FIX2FLT(pt->y));
}
last_pt = *pt;
i++;
break;
case GF_PATH_CURVE_CONIC:
ct1 = &path->points[i];
end = &path->points[i+1];
sprintf(szT, "Q%g %g %g %g", FIX2FLT(ct1->x), FIX2FLT(ct1->y), FIX2FLT(end->x), FIX2FLT(end->y));
last_pt = *end;
if (path->tags[i+2]==GF_PATH_CLOSE) {
strcat(szT, "z");
}
i+=2;
break;
case GF_PATH_CURVE_CUBIC:
ct1 = &path->points[i];
ct2 = &path->points[i+1];
end = &path->points[i+2];
sprintf(szT, "C%g %g %g %g %g %g", FIX2FLT(ct1->x), FIX2FLT(ct1->y), FIX2FLT(ct2->x), FIX2FLT(ct2->y), FIX2FLT(end->x), FIX2FLT(end->y));
last_pt = *end;
if (path->tags[i+2]==GF_PATH_CLOSE) {
strcat(szT, "z");
}
i+=3;
break;
}
if (szT[0]) {
res = gf_realloc(res, sizeof(char)*(strlen(szT)+strlen(res)+1));
strcat(res, szT);
}
}
return res;
}
#else
static void svg_dump_point(SVG_Point *pt, char *attValue)
{
if (pt) sprintf(attValue, "%g %g ", FIX2FLT(pt->x), FIX2FLT(pt->y) );
}
static void svg_dump_path(SVG_PathData *path, char *attValue)
{
char szT[1000];
u32 i, pt_i, count;
count = gf_list_count(path->commands);
pt_i = 0;
strcpy(attValue, "");
for (i = 0; i < count; i++) {
u8 command = *(u8 *)gf_list_get(path->commands, i);
switch(command) {
case SVG_PATHCOMMAND_M:
strcat(attValue, "M");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_L:
strcat(attValue, "L");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_C:
strcat(attValue, "C");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_S:
strcat(attValue, "S");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_Q:
strcat(attValue, "Q");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_T:
strcat(attValue, "T");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_A:
strcat(attValue, "A");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
strcat(attValue, "0 0 0 ");
svg_dump_point((SVG_Point*)gf_list_get(path->points, pt_i), szT);
strcat(attValue, szT);
pt_i++;
break;
case SVG_PATHCOMMAND_Z:
strcat(attValue, "Z");
break;
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Dumping] unknown path command %d\n", command));
break;
}
}
}
#endif
static void svg_dump_access_key(XMLEV_Event *evt, char *attValue)
{
u32 i, count;
strcpy(attValue, "accessKey(");
count = sizeof(predefined_key_identifiers) / sizeof(struct predef_keyid);
for (i=0; i<count; i++) {
if (evt->parameter == predefined_key_identifiers[i].key_code) {
strcat(attValue, predefined_key_identifiers[i].name);
break;
}
}
/* OLD LASeR CODE
switch (evt->parameter) {
case 0: strcat(attValue, "UP"); break;
case 1: strcat(attValue, "DOWN"); break;
case 2: strcat(attValue, "LEFT"); break;
case 3: strcat(attValue, "RIGHT"); break;
case 4: strcat(attValue, "FIRE"); break;
case 5: strcat(attValue, "NO_KEY"); break;
case 6: strcat(attValue, "ANY_KEY"); break;
case 7: strcat(attValue, "SOFT_KEY_1"); break;
case 8: strcat(attValue, "SOFT_KEY_2"); break;
case 35: strcat(attValue, "#"); break;
case 42: strcat(attValue, "*"); break;
case 48: strcat(attValue, "0"); break;
case 49: strcat(attValue, "1"); break;
case 50: strcat(attValue, "2"); break;
case 51: strcat(attValue, "3"); break;
case 52: strcat(attValue, "4"); break;
case 53: strcat(attValue, "5"); break;
case 54: strcat(attValue, "6"); break;
case 55: strcat(attValue, "7"); break;
case 56: strcat(attValue, "8"); break;
case 57: strcat(attValue, "9"); break;
*/
strcat(attValue, ")");
}
static char *gf_svg_dump_matrix(GF_Matrix2D *matrix)
{
char attValue[1024];
attValue[0]=0;
/*try to do a simple decomposition...*/
if (!matrix->m[1] && !matrix->m[3]) {
if (matrix->m[2] != 0 || matrix->m[5] != 0) sprintf(attValue, "translate(%g,%g)", FIX2FLT(matrix->m[2]), FIX2FLT(matrix->m[5]) );
if ((matrix->m[0]!=FIX_ONE) || (matrix->m[4]!=FIX_ONE)) {
char szT[1024];
if ((matrix->m[0]==-FIX_ONE) && (matrix->m[4]==-FIX_ONE)) {
strcpy(szT, " rotate(180)");
} else {
sprintf(szT, " scale(%g,%g)", FIX2FLT(matrix->m[0]), FIX2FLT(matrix->m[4]) );
}
strcat(attValue, szT);
}
} else if (matrix->m[1] == - matrix->m[3]) {
Fixed angle = gf_asin(matrix->m[3]);
Fixed cos_a = gf_cos(angle);
if (ABS(cos_a)>FIX_EPSILON) {
Fixed sx, sy;
sx = gf_divfix(matrix->m[0], cos_a);
sy = gf_divfix(matrix->m[4], cos_a);
angle = gf_divfix(180*angle, GF_PI);
if ((sx==sy) && ( ABS(FIX_ONE - ABS(sx) ) < FIX_ONE/100)) {
if (matrix->m[2] != 0 || matrix->m[5] != 0)
sprintf(attValue, "translate(%g,%g) rotate(%g)", FIX2FLT(matrix->m[2]), FIX2FLT(matrix->m[5]), FIX2FLT(gf_divfix(angle*180, GF_PI) ) );
else
sprintf(attValue, "rotate(%g)", FIX2FLT(gf_divfix(angle*180, GF_PI) ) );
} else {
if (matrix->m[2] != 0 || matrix->m[5] != 0)
sprintf(attValue, "translate(%g,%g) scale(%g,%g) rotate(%g)", FIX2FLT(matrix->m[2]), FIX2FLT(matrix->m[5]), FIX2FLT(sx), FIX2FLT(sy), FIX2FLT(gf_divfix(angle*180, GF_PI) ) );
else
sprintf(attValue, "scale(%g,%g) rotate(%g)", FIX2FLT(sx), FIX2FLT(sy), FIX2FLT(gf_divfix(angle*180, GF_PI) ) );
}
} else {
Fixed a = angle;
if (a<0) a += GF_2PI;
if (matrix->m[2] != 0 || matrix->m[5] != 0)
sprintf(attValue, "translate(%g,%g) rotate(%g)", FIX2FLT(matrix->m[2]), FIX2FLT(matrix->m[5]), FIX2FLT(gf_divfix(a*180, GF_PI) ) );
else
sprintf(attValue, "rotate(%g)", FIX2FLT(gf_divfix(a*180, GF_PI) ) );
}
}
/*default*/
if (!strlen(attValue))
sprintf(attValue, "matrix(%g %g %g %g %g %g)", FIX2FLT(matrix->m[0]), FIX2FLT(matrix->m[3]), FIX2FLT(matrix->m[1]), FIX2FLT(matrix->m[4]), FIX2FLT(matrix->m[2]), FIX2FLT(matrix->m[5]) );
return gf_strdup(attValue);
}
char *gf_svg_dump_attribute(GF_Node *elt, GF_FieldInfo *info)
{
char tmp[1024];
u8 intVal;
if (!info->far_ptr) return gf_strdup("");
intVal = *(u8 *)info->far_ptr;
switch (info->fieldType) {
case SVG_Boolean_datatype:
return gf_strdup( *(SVG_Boolean *)info->far_ptr ? "true" : "false");
case SVG_Color_datatype:
return svg_dump_color((SVG_Color *)info->far_ptr);
case SVG_Paint_datatype:
{
SVG_Paint *paint = (SVG_Paint *)info->far_ptr;
if (paint->type == SVG_PAINT_NONE) return gf_strdup("none");
else if (paint->type == SVG_PAINT_INHERIT) return gf_strdup("inherit");
else if (paint->type == SVG_PAINT_URI) {
char *tmp = svg_dump_iri(&paint->iri);
char *res = gf_malloc(sizeof(char)*(strlen(tmp)+6));
sprintf(res, "url(%s)", tmp);
gf_free(tmp);
return res;
} else {
return svg_dump_color(&paint->color);
}
}
break;
/* beginning of keyword type parsing */
case SVG_FillRule_datatype:
if (intVal == SVG_FILLRULE_INHERIT) return gf_strdup("inherit");
else if (intVal == SVG_FILLRULE_NONZERO) return gf_strdup("nonzero");
else return gf_strdup("evenodd");
break;
case SVG_StrokeLineJoin_datatype:
if (intVal==SVG_STROKELINEJOIN_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_STROKELINEJOIN_MITER) return gf_strdup("miter");
else if (intVal==SVG_STROKELINEJOIN_ROUND) return gf_strdup("round");
else if (intVal==SVG_STROKELINEJOIN_BEVEL) return gf_strdup("bevel");
break;
case SVG_StrokeLineCap_datatype:
if (intVal==SVG_STROKELINECAP_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_STROKELINECAP_BUTT) return gf_strdup("butt");
else if (intVal==SVG_STROKELINECAP_ROUND) return gf_strdup("round");
else if (intVal==SVG_STROKELINECAP_SQUARE) return gf_strdup("square");
break;
case SVG_FontStyle_datatype:
if (intVal==SVG_FONTSTYLE_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_FONTSTYLE_NORMAL) return gf_strdup("normal");
else if (intVal==SVG_FONTSTYLE_ITALIC) return gf_strdup("italic");
else if (intVal==SVG_FONTSTYLE_OBLIQUE) return gf_strdup("oblique");
break;
case SVG_FontWeight_datatype:
if (intVal==SVG_FONTWEIGHT_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_FONTWEIGHT_NORMAL) return gf_strdup("normal");
else if (intVal==SVG_FONTWEIGHT_BOLD) return gf_strdup("bold");
else if (intVal==SVG_FONTWEIGHT_BOLDER) return gf_strdup("bolder");
else if (intVal==SVG_FONTWEIGHT_LIGHTER) return gf_strdup("lighter");
else if (intVal==SVG_FONTWEIGHT_100) return gf_strdup("100");
else if (intVal==SVG_FONTWEIGHT_200) return gf_strdup("200");
else if (intVal==SVG_FONTWEIGHT_300) return gf_strdup("300");
else if (intVal==SVG_FONTWEIGHT_400) return gf_strdup("400");
else if (intVal==SVG_FONTWEIGHT_500) return gf_strdup("500");
else if (intVal==SVG_FONTWEIGHT_600) return gf_strdup("600");
else if (intVal==SVG_FONTWEIGHT_700) return gf_strdup("700");
else if (intVal==SVG_FONTWEIGHT_800) return gf_strdup("800");
else if (intVal==SVG_FONTWEIGHT_900) return gf_strdup("900");
break;
case SVG_FontVariant_datatype:
if (intVal==SVG_FONTVARIANT_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_FONTVARIANT_NORMAL) return gf_strdup("normal");
else if (intVal==SVG_FONTVARIANT_SMALLCAPS) return gf_strdup("small-caps");
break;
case SVG_TextAnchor_datatype:
if (intVal==SVG_TEXTANCHOR_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_TEXTANCHOR_START) return gf_strdup("start");
else if (intVal==SVG_TEXTANCHOR_MIDDLE) return gf_strdup("middle");
else if (intVal==SVG_TEXTANCHOR_END) return gf_strdup("end");
break;
case SVG_Display_datatype:
if (intVal==SVG_DISPLAY_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_DISPLAY_NONE) return gf_strdup("none");
else if (intVal==SVG_DISPLAY_INLINE) return gf_strdup("inline");
else if (intVal==SVG_DISPLAY_BLOCK) return gf_strdup("block");
else if (intVal==SVG_DISPLAY_LIST_ITEM) return gf_strdup("list-item");
else if (intVal==SVG_DISPLAY_RUN_IN) return gf_strdup("run-in");
else if (intVal==SVG_DISPLAY_COMPACT) return gf_strdup("compact");
else if (intVal==SVG_DISPLAY_MARKER) return gf_strdup("marker");
else if (intVal==SVG_DISPLAY_TABLE) return gf_strdup("table");
else if (intVal==SVG_DISPLAY_INLINE_TABLE) return gf_strdup("inline-table");
else if (intVal==SVG_DISPLAY_TABLE_ROW_GROUP) return gf_strdup("table-row-group");
else if (intVal==SVG_DISPLAY_TABLE_HEADER_GROUP) return gf_strdup("table-header-group");
else if (intVal==SVG_DISPLAY_TABLE_FOOTER_GROUP) return gf_strdup("table-footer-group");
else if (intVal==SVG_DISPLAY_TABLE_ROW) return gf_strdup("table-row");
else if (intVal==SVG_DISPLAY_TABLE_COLUMN_GROUP) return gf_strdup("table-column-group");
else if (intVal==SVG_DISPLAY_TABLE_COLUMN) return gf_strdup("table-column");
else if (intVal==SVG_DISPLAY_TABLE_CELL) return gf_strdup("table-cell");
else if (intVal==SVG_DISPLAY_TABLE_CAPTION) return gf_strdup("table-caption");
break;
case SVG_Visibility_datatype:
if (intVal==SVG_VISIBILITY_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_VISIBILITY_VISIBLE) return gf_strdup("visible");
else if (intVal==SVG_VISIBILITY_HIDDEN) return gf_strdup("hidden");
else if (intVal==SVG_VISIBILITY_COLLAPSE) return gf_strdup("collapse");
break;
case SVG_Overflow_datatype:
if (intVal==SVG_OVERFLOW_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_OVERFLOW_VISIBLE) return gf_strdup("visible");
else if (intVal==SVG_OVERFLOW_HIDDEN) return gf_strdup("hidden");
else if (intVal==SVG_OVERFLOW_SCROLL) return gf_strdup("scroll");
else if (intVal==SVG_OVERFLOW_AUTO) return gf_strdup("auto");
break;
case SVG_ZoomAndPan_datatype:
if (intVal==SVG_ZOOMANDPAN_DISABLE) return gf_strdup("disable");
else return gf_strdup("magnify");
break;
case SVG_DisplayAlign_datatype:
if (intVal==SVG_DISPLAYALIGN_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_DISPLAYALIGN_AUTO) return gf_strdup("auto");
else if (intVal==SVG_DISPLAYALIGN_BEFORE) return gf_strdup("before");
else if (intVal==SVG_DISPLAYALIGN_CENTER) return gf_strdup("center");
else if (intVal==SVG_DISPLAYALIGN_AFTER) return gf_strdup("after");
break;
case SVG_TextAlign_datatype:
if (intVal==SVG_TEXTALIGN_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_TEXTALIGN_START) return gf_strdup("start");
else if (intVal==SVG_TEXTALIGN_CENTER) return gf_strdup("center");
else if (intVal==SVG_TEXTALIGN_END) return gf_strdup("end");
break;
case SVG_PointerEvents_datatype:
if (intVal==SVG_POINTEREVENTS_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_POINTEREVENTS_VISIBLEPAINTED) return gf_strdup("visiblePainted");
else if (intVal==SVG_POINTEREVENTS_VISIBLEFILL) return gf_strdup("visibleFill");
else if (intVal==SVG_POINTEREVENTS_VISIBLESTROKE) return gf_strdup("visibleStroke");
else if (intVal==SVG_POINTEREVENTS_VISIBLE) return gf_strdup("visible");
else if (intVal==SVG_POINTEREVENTS_PAINTED) return gf_strdup("painted");
else if (intVal==SVG_POINTEREVENTS_FILL) return gf_strdup("fill");
else if (intVal==SVG_POINTEREVENTS_STROKE) return gf_strdup("stroke");
else if (intVal==SVG_POINTEREVENTS_ALL) return gf_strdup("all");
else if (intVal==SVG_POINTEREVENTS_NONE) return gf_strdup("none");
else if (intVal==SVG_POINTEREVENTS_BOUNDINGBOX) return gf_strdup("boundingBox");
break;
case SVG_RenderingHint_datatype:
if (intVal==SVG_RENDERINGHINT_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_RENDERINGHINT_AUTO) return gf_strdup("auto");
else if (intVal==SVG_RENDERINGHINT_OPTIMIZEQUALITY) return gf_strdup("optimizeQuality");
else if (intVal==SVG_RENDERINGHINT_OPTIMIZESPEED) return gf_strdup("optimizeSpeed");
else if (intVal==SVG_RENDERINGHINT_OPTIMIZELEGIBILITY) return gf_strdup("optimizeLegibility");
else if (intVal==SVG_RENDERINGHINT_CRISPEDGES) return gf_strdup("crispEdges");
else if (intVal==SVG_RENDERINGHINT_GEOMETRICPRECISION) return gf_strdup("geometricPrecision");
break;
case SVG_VectorEffect_datatype:
if (intVal==SVG_VECTOREFFECT_INHERIT) return gf_strdup("inherit");
else if (intVal==SVG_VECTOREFFECT_NONE) return gf_strdup("none");
else if (intVal==SVG_VECTOREFFECT_NONSCALINGSTROKE) return gf_strdup("non-scaling-stroke");
break;
case SVG_PlaybackOrder_datatype:
if (intVal== SVG_PLAYBACKORDER_FORWARDONLY) return gf_strdup("forwardOnly");
else if (intVal== SVG_PLAYBACKORDER_ALL) return gf_strdup("all");
break;
case SVG_TimelineBegin_datatype:
if (intVal== SVG_TIMELINEBEGIN_ONSTART) return gf_strdup("onStart");
else if (intVal== SVG_TIMELINEBEGIN_ONLOAD) return gf_strdup("onLoad");
break;
case XML_Space_datatype:
if (intVal==XML_SPACE_DEFAULT) return gf_strdup("default");
else if (intVal==XML_SPACE_PRESERVE) return gf_strdup("preserve");
break;
case XMLEV_Propagate_datatype:
if (intVal==XMLEVENT_PROPAGATE_CONTINUE) return gf_strdup("continue");
else if (intVal==XMLEVENT_PROPAGATE_STOP) return gf_strdup("stop");
break;
case XMLEV_DefaultAction_datatype:
if (intVal==XMLEVENT_DEFAULTACTION_CANCEL) return gf_strdup("cancel");
else if (intVal==XMLEVENT_DEFAULTACTION_PERFORM) return gf_strdup("perform");
break;
case XMLEV_Phase_datatype:
if (intVal==XMLEVENT_PHASE_DEFAULT) return gf_strdup("default");
else if (intVal==XMLEVENT_PHASE_CAPTURE) return gf_strdup("capture");
break;
case SMIL_SyncBehavior_datatype:
if (intVal==SMIL_SYNCBEHAVIOR_INHERIT) return gf_strdup("inherit");
else if (intVal==SMIL_SYNCBEHAVIOR_DEFAULT) return gf_strdup("default");
else if (intVal==SMIL_SYNCBEHAVIOR_LOCKED) return gf_strdup("locked");
else if (intVal==SMIL_SYNCBEHAVIOR_CANSLIP) return gf_strdup("canSlip");
else if (intVal==SMIL_SYNCBEHAVIOR_INDEPENDENT) return gf_strdup("independent");
break;
case SMIL_SyncTolerance_datatype:
if (((SMIL_SyncTolerance*)info->far_ptr)->type==SMIL_SYNCTOLERANCE_INHERIT) return gf_strdup("inherit");
else if (((SMIL_SyncTolerance*)info->far_ptr)->type==SMIL_SYNCTOLERANCE_DEFAULT) return gf_strdup("default");
else if (((SMIL_SyncTolerance*)info->far_ptr)->type==SMIL_SYNCBEHAVIOR_LOCKED) {
sprintf(tmp, "%g", ((SMIL_SyncTolerance*)info->far_ptr)->value);
return gf_strdup(tmp);
}
break;
case SMIL_AttributeType_datatype:
if (intVal==SMIL_ATTRIBUTETYPE_AUTO) return gf_strdup("auto");
else if (intVal==SMIL_ATTRIBUTETYPE_XML) return gf_strdup("XML");
else if (intVal==SMIL_ATTRIBUTETYPE_CSS) return gf_strdup("CSS");
break;
case SMIL_CalcMode_datatype:
if (intVal==SMIL_CALCMODE_DISCRETE) return gf_strdup("discrete");
else if (intVal==SMIL_CALCMODE_LINEAR) return gf_strdup("linear");
else if (intVal==SMIL_CALCMODE_PACED) return gf_strdup("paced");
else if (intVal==SMIL_CALCMODE_SPLINE) return gf_strdup("spline");
break;
case SMIL_Additive_datatype:
if (intVal==SMIL_ADDITIVE_REPLACE) return gf_strdup("replace");
else if (intVal==SMIL_ADDITIVE_SUM) return gf_strdup("sum");
break;
case SMIL_Accumulate_datatype:
if (intVal==SMIL_ACCUMULATE_NONE) return gf_strdup("none");
else if (intVal==SMIL_ACCUMULATE_SUM) return gf_strdup("sum");
break;
case SMIL_Restart_datatype:
if (intVal==SMIL_RESTART_ALWAYS) return gf_strdup("always");
else if (intVal==SMIL_RESTART_WHENNOTACTIVE) return gf_strdup("whenNotActive");
else if (intVal==SMIL_RESTART_NEVER) return gf_strdup("never");
break;
case SMIL_Fill_datatype:
if (intVal==SMIL_FILL_FREEZE) return gf_strdup("freeze");
else if (intVal==SMIL_FILL_REMOVE) return gf_strdup("remove");
break;
case SVG_GradientUnit_datatype:
if (intVal==SVG_GRADIENTUNITS_USER) return gf_strdup("userSpaceOnUse");
else if (intVal==SVG_GRADIENTUNITS_OBJECT) return gf_strdup("objectBoundingBox");
break;
case SVG_InitialVisibility_datatype:
if (intVal==SVG_INITIALVISIBILTY_WHENSTARTED) return gf_strdup("whenStarted");
else if (intVal==SVG_INITIALVISIBILTY_ALWAYS) return gf_strdup("always");
break;
case SVG_FocusHighlight_datatype:
if (intVal==SVG_FOCUSHIGHLIGHT_AUTO) return gf_strdup("auto");
else if (intVal==SVG_FOCUSHIGHLIGHT_NONE) return gf_strdup("none");
break;
case SVG_Overlay_datatype:
if (intVal==SVG_OVERLAY_NONE) return gf_strdup("none");
else if (intVal==SVG_OVERLAY_TOP) return gf_strdup("top");
break;
case SVG_TransformBehavior_datatype:
if (intVal==SVG_TRANSFORMBEHAVIOR_GEOMETRIC) return gf_strdup("geometric");
else if (intVal==SVG_TRANSFORMBEHAVIOR_PINNED) return gf_strdup("pinned");
else if (intVal==SVG_TRANSFORMBEHAVIOR_PINNED90) return gf_strdup("pinned90");
else if (intVal==SVG_TRANSFORMBEHAVIOR_PINNED180) return gf_strdup("pinned180");
else if (intVal==SVG_TRANSFORMBEHAVIOR_PINNED270) return gf_strdup("pinned270");
break;
case SVG_SpreadMethod_datatype:
if (intVal==SVG_SPREAD_REFLECT) return gf_strdup("reflect");
else if (intVal==SVG_SPREAD_REPEAT) return gf_strdup("repeat");
else return gf_strdup("pad");
break;
case SVG_Filter_TransferType_datatype:
if (intVal==SVG_FILTER_TRANSFER_TABLE) return gf_strdup("table");
else if (intVal==SVG_FILTER_TRANSFER_DISCRETE) return gf_strdup("discrete");
else if (intVal==SVG_FILTER_TRANSFER_LINEAR) return gf_strdup("linear");
else if (intVal==SVG_FILTER_TRANSFER_GAMMA) return gf_strdup("gamma");
else return gf_strdup("identity");
break;
case LASeR_Choice_datatype:
if (intVal==LASeR_CHOICE_ALL) return gf_strdup("all");
else if (intVal==LASeR_CHOICE_NONE) return gf_strdup("none");
else if (intVal==LASeR_CHOICE_N) {
sprintf(tmp, "%d", ((LASeR_Choice *)info->far_ptr)->choice_index);
return gf_strdup(tmp);
}
break;
case LASeR_Size_datatype:
sprintf(tmp, "%g %g", FIX2FLT(((LASeR_Size *)info->far_ptr)->width), FIX2FLT(((LASeR_Size *)info->far_ptr)->height));
return gf_strdup(tmp);
/* end of keyword type parsing */
/* inheritable floats */
case SVG_FontSize_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_Rotate_datatype:
case SVG_Number_datatype:
#if DUMP_COORDINATES
return svg_dump_number((SVG_Number *)info->far_ptr);
#endif
case XMLRI_datatype:
return svg_dump_iri((XMLRI*)info->far_ptr);
case XML_IDREF_datatype:
return svg_dump_idref((XMLRI*)info->far_ptr);
case XMLRI_List_datatype:
{
GF_List *l = *(GF_List **)info->far_ptr;
u32 i, count = gf_list_count(l);
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
for (i=0; i<count; i++) {
u32 len;
char *szT;
XMLRI *iri = (XMLRI *)gf_list_get(l, i);
szT = svg_dump_iri(iri);
len = (u32) strlen(szT);
if (len) {
attVal = gf_realloc(attVal, sizeof(char)*(len+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
}
gf_free(szT);
}
return attVal;
}
break;
case SVG_PathData_datatype:
#if DUMP_COORDINATES
return svg_dump_path((SVG_PathData *)info->far_ptr);
#endif
break;
case SVG_Points_datatype:
{
#if DUMP_COORDINATES
GF_List *l = *(GF_List **) info->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l);
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
for (i=0; i<count; i++) {
char szT[200];
SVG_Point *p = (SVG_Point *)gf_list_get(l, i);
sprintf(szT, "%g %g", FIX2FLT(p->x), FIX2FLT(p->y));
attVal = gf_realloc(attVal, sizeof(char)*(strlen(szT)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
}
return attVal;
#endif
}
break;
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
{
GF_List *l = *(GF_List **) info->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l);
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
for (i=0; i<count; i++) {
char szT[1000];
Fixed *p = (Fixed *)gf_list_get(l, i);
sprintf(szT, "%g", FIX2FLT(*p));
attVal = gf_realloc(attVal, sizeof(char)*(strlen(szT)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
}
return attVal;
}
break;
case SVG_Coordinates_datatype:
{
#if DUMP_COORDINATES
GF_List *l = *(GF_List **) info->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l);
char *attVal = gf_malloc(sizeof(char));
attVal[0]=0;
for (i=0; i<count; i++) {
char *szT;
SVG_Coordinate *p = (SVG_Coordinate *)gf_list_get(l, i);
szT = svg_dump_number((SVG_Length *)p);
attVal = gf_realloc(attVal, sizeof(char)*(strlen(szT)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
gf_free(szT);
}
return attVal;
#endif
}
break;
case SVG_ViewBox_datatype:
{
SVG_ViewBox *v = (SVG_ViewBox *)info->far_ptr;
if (v->is_set) {
sprintf(tmp, "%g %g %g %g", FIX2FLT(v->x), FIX2FLT(v->y), FIX2FLT(v->width), FIX2FLT(v->height) );
return gf_strdup(tmp);
} else
return gf_strdup("none");
}
break;
case SVG_StrokeDashArray_datatype:
{
SVG_StrokeDashArray *p = (SVG_StrokeDashArray *)info->far_ptr;
if (p->type==SVG_STROKEDASHARRAY_NONE) return gf_strdup("none");
else if (p->type==SVG_STROKEDASHARRAY_INHERIT) return gf_strdup("inherit");
else if (p->type==SVG_STROKEDASHARRAY_ARRAY) {
u32 i = 0;
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
for (i=0; i<p->array.count; i++) {
char *szT;
SVG_Length l;
l.type = p->array.units[i];
l.value = p->array.vals[i];
szT = svg_dump_number(&l);
attVal = gf_realloc(attVal, sizeof(char)*(strlen(szT)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
gf_free(szT);
}
return attVal;
}
}
break;
case SVG_FontFamily_datatype:
{
SVG_FontFamily *f = (SVG_FontFamily *)info->far_ptr;
return gf_strdup( (f->type==SVG_FONTFAMILY_INHERIT) ? "inherit" : (const char *) f->value);
}
case SVG_PreserveAspectRatio_datatype:
{
SVG_PreserveAspectRatio *par = (SVG_PreserveAspectRatio *)info->far_ptr;
tmp[0] = 0;
if (par->defer) strcat(tmp, "defer ");
if (par->align == SVG_PRESERVEASPECTRATIO_NONE) strcat(tmp, "none");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMINYMIN) strcat(tmp, "xMinYMin");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMIDYMIN) strcat(tmp, "xMidYMin");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMAXYMIN) strcat(tmp, "xMaxYMin");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMINYMID) strcat(tmp, "xMinYMid");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMIDYMID) strcat(tmp, "xMidYMid");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMAXYMID) strcat(tmp, "xMaxYMid");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMINYMAX) strcat(tmp, "xMinYMax");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMIDYMAX) strcat(tmp, "xMidYMax");
else if (par->align == SVG_PRESERVEASPECTRATIO_XMAXYMAX) strcat(tmp, "xMaxYMax");
if (par->meetOrSlice== SVG_MEETORSLICE_SLICE) strcat(tmp, " slice");
return gf_strdup(tmp);
}
case SVG_Clock_datatype:
sprintf(tmp, "%g", * (SVG_Clock *)info->far_ptr );
return gf_strdup(tmp);
case SVG_ID_datatype:
case SVG_LanguageID_datatype:
case SVG_GradientOffset_datatype:
case DOM_String_datatype:
case SVG_ContentType_datatype:
if (*(SVG_String *)info->far_ptr)
return gf_strdup( *(SVG_String *)info->far_ptr );
break;
case SVG_Focus_datatype:
{
SVG_Focus *foc = (SVG_Focus *)info->far_ptr;
if (foc->type==SVG_FOCUS_SELF) return gf_strdup("self");
else if (foc->type==SVG_FOCUS_AUTO) return gf_strdup("auto");
else {
sprintf(tmp, "#%s", foc->target.string);
return gf_strdup(tmp);
}
}
break;
case SVG_Focusable_datatype:
{
SVG_Focusable *f = (SVG_Focusable *)info->far_ptr;
if (*f == SVG_FOCUSABLE_TRUE) return gf_strdup("true");
else if (*f == SVG_FOCUSABLE_FALSE) return gf_strdup("false");
else return gf_strdup("auto");
}
case DOM_StringList_datatype:
{
GF_List *l1 = *(GF_List **) info->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
for (i=0; i<count; i++) {
char *p1 = (char *)gf_list_get(l1, i);
attVal = gf_realloc(attVal, sizeof(char)*(strlen(p1)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, p1);
}
return attVal;
}
case SVG_Numbers_datatype:
{
#if DUMP_COORDINATES
GF_List *l1 = *(GF_List **) info->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
char *attVal = gf_malloc(sizeof(char));
attVal[0]=0;
for (i=0; i<count; i++) {
char *szT;
SVG_Number *p = (SVG_Number *)gf_list_get(l1, i);
szT = svg_dump_number(p);
attVal = gf_realloc(attVal, sizeof(char)*(strlen(szT)+strlen(attVal)+ (i ? 2 : 1) ));
if (i) strcat(attVal, " ");
strcat(attVal, szT);
gf_free(szT);
}
return attVal;
#endif
}
break;
case SVG_Motion_datatype:
{
#if DUMP_COORDINATES
GF_Matrix2D *m = (GF_Matrix2D *)info->far_ptr;
sprintf(tmp, "%g %g", FIX2FLT(m->m[2]), FIX2FLT(m->m[5]));
return gf_strdup(tmp);
#endif
}
break;
case SVG_Transform_datatype:
{
SVG_Transform *t= (SVG_Transform *)info->far_ptr;
if (t->is_ref) {
sprintf(tmp, "ref(svg,%g,%g)", FIX2FLT(t->mat.m[2]), FIX2FLT(t->mat.m[5]) );
return gf_strdup(tmp);
} else {
return gf_svg_dump_matrix(&t->mat);
}
}
break;
case SVG_Transform_Translate_datatype:
{
SVG_Point *pt = (SVG_Point *)info->far_ptr;
#if DUMP_COORDINATES
sprintf(tmp, "%g %g", FIX2FLT(pt->x), FIX2FLT(pt->y) );
return gf_strdup(tmp);
#endif
}
break;
case SVG_Transform_Scale_datatype:
{
SVG_Point *pt = (SVG_Point *)info->far_ptr;
#if DUMP_COORDINATES
if (pt->x == pt->y) {
sprintf(tmp, "%g", FIX2FLT(pt->x));
} else {
sprintf(tmp, "%g %g", FIX2FLT(pt->x), FIX2FLT(pt->y) );
}
return gf_strdup(tmp);
#endif
}
break;
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
{
Fixed *f = (Fixed *)info->far_ptr;
#if DUMP_COORDINATES
sprintf(tmp, "%g", FIX2FLT( 180 * gf_divfix(*f, GF_PI) ));
return gf_strdup(tmp);
#endif
}
break;
case SVG_Transform_Rotate_datatype:
{
SVG_Point_Angle *pt = (SVG_Point_Angle *)info->far_ptr;
#if DUMP_COORDINATES
if (pt->x || pt->y) {
sprintf(tmp, "%g %g %g", FIX2FLT( 180 * gf_divfix(pt->angle, GF_PI) ), FIX2FLT(pt->x), FIX2FLT(pt->y) );
} else {
sprintf(tmp, "%g", FIX2FLT(gf_divfix(180 * pt->angle, GF_PI) ));
}
return gf_strdup(tmp);
#endif
}
break;
case SMIL_AttributeName_datatype:
{
SMIL_AttributeName *att_name = (SMIL_AttributeName *) info->far_ptr;
if (att_name->name)
return gf_strdup(att_name->name);
if (att_name->tag) {
char *att_name_val = (char *)gf_svg_get_attribute_name(elt, att_name->tag);
if (!att_name_val) {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG] unknown attribute name for tag %d\n", att_name->tag));
return NULL;
}
return gf_strdup(att_name_val );
}
}
break;
case SMIL_Times_datatype:
{
u32 i, count;
GF_Node *par = gf_node_get_parent((GF_Node *)elt, 0);
GF_List *l = *(GF_List **) info->far_ptr;
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
count = gf_list_count(l);
for (i=0; i<count; i++) {
char szBuf[1000];
SMIL_Time *t = (SMIL_Time *)gf_list_get(l, i);
szBuf[0] = 0;
if (t->type == GF_SMIL_TIME_CLOCK) {
sprintf(szBuf, "%gs", t->clock);
} else if (t->type==GF_SMIL_TIME_INDEFINITE) {
strcpy(szBuf, "indefinite");
} else if (t->type==GF_SMIL_TIME_WALLCLOCK) {
u32 h, m, s;
/*TODO - day month and year*/
h = (u32) t->clock * 3600;
m = (u32) (t->clock * 60 - 60*h);
s = (u32) (t->clock - 3600*h - 60*m);
sprintf(szBuf, "wallclock(%d:%d:%d)", h, m, s);
}
else if (t->type==GF_SMIL_TIME_EVENT) {
if (t->event.type == GF_EVENT_KEYDOWN) {
svg_dump_access_key(&t->event, szBuf);
} else {
if (t->element_id) {
strcpy(szBuf, t->element_id);
strcat(szBuf, ".");
} else if (t->element && (t->element!=par) && gf_node_get_id(t->element) ) {
const char *name = gf_node_get_name(t->element);
if (name) {
strcpy(szBuf, name);
} else {
sprintf(szBuf, "N%d", gf_node_get_id(t->element)-1 );
}
strcat(szBuf, ".");
}
strcat(szBuf, gf_dom_event_get_name(t->event.type));
}
if (t->clock) {
char szCk[40];
sprintf(szCk, "+%gs", t->clock);
strcat(szBuf, szCk);
}
}
if (szBuf[0]) {
attVal = gf_realloc(attVal, sizeof(char)*(strlen(attVal)+strlen(szBuf)+ (i ? 2 : 1) ));
if ( strlen(attVal) ) strcat(attVal, ";");
strcat(attVal, szBuf);
}
}
return attVal;
}
break;
case SMIL_Duration_datatype:
{
SMIL_Duration *dur = (SMIL_Duration *)info->far_ptr;
if (dur->type == SMIL_DURATION_INDEFINITE) return gf_strdup("indefinite");
else if (dur->type == SMIL_DURATION_MEDIA) return gf_strdup("media");
else if (dur->type == SMIL_DURATION_DEFINED) {
sprintf(tmp, "%gs", dur->clock_value);
return gf_strdup(tmp);
} else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Dumping] smil duration not assigned\n"));
}
}
break;
case SMIL_RepeatCount_datatype:
{
SMIL_RepeatCount *rep = (SMIL_RepeatCount *)info->far_ptr;
if (rep->type == SMIL_REPEATCOUNT_INDEFINITE) return gf_strdup("indefinite");
else if (rep->type == SMIL_REPEATCOUNT_DEFINED) {
sprintf(tmp, "%g", FIX2FLT(rep->count) );
return gf_strdup(tmp);
}
else {
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Dumping] smil repeat count not assigned\n"));
}
}
break;
case SVG_TransformType_datatype:
{
SVG_TransformType tr = *(SVG_TransformType *)info->far_ptr;
if (tr == SVG_TRANSFORM_MATRIX) return gf_strdup("matrix");
else if (tr == SVG_TRANSFORM_SCALE) return gf_strdup("scale");
else if (tr == SVG_TRANSFORM_ROTATE) return gf_strdup("rotate");
else if (tr == SVG_TRANSFORM_TRANSLATE) return gf_strdup("translate");
else if (tr == SVG_TRANSFORM_SKEWX) return gf_strdup("skewX");
else if (tr == SVG_TRANSFORM_SKEWY) return gf_strdup("skewY");
}
break;
case SMIL_AnimateValue_datatype:
{
GF_FieldInfo a_fi;
SMIL_AnimateValue*av = (SMIL_AnimateValue*)info->far_ptr;
a_fi.fieldIndex = 0;
a_fi.fieldType = av->type;
a_fi.name = info->name;
a_fi.far_ptr = av->value;
return gf_svg_dump_attribute(elt, &a_fi);
}
break;
case SMIL_AnimateValues_datatype:
{
GF_FieldInfo a_fi;
u32 i, count;
SMIL_AnimateValues *av = (SMIL_AnimateValues*)info->far_ptr;
char *attVal = gf_malloc(sizeof(char));
attVal[0] = 0;
if (av->type) {
count = gf_list_count(av->values);
a_fi.fieldIndex = 0;
a_fi.fieldType = av->type;
a_fi.name = info->name;
for (i=0; i<count; i++) {
char *szBuf;
a_fi.far_ptr = gf_list_get(av->values, i);
szBuf = gf_svg_dump_attribute(elt, &a_fi);
attVal = gf_realloc(attVal, sizeof(char)*(strlen(attVal)+strlen(szBuf)+ (i ? 2 : 1) ));
if (i) strcat(attVal, ";");
strcat(attVal, szBuf);
gf_free(szBuf);
}
}
return attVal;
}
case XMLEV_Event_datatype:
{
XMLEV_Event *d = (XMLEV_Event *)info->far_ptr;
if (d->parameter) {
svg_dump_access_key(d, tmp);
} else {
strcpy(tmp, gf_dom_event_get_name(d->type));
}
return gf_strdup(tmp);
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Dumping] field %s of type %s not supported\n", info->name, gf_svg_attribute_type_to_string(info->fieldType)));
break;
}
return gf_strdup("");
}
char *gf_svg_dump_attribute_indexed(GF_Node *elt, GF_FieldInfo *info)
{
char tmp[1024];
switch (info->fieldType) {
case SVG_PointerEvents_datatype:
break;
case XMLRI_List_datatype:
return gf_strdup( (char *) info->far_ptr);
case SVG_Points_datatype:
{
#if DUMP_COORDINATES
SVG_Point *p = (SVG_Point *)info->far_ptr;
sprintf(tmp, "%g %g", FIX2FLT(p->x), FIX2FLT(p->y));
return gf_strdup(tmp);
#endif
}
break;
case SMIL_KeyPoints_datatype:
case SMIL_KeyTimes_datatype:
case SMIL_KeySplines_datatype:
{
Fixed *p = (Fixed *)info->far_ptr;
sprintf(tmp, "%g", FIX2FLT(*p));
return gf_strdup(tmp);
}
break;
case SVG_Coordinates_datatype:
#if DUMP_COORDINATES
return svg_dump_number((SVG_Length *) (SVG_Coordinate *)info->far_ptr);
#endif
break;
case SVG_ViewBox_datatype:
{
Fixed *v = (Fixed *)info->far_ptr;
sprintf(tmp, "%g", FIX2FLT(*v));
return gf_strdup(tmp);
}
break;
case SVG_StrokeDashArray_datatype:
{
/*TODO: fix this: should be an SVG_Length*/
Fixed *p = (Fixed *)info->far_ptr;
sprintf(tmp, "%g", FIX2FLT(*p));
return gf_strdup(tmp);
}
break;
case SMIL_Times_datatype:
{
SMIL_Time *t = (SMIL_Time *)info->far_ptr;
if (t->type == GF_SMIL_TIME_CLOCK) {
sprintf(tmp, "%gs", t->clock);
} else if (t->type==GF_SMIL_TIME_INDEFINITE) {
strcpy(tmp, "indefinite");
} else if (t->type==GF_SMIL_TIME_WALLCLOCK) {
u32 h, m, s;
/*TODO - day month and year*/
h = (u32) t->clock * 3600;
m = (u32) (t->clock * 60 - 60*h);
s = (u32) (t->clock - 3600*h - 60*m);
sprintf(tmp, "wallclock(%d:%d:%d)", h, m, s);
}
else if (t->type==GF_SMIL_TIME_EVENT) {
GF_Node *par = gf_node_get_parent((GF_Node *)elt, 0);
if (t->event.type == GF_EVENT_KEYDOWN) {
svg_dump_access_key(&t->event, tmp);
} else {
strcpy(tmp, "");
if (t->element_id) {
strcat(tmp, t->element_id);
strcat(tmp, ".");
} else if (t->element && (t->element!=par) && gf_node_get_id(t->element) ) {
const char *name = gf_node_get_name(t->element);
if (name) {
strcat(tmp, name);
} else {
sprintf(tmp, "N%d", gf_node_get_id(t->element)-1 );
}
strcat(tmp, ".");
}
strcat(tmp, gf_dom_event_get_name(t->event.type));
}
if (t->clock) {
char szBuf[100];
sprintf(szBuf, "+%gs", t->clock);
strcat(tmp, szBuf);
}
}
return gf_strdup(tmp);
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_PARSER, ("[SVG Dumping] indexed field %s of type %s not supported\n", info->name, gf_svg_attribute_type_to_string(info->fieldType)));
break;
}
return gf_strdup("");
}
static Bool svg_viewbox_equal(SVG_ViewBox *v1, SVG_ViewBox *v2)
{
if (v1->is_set != v2->is_set) return 0;
if (!v1->is_set)
return 1;
else {
if ( (v1->x == v2->x) && (v1->y == v2->y) && (v1->width == v2->width) && (v1->height == v2->height) )
return 1;
else
return 0;
}
}
static Bool svg_colors_equal(SVG_Color *c1, SVG_Color *c2)
{
if (c1->type != c2->type) return 0;
if (c1->red != c2->red) return 0;
if (c1->green != c2->green) return 0;
if (c1->blue != c2->blue) return 0;
return 1;
}
static Bool svg_numbers_equal(SVG_Length *l1, SVG_Length *l2)
{
if (l1->type!=l2->type) return 0;
if (l1->type >= SVG_NUMBER_INHERIT) return 1;
return (l1->value==l2->value) ? 1 : 0;
}
static Bool svg_iris_equal(XMLRI*iri1, XMLRI*iri2)
{
u32 type1, type2;
type1 = iri1->type;
type2 = iri2->type;
/*ignore undef hrefs, these are internall ones*/
if ((iri1->type == XMLRI_ELEMENTID) && iri1->target) {
if (!gf_node_get_id((GF_Node *)iri1->target)) type1 = 0;
}
if ((iri2->type == XMLRI_ELEMENTID) && iri2->target) {
if (!gf_node_get_id((GF_Node *)iri2->target)) type2 = 0;
}
if (type1 != type2) return 0;
if ((type1 == XMLRI_ELEMENTID) && (iri1->target == iri2->target) ) return 1;
if (iri1->string && iri2->string && !strcmp(iri1->string, iri2->string)) return 1;
if (!iri1->string && !iri2->string) return 1;
return 0;
}
static Bool svg_matrices_equal(GF_Matrix2D *m1, GF_Matrix2D *m2)
{
if (m1->m[0] != m2->m[0]) return 0;
if (m1->m[1] != m2->m[1]) return 0;
if (m1->m[2] != m2->m[2]) return 0;
if (m1->m[3] != m2->m[3]) return 0;
if (m1->m[4] != m2->m[4]) return 0;
if (m1->m[5] != m2->m[5]) return 0;
return 1;
}
Bool gf_svg_attributes_equal(GF_FieldInfo *f1, GF_FieldInfo *f2)
{
u32 v1, v2;
if (f1->fieldType!=f2->fieldType) return 0;
if (f1->far_ptr && !f2->far_ptr) return 0;
if (f2->far_ptr && !f1->far_ptr) return 0;
if (!f1->far_ptr) return 1;
v1 = *(u8 *)f1->far_ptr;
v2 = *(u8 *)f2->far_ptr;
switch (f1->fieldType) {
case SVG_Boolean_datatype:
case SVG_FillRule_datatype:
case SVG_StrokeLineJoin_datatype:
case SVG_StrokeLineCap_datatype:
case SVG_FontStyle_datatype:
case SVG_FontWeight_datatype:
case SVG_FontVariant_datatype:
case SVG_TextAnchor_datatype:
case SVG_Display_datatype:
case SVG_Visibility_datatype:
case SVG_GradientUnit_datatype:
case SVG_PreserveAspectRatio_datatype:
case XML_Space_datatype:
case XMLEV_Propagate_datatype:
case XMLEV_DefaultAction_datatype:
case XMLEV_Phase_datatype:
case SMIL_SyncBehavior_datatype:
case SMIL_AttributeType_datatype:
case SMIL_CalcMode_datatype:
case SMIL_Additive_datatype:
case SMIL_Accumulate_datatype:
case SMIL_Restart_datatype:
case SMIL_Fill_datatype:
case SVG_Overflow_datatype:
case SVG_ZoomAndPan_datatype:
case SVG_DisplayAlign_datatype:
case SVG_TextAlign_datatype:
case SVG_PointerEvents_datatype:
case SVG_RenderingHint_datatype:
case SVG_VectorEffect_datatype:
case SVG_PlaybackOrder_datatype:
case SVG_TimelineBegin_datatype:
case SVG_Focusable_datatype:
case SVG_FocusHighlight_datatype:
case SVG_TransformType_datatype:
case SVG_Overlay_datatype:
case SVG_TransformBehavior_datatype:
case SVG_SpreadMethod_datatype:
case SVG_InitialVisibility_datatype:
case LASeR_Choice_datatype:
return (v1==v2) ? 1 : 0;
case SVG_Color_datatype:
return svg_colors_equal((SVG_Color *)f1->far_ptr, (SVG_Color *)f2->far_ptr);
case SMIL_SyncTolerance_datatype:
{
SMIL_SyncTolerance *st1 = (SMIL_SyncTolerance*)f1->far_ptr;
SMIL_SyncTolerance *st2 = (SMIL_SyncTolerance*)f2->far_ptr;
if (st1->type!=st2->type) return 0;
if ((st1->type==SMIL_SYNCTOLERANCE_VALUE) && (st1->value!=st2->value)) return 0;
return 1;
}
case SVG_Paint_datatype:
{
SVG_Paint *p1 = (SVG_Paint *)f1->far_ptr;
SVG_Paint *p2 = (SVG_Paint *)f2->far_ptr;
if (p1->type != p2->type) return 0;
if (p1->type==SVG_PAINT_COLOR) return svg_colors_equal(&p1->color, &p2->color);
else if (p1->type==SVG_PAINT_URI) return svg_iris_equal(&p1->iri, &p2->iri);
return 1;
}
break;
case SVG_FontSize_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_Rotate_datatype:
case SVG_Number_datatype:
return svg_numbers_equal((SVG_Number *)f1->far_ptr, (SVG_Number *)f2->far_ptr);
case XMLRI_datatype:
return svg_iris_equal((XMLRI*)f1->far_ptr, (XMLRI*)f2->far_ptr);
case XMLRI_List_datatype:
{
GF_List *l1 = *(GF_List **)f1->far_ptr;
GF_List *l2 = *(GF_List **)f2->far_ptr;
u32 i, count = gf_list_count(l1);
if (gf_list_count(l2)!=count) return 0;
for (i=0; i<count; i++) {
if (!svg_iris_equal((XMLRI*)gf_list_get(l1, i), (XMLRI*)gf_list_get(l2, i) )) return 0;
}
return 1;
}
case SVG_PathData_datatype:
{
SVG_PathData *d1 = (SVG_PathData *)f1->far_ptr;
SVG_PathData *d2 = (SVG_PathData *)f2->far_ptr;
u32 i;
/*FIXME - be less lazy..*/
#if USE_GF_PATH
if (d1->n_points != d2->n_points) return 0;
if (d1->n_contours != d2->n_contours) return 0;
for (i=0; i<d1->n_points; i++) {
if (d1->points[i].x != d2->points[i].x) return 0;
if (d1->points[i].y != d2->points[i].y) return 0;
}
for (i=0; i<d1->n_points; i++) {
if (d1->tags[i] != d2->tags[i]) return 0;
}
for (i=0; i<d1->n_contours; i++) {
if (d1->contours[i] != d2->contours[i]) return 0;
}
return 1;
#else
if (!gf_list_count(d1->commands) && !gf_list_count(d2->commands)) return 1;
#endif
return 0;
}
case SVG_Points_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2)!=count) return 0;
for (i=0; i<count; i++) {
SVG_Point *p1 = (SVG_Point *)gf_list_get(l1, i);
SVG_Point *p2 = (SVG_Point *)gf_list_get(l2, i);
if (p1->x != p2->x) return 0;
if (p1->y != p2->y) return 0;
}
return 1;
}
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2)!=count) return 0;
for (i=0; i<count; i++) {
Fixed *p1 = (Fixed *)gf_list_get(l1, i);
Fixed *p2 = (Fixed *)gf_list_get(l2, i);
if (*p1 != *p2) return 0;
}
return 1;
}
case SVG_Coordinates_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2) != count) return 0;
for (i=0; i<count; i++) {
SVG_Coordinate *p1 = (SVG_Coordinate *)gf_list_get(l1, i);
SVG_Coordinate *p2 = (SVG_Coordinate *)gf_list_get(l2, i);
if (!svg_numbers_equal(p1, p2)) return 0;
}
return 1;
}
case SVG_ViewBox_datatype:
{
SVG_ViewBox *v1 = (SVG_ViewBox *)f1->far_ptr;
SVG_ViewBox *v2 = (SVG_ViewBox *)f2->far_ptr;
return svg_viewbox_equal(v1, v2);
}
case SVG_StrokeDashArray_datatype:
{
SVG_StrokeDashArray *p1 = (SVG_StrokeDashArray *)f1->far_ptr;
SVG_StrokeDashArray *p2 = (SVG_StrokeDashArray *)f2->far_ptr;
if (p1->type!=p2->type) return 0;
if (p1->type==SVG_STROKEDASHARRAY_ARRAY) {
u32 i = 0;
if (p1->array.count != p2->array.count) return 0;
for (i=0; i<p1->array.count; i++) {
if (p1->array.units[i] != p2->array.units[i]) return 0;
if (p1->array.vals[i] != p2->array.vals[i]) return 0;
}
}
return 1;
}
case SVG_FontFamily_datatype:
{
SVG_FontFamily *ff1 = (SVG_FontFamily *)f1->far_ptr;
SVG_FontFamily *ff2 = (SVG_FontFamily *)f2->far_ptr;
if (ff1->type!=ff2->type) return 0;
if (ff1->type==SVG_FONTFAMILY_INHERIT) return 1;
return (ff1->value && ff2->value && !strcmp(ff1->value, ff2->value)) ? 1 : 0;
}
case SVG_Clock_datatype:
return (* (SVG_Clock *)f1->far_ptr == * (SVG_Clock *)f2->far_ptr) ? 1 : 0;
/* required for animateMotion */
case SVG_Motion_datatype:
return svg_matrices_equal((GF_Matrix2D*)f1->far_ptr, (GF_Matrix2D*)f2->far_ptr);
case SVG_Transform_datatype:
{
SVG_Transform *t1 = (SVG_Transform *)f1->far_ptr;
SVG_Transform *t2 = (SVG_Transform *)f2->far_ptr;
if (t1->is_ref == t2->is_ref)
return svg_matrices_equal(&t1->mat, &t2->mat);
else
return 0;
}
case SVG_Transform_Translate_datatype:
case SVG_Transform_Scale_datatype:
{
SVG_Point *p1 = (SVG_Point *)f1->far_ptr;
SVG_Point *p2 = (SVG_Point *)f2->far_ptr;
if (p1->x != p2->x) return 0;
if (p1->y != p2->y) return 0;
return 1;
}
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
{
Fixed *p1 = (Fixed *)f1->far_ptr;
Fixed *p2 = (Fixed *)f2->far_ptr;
return (*p1 == *p2);
}
case SVG_Transform_Rotate_datatype:
{
SVG_Point_Angle *p1 = (SVG_Point_Angle *)f1->far_ptr;
SVG_Point_Angle *p2 = (SVG_Point_Angle *)f2->far_ptr;
if (p1->x != p2->x) return 0;
if (p1->y != p2->y) return 0;
if (p1->angle != p2->angle) return 0;
return 1;
}
case SVG_ID_datatype:
case SVG_LanguageID_datatype:
case SVG_GradientOffset_datatype:
case DOM_String_datatype:
case SVG_ContentType_datatype:
{
char *str1 = *(SVG_String *)f1->far_ptr;
char *str2 = *(SVG_String *)f2->far_ptr;
if (!str1 && !str2) return 1;
return (str1 && str2 && !strcmp(str1, str2)) ? 1 : 0;
}
case SVG_Focus_datatype:
{
SVG_Focus *foc1 = (SVG_Focus *) f1->far_ptr;
SVG_Focus *foc2 = (SVG_Focus *)f2->far_ptr;
if (foc1->type!=foc2->type) return 0;
if (foc1->type != SVG_FOCUS_IRI) return 1;
return (foc1->target.string && foc2->target.string && !strcmp(foc1->target.string, foc2->target.string)) ? 1 : 0;
}
break;
case DOM_StringList_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2) != count) return 0;
for (i=0; i<count; i++) {
char *p1 = (char *)gf_list_get(l1, i);
char *p2 = (char *)gf_list_get(l2, i);
if (strcmp(p1, p2)) return 0;
}
return 1;
}
case SVG_Numbers_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2) != count) return 0;
for (i=0; i<count; i++) {
SVG_Number *p1 = (SVG_Number *)gf_list_get(l1, i);
SVG_Number *p2 = (SVG_Number *)gf_list_get(l2, i);
if (!svg_numbers_equal(p1, p2)) return 0;
}
return 1;
}
case SMIL_Times_datatype:
{
GF_List *l1 = *(GF_List **) f1->far_ptr;
GF_List *l2 = *(GF_List **) f2->far_ptr;
u32 i = 0;
u32 count = gf_list_count(l1);
if (gf_list_count(l2) != count) return 0;
for (i=0; i<count; i++) {
SMIL_Time *p1 = (SMIL_Time *)gf_list_get(l1, i);
SMIL_Time *p2 = (SMIL_Time *)gf_list_get(l2, i);
if (p1->type != p2->type) return 0;
if (p1->clock != p2->clock) return 0;
if (p1->type==GF_SMIL_TIME_EVENT) {
if (p1->event.type != p2->event.type) return 0;
if (p1->event.parameter != p2->event.parameter) return 0;
}
}
return 1;
}
case SMIL_Duration_datatype:
{
SMIL_Duration *d1 = (SMIL_Duration *)f1->far_ptr;
SMIL_Duration *d2 = (SMIL_Duration *)f2->far_ptr;
if (d1->type != d2->type) return 0;
if (d1->clock_value != d2->clock_value) return 0;
return 1;
}
case SMIL_RepeatCount_datatype:
{
SMIL_RepeatCount *d1 = (SMIL_RepeatCount *)f1->far_ptr;
SMIL_RepeatCount *d2 = (SMIL_RepeatCount *)f2->far_ptr;
if (d1->type != d2->type) return 0;
if (d1->count != d2->count) return 0;
return 1;
}
case SMIL_AttributeName_datatype:
{
SMIL_AttributeName *att1 = (SMIL_AttributeName *) f1->far_ptr;
SMIL_AttributeName *att2 = (SMIL_AttributeName *) f2->far_ptr;
/*TODO check me...*/
if (att2->field_ptr == att1->field_ptr) return 1;
return 0;
}
case SMIL_AnimateValue_datatype:
{
SMIL_AnimateValue *av1 = (SMIL_AnimateValue*)f1->far_ptr;
SMIL_AnimateValue *av2 = (SMIL_AnimateValue*)f2->far_ptr;
if (av1->value != av2->value) return 0;
return 1;
}
break;
case SMIL_AnimateValues_datatype:
{
u32 count;
SMIL_AnimateValues *av1 = (SMIL_AnimateValues*)f1->far_ptr;
SMIL_AnimateValues *av2 = (SMIL_AnimateValues*)f2->far_ptr;
if (av1->type != av2->type) return 0;
if ( (count = gf_list_count(av1->values) ) != gf_list_count(av1->values)) return 0;
return count ? 0 : 1;
}
case XMLEV_Event_datatype:
{
XMLEV_Event *d1 = (XMLEV_Event *)f1->far_ptr;
XMLEV_Event *d2 = (XMLEV_Event *)f2->far_ptr;
if (d1->type != d2->type) return 0;
if (d1->parameter != d2->parameter) return 0;
return 1;
}
case LASeR_Size_datatype:
{
LASeR_Size *sz1 = (LASeR_Size *)f1->far_ptr;
LASeR_Size *sz2 = (LASeR_Size *)f2->far_ptr;
if (sz1->width != sz2->width) return 0;
if (sz1->height != sz2->height) return 0;
return 1;
}
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_INTERACT, ("[SVG Attributes] comparaison for field %s of type %s not supported\n", f1->name ? f1->name : "unknown", gf_svg_attribute_type_to_string(f1->fieldType)));
return 0;
}
}
static void svg_color_clamp(SVG_Color *a)
{
a->red = MAX(0, MIN(FIX_ONE, a->red));
a->green = MAX(0, MIN(FIX_ONE, a->green));
a->blue = MAX(0, MIN(FIX_ONE, a->blue));
}
static GF_Err svg_color_muladd(Fixed alpha, SVG_Color *a, Fixed beta, SVG_Color *b, SVG_Color *c, Bool clamp)
{
if (a->type != SVG_COLOR_RGBCOLOR || b->type != SVG_COLOR_RGBCOLOR) {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] only RGB colors are additive\n"));
return GF_BAD_PARAM;
}
c->type = SVG_COLOR_RGBCOLOR;
c->red = gf_mulfix(alpha, a->red) + gf_mulfix(beta, b->red);
c->green = gf_mulfix(alpha, a->green) + gf_mulfix(beta, b->green);
c->blue = gf_mulfix(alpha, a->blue) + gf_mulfix(beta, b->blue);
if (clamp) svg_color_clamp(c);
return GF_OK;
}
static GF_Err svg_number_muladd(Fixed alpha, SVG_Number *a, Fixed beta, SVG_Number *b, SVG_Number *c)
{
if (!a || !b || !c) return GF_BAD_PARAM;
if (a->type != b->type) {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] cannot add lengths of mismatching types\n"));
return GF_BAD_PARAM;
}
if (a->type == SVG_NUMBER_INHERIT || a->type == SVG_NUMBER_AUTO) {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] cannot add lengths\n"));
return GF_BAD_PARAM;
}
c->value = gf_mulfix(alpha, a->value) + gf_mulfix(beta, b->value);
return GF_OK;
}
static GF_Err svg_viewbox_muladd(Fixed alpha, SVG_ViewBox *a, Fixed beta, SVG_ViewBox *b, SVG_ViewBox *c)
{
c->is_set = 1;
c->x = gf_mulfix(alpha, a->x) + gf_mulfix(beta, b->x);
c->y = gf_mulfix(alpha, a->y) + gf_mulfix(beta, b->y);
c->width = gf_mulfix(alpha, a->width) + gf_mulfix(beta, b->width);
c->height= gf_mulfix(alpha, a->height) + gf_mulfix(beta, b->height);
return GF_OK;
}
static GF_Err svg_point_muladd(Fixed alpha, SVG_Point *pta, Fixed beta, SVG_Point *ptb, SVG_Point *ptc)
{
if (!pta || !ptb || !ptc) return GF_BAD_PARAM;
ptc->x = gf_mulfix(alpha, pta->x) + gf_mulfix(beta, ptb->x);
ptc->y = gf_mulfix(alpha, pta->y) + gf_mulfix(beta, ptb->y);
return GF_OK;
}
static GF_Err svg_point_angle_muladd(Fixed alpha, SVG_Point_Angle *pta, Fixed beta, SVG_Point_Angle *ptb, SVG_Point_Angle *ptc)
{
ptc->x = gf_mulfix(alpha, pta->x) + gf_mulfix(beta, ptb->x);
ptc->y = gf_mulfix(alpha, pta->y) + gf_mulfix(beta, ptb->y);
ptc->angle = gf_mulfix(alpha, pta->angle) + gf_mulfix(beta, ptb->angle);
return GF_OK;
}
static GF_Err svg_points_muladd(Fixed alpha, SVG_Points *a, Fixed beta, SVG_Points *b, SVG_Points *c)
{
u32 a_count = gf_list_count(*a);
u32 i;
if (a_count != gf_list_count(*b)) return GF_BAD_PARAM;
while (gf_list_count(*c)) {
SVG_Point *ptc = (SVG_Point *)gf_list_get(*c, 0);
gf_list_rem(*c, 0);
gf_free(ptc);
}
for (i = 0; i < a_count; i ++) {
SVG_Point *ptc;
SVG_Point *pta = (SVG_Point *)gf_list_get(*a, i);
SVG_Point *ptb = (SVG_Point *)gf_list_get(*b, i);
GF_SAFEALLOC(ptc, SVG_Point)
svg_point_muladd(alpha, pta, beta, ptb, ptc);
gf_list_add(*c, ptc);
}
return GF_OK;
}
static GF_Err svg_points_copy(SVG_Points *a, SVG_Points *b)
{
u32 i, count;
count = gf_list_count(*a);
for (i = 0; i < count; i++) {
SVG_Point *pt = (SVG_Point *)gf_list_get(*a, i);
gf_free(pt);
}
gf_list_reset(*a);
count = gf_list_count(*b);
for (i = 0; i < count; i ++) {
SVG_Point *ptb = (SVG_Point *)gf_list_get(*b, i);
SVG_Point *pta;
GF_SAFEALLOC(pta, SVG_Point)
if (!pta) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Cannot allocate SVG point\n"));
continue;
}
*pta = *ptb;
gf_list_add(*a, pta);
}
return GF_OK;
}
static GF_Err svg_numbers_muladd(Fixed alpha, SVG_Numbers *a, Fixed beta, SVG_Numbers *b, SVG_Numbers *c)
{
u32 a_count = gf_list_count(*a);
u32 i;
if (a_count != gf_list_count(*b)) return GF_BAD_PARAM;
gf_list_reset(*c);
for (i = 0; i < a_count; i ++) {
SVG_Number *nc;
SVG_Number *na = (SVG_Number *)gf_list_get(*a, i);
SVG_Number *nb = (SVG_Number *)gf_list_get(*b, i);
GF_SAFEALLOC(nc, SVG_Number)
svg_number_muladd(alpha, na, beta, nb, nc);
gf_list_add(*c, nc);
}
return GF_OK;
}
static GF_Err svg_numbers_copy(SVG_Numbers *a, SVG_Numbers *b)
{
u32 i, count;
count = gf_list_count(*a);
for (i = 0; i < count; i++) {
SVG_Coordinate *c = (SVG_Coordinate *)gf_list_get(*a, i);
gf_free(c);
}
gf_list_reset(*a);
count = gf_list_count(*b);
for (i = 0; i < count; i ++) {
SVG_Number *na;
GF_SAFEALLOC(na, SVG_Number)
if (!na) {
GF_LOG(GF_LOG_ERROR, GF_LOG_PARSER, ("[SVG Parsing] Cannot allocate SVG number\n"));
continue;
}
*na = *(SVG_Number *)gf_list_get(*b, i);
gf_list_add(*a, na);
}
return GF_OK;
}
#if USE_GF_PATH
static GF_Err svg_path_copy(SVG_PathData *a, SVG_PathData *b)
{
if (a->contours) gf_free(a->contours);
if (a->points) gf_free(a->points);
if (a->tags) gf_free(a->tags);
a->contours = (u32 *)gf_malloc(sizeof(u32)*b->n_contours);
a->points = (GF_Point2D *) gf_malloc(sizeof(GF_Point2D)*b->n_points);
a->tags = (u8 *) gf_malloc(sizeof(u8)*b->n_points);
memcpy(a->contours, b->contours, sizeof(u32)*b->n_contours);
a->n_contours = b->n_contours;
memcpy(a->points, b->points, sizeof(GF_Point2D)*b->n_points);
memcpy(a->tags, b->tags, sizeof(u8)*b->n_points);
a->n_alloc_points = a->n_points = b->n_points;
a->flags = b->flags;
a->bbox = b->bbox;
a->fineness = b->fineness;
return GF_OK;
}
#else
static GF_Err svg_path_copy(SVG_PathData *a, SVG_PathData *b)
{
u32 i, count;
count = gf_list_count(a->commands);
for (i = 0; i < count; i++) {
u8 *command = (u8 *)gf_list_get(a->commands, i);
gf_free(command);
}
gf_list_reset(a->commands);
count = gf_list_count(a->points);
for (i = 0; i < count; i++) {
SVG_Point *pt = (SVG_Point *)gf_list_get(a->points, i);
gf_free(pt);
}
gf_list_reset(a->points);
count = gf_list_count(b->commands);
for (i = 0; i < count; i ++) {
u8 *nc = (u8 *)gf_malloc(sizeof(u8));
*nc = *(u8*)gf_list_get(b->commands, i);
gf_list_add(a->commands, nc);
}
count = gf_list_count(b->points);
for (i = 0; i < count; i ++) {
SVG_Point *pta;
GF_SAFEALLOC(pta, SVG_Point)
*pta = *(SVG_Point *)gf_list_get(b->points, i);
gf_list_add(a->points, pta);
}
return GF_OK;
}
#endif
#if USE_GF_PATH
static GF_Err svg_path_muladd(Fixed alpha, SVG_PathData *a, Fixed beta, SVG_PathData *b, SVG_PathData *c)
{
u32 i;
if (a->n_points != b->n_points) return GF_BAD_PARAM;
gf_path_reset(c);
svg_path_copy(c, a);
for (i=0; i<a->n_points; i++) {
svg_point_muladd(alpha, (SVG_Point *) &a->points[i], beta, (SVG_Point *) &b->points[i], (SVG_Point *) &c->points[i]);
}
c->flags |= GF_PATH_BBOX_DIRTY;
c->flags &= ~GF_PATH_FLATTENED;
return GF_OK;
}
#else
static GF_Err svg_path_muladd(Fixed alpha, SVG_PathData *a, Fixed beta, SVG_PathData *b, SVG_PathData *c)
{
u32 i, ccount, pcount;
ccount = gf_list_count(a->commands);
pcount = gf_list_count(a->points);
if (pcount != gf_list_count(b->points)) return GF_BAD_PARAM;
#if 0
if (ccount != gf_list_count(b->commands)) return GF_BAD_PARAM;
for (i = 0; i < ccount; i++) {
u8 *ac = gf_list_get(a->commands, i);
u8 *bc = gf_list_get(b->commands, i);
if (*ac != *bc) return GF_BAD_PARAM;
}
#endif
while (gf_list_count(c->commands)) {
u8 *command = (u8 *)gf_list_last(c->commands);
gf_free(command);
gf_list_rem_last(c->commands);
}
while (gf_list_count(c->points)) {
SVG_Point *pt = (SVG_Point *)gf_list_last(c->points);
gf_free(pt);
gf_list_rem_last(c->points);
}
for (i = 0; i < ccount; i++) {
u8 *nc = (u8 *)gf_malloc(sizeof(u8));
*nc = *(u8*)gf_list_get(a->commands, i);
gf_list_add(c->commands, nc);
}
for (i = 0; i < pcount; i++) {
SVG_Point *pta = (SVG_Point *)gf_list_get(a->points, i);
SVG_Point *ptb = (SVG_Point *)gf_list_get(b->points, i);
SVG_Point *ptc;
GF_SAFEALLOC(ptc, SVG_Point)
svg_point_muladd(alpha, pta, beta, ptb, ptc);
gf_list_add(c->points, ptc);
}
return GF_OK;
}
#endif
static GF_Err svg_dasharray_muladd(Fixed alpha, SVG_StrokeDashArray *a, Fixed beta, SVG_StrokeDashArray *b, SVG_StrokeDashArray *c)
{
u32 i;
if (a->type != b->type) return GF_BAD_PARAM;
if (a->array.count != b->array.count) return GF_BAD_PARAM;
c->type = a->type;
c->array.count = a->array.count;
c->array.vals = (Fixed *) gf_malloc(sizeof(Fixed)*c->array.count);
for (i = 0; i < c->array.count; i++) {
/* TODO: convert units if needed */
c->array.units[i] = a->array.units[i];
c->array.vals[i] = gf_mulfix(alpha, a->array.vals[i]) + gf_mulfix(beta, b->array.vals[i]);
}
return GF_OK;
}
static GF_Err svg_dasharray_copy(SVG_StrokeDashArray *a, SVG_StrokeDashArray *b)
{
a->type = b->type;
a->array.count = b->array.count;
a->array.units = (u8*)gf_malloc(sizeof(u8)*a->array.count);
memcpy(a->array.units, b->array.units, sizeof(u8)*a->array.count);
a->array.vals = (Fixed*)gf_malloc(sizeof(Fixed)*a->array.count);
memcpy(a->array.vals, b->array.vals, sizeof(Fixed)*a->array.count);
return GF_OK;
}
static GF_Err svg_matrix_muladd(Fixed alpha, GF_Matrix2D *a, Fixed beta, GF_Matrix2D *b, GF_Matrix2D *c)
{
/*
if ((alpha == beta) && (alpha == FIX_ONE) ) {
GF_Matrix2D tmp;
gf_mx2d_copy(tmp, *b);
gf_mx2d_add_matrix(&tmp, a);
gf_mx2d_copy(*c, tmp);
} else */
if (alpha <= FIX_ONE) {
/* This case should happen only when using animateMotion and accumulation
see animate-elem-202-t.svg
we only add and multiply the translation component; */
/*
c->m[0] = gf_mulfix(alpha, a->m[0]) + gf_mulfix(beta, b->m[0]);
c->m[1] = gf_mulfix(alpha, a->m[1]) + gf_mulfix(beta, b->m[1]);
c->m[2] = gf_mulfix(alpha, a->m[2]) + gf_mulfix(beta, b->m[2]);
c->m[3] = gf_mulfix(alpha, a->m[3]) + gf_mulfix(beta, b->m[3]);
*/
c->m[0] = a->m[0];
c->m[1] = a->m[1];
c->m[2] = gf_mulfix(alpha, a->m[2]) + gf_mulfix(beta, b->m[2]);
c->m[3] = a->m[3];
c->m[4] = a->m[4];
c->m[5] = gf_mulfix(alpha, a->m[5]) + gf_mulfix(beta, b->m[5]);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_BAD_PARAM;
}
return GF_OK;
}
static GF_Err laser_size_muladd(Fixed alpha, LASeR_Size *sza, Fixed beta, LASeR_Size *szb, LASeR_Size *szc)
{
szc->width = gf_mulfix(alpha, sza->width) + gf_mulfix(beta, szb->width);
szc->height = gf_mulfix(alpha, sza->height) + gf_mulfix(beta, szb->height);
return GF_OK;
}
/* c = alpha * a + beta * b */
GF_Err gf_svg_attributes_muladd(Fixed alpha, GF_FieldInfo *a,
Fixed beta, GF_FieldInfo *b,
GF_FieldInfo *c,
Bool clamp)
{
if (!a->far_ptr || !b->far_ptr || !c->far_ptr) return GF_BAD_PARAM;
if (a->fieldType != b->fieldType) {
if (a->fieldType != SVG_Transform_datatype &&
a->fieldType != SVG_Transform_Scale_datatype &&
a->fieldType != SVG_Transform_Translate_datatype &&
a->fieldType != SVG_Transform_Rotate_datatype &&
a->fieldType != SVG_Transform_SkewX_datatype &&
a->fieldType != SVG_Transform_SkewY_datatype &&
a->fieldType != SVG_Motion_datatype)
return GF_BAD_PARAM;
}
/* by default a and c are of the same type, except for matrix related types */
c->fieldType = a->fieldType;
switch (a->fieldType) {
/* Numeric types */
case SVG_Color_datatype:
return svg_color_muladd(alpha, (SVG_Color*)a->far_ptr, beta, (SVG_Color*)b->far_ptr, (SVG_Color*)c->far_ptr, clamp);
case SVG_Paint_datatype:
{
SVG_Paint *pa = (SVG_Paint *)a->far_ptr;
SVG_Paint *pb = (SVG_Paint *)b->far_ptr;
SVG_Paint *pc = (SVG_Paint *)c->far_ptr;
if (pa->type != pb->type || pa->type != SVG_PAINT_COLOR || pb->type != SVG_PAINT_COLOR) {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] only color paints are additive\n"));
return GF_BAD_PARAM;
}
pc->type = SVG_PAINT_COLOR;
return svg_color_muladd(alpha, &pa->color, beta, &pb->color, &pc->color, clamp);
}
case SVG_Number_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_FontSize_datatype:
return svg_number_muladd(alpha, (SVG_Number*)a->far_ptr, beta, (SVG_Number*)b->far_ptr, (SVG_Number*)c->far_ptr);
case SVG_ViewBox_datatype:
return svg_viewbox_muladd(alpha, (SVG_ViewBox*)a->far_ptr, beta, (SVG_ViewBox*)b->far_ptr, (SVG_ViewBox*)c->far_ptr);
case SVG_Points_datatype:
return svg_points_muladd(alpha, (GF_List **)a->far_ptr, beta, (GF_List **)b->far_ptr, (GF_List **)c->far_ptr);
case SVG_Numbers_datatype:
case SVG_Coordinates_datatype:
return svg_numbers_muladd(alpha, (GF_List **)a->far_ptr, beta, (GF_List **)b->far_ptr, (GF_List **)c->far_ptr);
case SVG_PathData_datatype:
return svg_path_muladd(alpha, (SVG_PathData*)a->far_ptr, beta, (SVG_PathData*)b->far_ptr, (SVG_PathData*)c->far_ptr);
case SVG_StrokeDashArray_datatype:
return svg_dasharray_muladd(alpha, (SVG_StrokeDashArray*)a->far_ptr, beta, (SVG_StrokeDashArray*)b->far_ptr, (SVG_StrokeDashArray*)c->far_ptr);
case SVG_Motion_datatype:
return svg_matrix_muladd(alpha, (GF_Matrix2D*)a->far_ptr, beta, (GF_Matrix2D*)b->far_ptr, (GF_Matrix2D*)c->far_ptr);
case SVG_Transform_datatype:
if (b->fieldType == SVG_Transform_datatype) {
SVG_Transform *ta = (SVG_Transform *)a->far_ptr;
SVG_Transform *tb = (SVG_Transform *)b->far_ptr;
SVG_Transform *tc = (SVG_Transform *)c->far_ptr;
if (ta->is_ref == tb->is_ref) {
return svg_matrix_muladd(alpha, &ta->mat, beta, &tb->mat, &tc->mat);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
} else {
/* a and c are matrices but b is not */
GF_Matrix2D tmp;
/*TOCHECK what is this test*/
/*
if (alpha != FIX_ONE) {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
*/
gf_mx2d_init(tmp);
switch (b->fieldType) {
case SVG_Transform_Translate_datatype:
gf_mx2d_add_translation(&tmp, gf_mulfix(((SVG_Point *)b->far_ptr)->x, beta), gf_mulfix(((SVG_Point *)b->far_ptr)->y, beta));
break;
case SVG_Transform_Scale_datatype:
gf_mx2d_add_scale(&tmp, gf_mulfix(((SVG_Point *)b->far_ptr)->x, beta), gf_mulfix(((SVG_Point *)b->far_ptr)->y, beta));
break;
case SVG_Transform_Rotate_datatype:
gf_mx2d_add_rotation(&tmp, gf_mulfix(((SVG_Point_Angle *)b->far_ptr)->x, beta), gf_mulfix(((SVG_Point_Angle *)b->far_ptr)->y, beta), gf_mulfix(((SVG_Point_Angle *)b->far_ptr)->angle, beta));
break;
case SVG_Transform_SkewX_datatype:
gf_mx2d_add_skew_x(&tmp, gf_mulfix(*(Fixed*)b->far_ptr, beta));
break;
case SVG_Transform_SkewY_datatype:
gf_mx2d_add_skew_y(&tmp, gf_mulfix(*(Fixed*)b->far_ptr, beta));
break;
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] copy of attributes %s not supported\n", a->name));
return GF_NOT_SUPPORTED;
}
gf_mx2d_add_matrix(&tmp, &((SVG_Transform*)a->far_ptr)->mat);
gf_mx2d_copy(((SVG_Transform*)c->far_ptr)->mat, tmp);
return GF_OK;
}
case SVG_Transform_Translate_datatype:
if (b->fieldType == SVG_Transform_Translate_datatype) {
return svg_point_muladd(alpha, (SVG_Point*)a->far_ptr, beta, (SVG_Point*)b->far_ptr, (SVG_Point*)c->far_ptr);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
case SVG_Transform_Scale_datatype:
if (b->fieldType == SVG_Transform_Scale_datatype) {
if (alpha == FIX_ONE && beta == FIX_ONE) {
/* addition of matrices which represent scales is equivalent
to multiplication of scale coefficients, we assume this only happens if
alpha and beta are set to one */
((SVG_Point*)c->far_ptr)->x = gf_mulfix(((SVG_Point*)a->far_ptr)->x,((SVG_Point*)b->far_ptr)->x);
((SVG_Point*)c->far_ptr)->y = gf_mulfix(((SVG_Point*)a->far_ptr)->y,((SVG_Point*)b->far_ptr)->y);
return GF_OK;
} else {
return svg_point_muladd(alpha, (SVG_Point*)a->far_ptr, beta, (SVG_Point*)b->far_ptr, (SVG_Point*)c->far_ptr);
}
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
case SVG_Transform_Rotate_datatype:
if (b->fieldType == SVG_Transform_Rotate_datatype) {
return svg_point_angle_muladd(alpha, (SVG_Point_Angle*)a->far_ptr, beta, (SVG_Point_Angle*)b->far_ptr, (SVG_Point_Angle*)c->far_ptr);
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
case SVG_Transform_SkewX_datatype:
if (b->fieldType == SVG_Transform_SkewX_datatype) {
*(Fixed*)c->far_ptr = gf_mulfix(alpha, *(Fixed*)a->far_ptr) + gf_mulfix(beta, *(Fixed*)b->far_ptr);
return GF_OK;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
case SVG_Transform_SkewY_datatype:
if (b->fieldType == SVG_Transform_SkewY_datatype) {
*(Fixed*)c->far_ptr = gf_mulfix(alpha, *(Fixed*)a->far_ptr) + gf_mulfix(beta, *(Fixed*)b->far_ptr);
return GF_OK;
} else {
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] matrix operations not supported\n"));
return GF_NOT_SUPPORTED;
}
case DOM_String_datatype:
{
u32 len;
char *res;
SVG_String *s_a = (SVG_String *)a->far_ptr;
SVG_String *s_b = (SVG_String *)b->far_ptr;
u32 len_a = (u32) strlen(*s_a);
u32 len_b = (u32) strlen(*s_b);
len_a = FIX2INT(alpha * len_a);
len_b = FIX2INT(beta * len_b);
len = len_a + len_b + 1;
res = (char*)gf_malloc(sizeof(char) * len);
memcpy(res, *s_a, len_a);
memcpy(res+len_a, *s_b, len_b);
res[len-1] = 0;
s_a = (SVG_String*)c->far_ptr;
if (*s_a) gf_free(*s_a);
*s_a = res;
}
break;
case LASeR_Size_datatype:
laser_size_muladd(alpha, (LASeR_Size*)a->far_ptr, beta, (LASeR_Size*)b->far_ptr, (LASeR_Size*)c->far_ptr);
break;
/* Keyword types */
case SVG_Boolean_datatype:
case SVG_FillRule_datatype:
case SVG_StrokeLineJoin_datatype:
case SVG_StrokeLineCap_datatype:
case SVG_FontStyle_datatype:
case SVG_FontWeight_datatype:
case SVG_FontVariant_datatype:
case SVG_TextAnchor_datatype:
case SVG_Display_datatype:
case SVG_Visibility_datatype:
case SVG_GradientUnit_datatype:
case SVG_PreserveAspectRatio_datatype:
case XML_Space_datatype:
case XMLEV_Propagate_datatype:
case XMLEV_DefaultAction_datatype:
case XMLEV_Phase_datatype:
case SMIL_SyncBehavior_datatype:
case SMIL_SyncTolerance_datatype:
case SMIL_AttributeType_datatype:
case SMIL_CalcMode_datatype:
case SMIL_Additive_datatype:
case SMIL_Accumulate_datatype:
case SMIL_Restart_datatype:
case SMIL_Fill_datatype:
case SVG_Overflow_datatype:
case SVG_ZoomAndPan_datatype:
case SVG_DisplayAlign_datatype:
case SVG_TextAlign_datatype:
case SVG_PointerEvents_datatype:
case SVG_RenderingHint_datatype:
case SVG_VectorEffect_datatype:
case SVG_PlaybackOrder_datatype:
case SVG_TimelineBegin_datatype:
case SVG_SpreadMethod_datatype:
case SVG_TransformType_datatype:
/* Unsupported types */
case SVG_ContentType_datatype:
case SVG_LanguageID_datatype:
case SVG_FontFamily_datatype:
case XMLRI_datatype:
case XMLRI_List_datatype:
case DOM_StringList_datatype:
case SVG_Clock_datatype:
case SVG_Focus_datatype:
case SVG_ID_datatype:
case SVG_GradientOffset_datatype:
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
case SMIL_AnimateValue_datatype:
case SMIL_AnimateValues_datatype:
case SMIL_AttributeName_datatype:
case SMIL_Times_datatype:
case SMIL_Duration_datatype:
case SMIL_RepeatCount_datatype:
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_INTERACT, ("[SVG Attributes] addition for attributes %s of type %s not supported\n", a->name, gf_svg_attribute_type_to_string(a->fieldType)));
return GF_NOT_SUPPORTED;
}
return GF_OK;
}
/* *a = *b, copy by value */
GF_EXPORT
GF_Err gf_svg_attributes_copy(GF_FieldInfo *a, GF_FieldInfo *b, Bool clamp)
{
if (!a->far_ptr || !b->far_ptr) return GF_BAD_PARAM;
switch (a->fieldType) {
/* Numeric types */
case SVG_Color_datatype:
*((SVG_Color *)a->far_ptr) = *((SVG_Color *)b->far_ptr);
if (clamp) svg_color_clamp((SVG_Color *)a->far_ptr);
break;
case SVG_Paint_datatype:
{
SVG_Paint *pa = (SVG_Paint *)a->far_ptr;
SVG_Paint *pb = (SVG_Paint *)b->far_ptr;
pa->type = pb->type;
if (pb->type == SVG_PAINT_URI) {
GF_FieldInfo tmp_a, tmp_b;
tmp_a.fieldType = tmp_b.fieldType = XMLRI_datatype;
tmp_a.far_ptr = &pa->iri;
tmp_b.far_ptr = &pb->iri;
gf_svg_attributes_copy(&tmp_a, &tmp_b, 0);
} else {
pa->color = pb->color;
}
return GF_OK;
}
break;
case SVG_Number_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_FontSize_datatype:
*((SVG_Number *)a->far_ptr) = *((SVG_Number *)b->far_ptr);
break;
case SVG_ViewBox_datatype:
*((SVG_ViewBox *)a->far_ptr) = *((SVG_ViewBox *)b->far_ptr);
break;
case SVG_Points_datatype:
return svg_points_copy((GF_List**)a->far_ptr, (GF_List**)b->far_ptr);
case SVG_Numbers_datatype:
case SVG_Coordinates_datatype:
return svg_numbers_copy((GF_List**)a->far_ptr, (GF_List**)b->far_ptr);
case SVG_PathData_datatype:
return svg_path_copy((SVG_PathData*)a->far_ptr, (SVG_PathData*)b->far_ptr);
case SVG_StrokeDashArray_datatype:
return svg_dasharray_copy((SVG_StrokeDashArray*)a->far_ptr, (SVG_StrokeDashArray*)b->far_ptr);
case SVG_Motion_datatype:
gf_mx2d_copy(*(GF_Matrix2D *)a->far_ptr, *(GF_Matrix2D *)b->far_ptr);
return GF_OK;
case SVG_Transform_datatype:
switch (b->fieldType) {
case SVG_Transform_Translate_datatype:
gf_mx2d_init(((SVG_Transform *)a->far_ptr)->mat);
gf_mx2d_add_translation(&((SVG_Transform *)a->far_ptr)->mat, ((SVG_Point*)b->far_ptr)->x, ((SVG_Point*)b->far_ptr)->y);
break;
case SVG_Transform_Scale_datatype:
gf_mx2d_init(((SVG_Transform *)a->far_ptr)->mat);
gf_mx2d_add_scale(&((SVG_Transform *)a->far_ptr)->mat, ((SVG_Point*)b->far_ptr)->x, ((SVG_Point*)b->far_ptr)->y);
break;
case SVG_Transform_Rotate_datatype:
gf_mx2d_init(((SVG_Transform *)a->far_ptr)->mat);
gf_mx2d_add_rotation(&((SVG_Transform *)a->far_ptr)->mat, ((SVG_Point_Angle*)b->far_ptr)->x, ((SVG_Point_Angle*)b->far_ptr)->y, ((SVG_Point_Angle*)b->far_ptr)->angle);
break;
case SVG_Transform_SkewX_datatype:
gf_mx2d_init(((SVG_Transform *)a->far_ptr)->mat);
gf_mx2d_add_skew_x(&((SVG_Transform *)a->far_ptr)->mat, *(Fixed *)b->far_ptr);
break;
case SVG_Transform_SkewY_datatype:
gf_mx2d_init(((SVG_Transform *)a->far_ptr)->mat);
gf_mx2d_add_skew_y(&((SVG_Transform *)a->far_ptr)->mat, *(Fixed *)b->far_ptr);
break;
case SVG_Transform_datatype:
gf_mx2d_copy(((SVG_Transform *)a->far_ptr)->mat, ((SVG_Transform *)b->far_ptr)->mat);
break;
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_INTERACT, ("[SVG Attributes] forbidden type of transform\n"));
return GF_NOT_SUPPORTED;
}
return GF_OK;
/* Keyword types */
case SVG_Boolean_datatype:
case SVG_FillRule_datatype:
case SVG_StrokeLineJoin_datatype:
case SVG_StrokeLineCap_datatype:
case SVG_FontStyle_datatype:
case SVG_FontWeight_datatype:
case SVG_FontVariant_datatype:
case SVG_TextAnchor_datatype:
case SVG_Display_datatype:
case SVG_Visibility_datatype:
case SVG_GradientUnit_datatype:
case SVG_PreserveAspectRatio_datatype:
case XML_Space_datatype:
case XMLEV_Propagate_datatype:
case XMLEV_DefaultAction_datatype:
case XMLEV_Phase_datatype:
case SMIL_SyncBehavior_datatype:
case SMIL_AttributeType_datatype:
case SMIL_CalcMode_datatype:
case SMIL_Additive_datatype:
case SMIL_Accumulate_datatype:
case SMIL_Restart_datatype:
case SMIL_Fill_datatype:
case SVG_Overflow_datatype:
case SVG_ZoomAndPan_datatype:
case SVG_DisplayAlign_datatype:
case SVG_TextAlign_datatype:
case SVG_PointerEvents_datatype:
case SVG_RenderingHint_datatype:
case SVG_VectorEffect_datatype:
case SVG_PlaybackOrder_datatype:
case SVG_TimelineBegin_datatype:
case SVG_TransformType_datatype:
case SVG_Focusable_datatype:
case SVG_FocusHighlight_datatype:
*(u8 *)a->far_ptr = *(u8 *)b->far_ptr;
return GF_OK;
case SMIL_SyncTolerance_datatype:
*(SMIL_SyncTolerance*)a->far_ptr = *(SMIL_SyncTolerance*)b->far_ptr;
return GF_OK;
/* Other types */
case SVG_ID_datatype:
case SVG_LanguageID_datatype:
case SVG_ContentType_datatype:
case DOM_String_datatype:
if (* (SVG_String *)a->far_ptr) gf_free(* (SVG_String *)a->far_ptr);
* (SVG_String *)a->far_ptr = *(SVG_String *)b->far_ptr ? gf_strdup(*(SVG_String *)b->far_ptr) : NULL;
return GF_OK;
case SVG_FontFamily_datatype:
((SVG_FontFamily *)a->far_ptr)->type = ((SVG_FontFamily *)b->far_ptr)->type;
if ( ((SVG_FontFamily *)a->far_ptr)->value) gf_free( ((SVG_FontFamily *)a->far_ptr)->value );
((SVG_FontFamily *)a->far_ptr)->value = (((SVG_FontFamily *)b->far_ptr)->value ? gf_strdup(((SVG_FontFamily *)b->far_ptr)->value) : NULL );
return GF_OK;
case XMLRI_datatype:
case XML_IDREF_datatype:
((XMLRI *)a->far_ptr)->type = ((XMLRI *)b->far_ptr)->type;
if (((XMLRI *)a->far_ptr)->string) gf_free(((XMLRI *)a->far_ptr)->string);
if (((XMLRI *)b->far_ptr)->string) {
((XMLRI *)a->far_ptr)->string = gf_strdup(((XMLRI *)b->far_ptr)->string);
} else {
((XMLRI *)a->far_ptr)->string = gf_strdup("");
}
((XMLRI *)a->far_ptr)->target = ((XMLRI *)b->far_ptr)->target;
if (((XMLRI *)a->far_ptr)->type == XMLRI_ELEMENTID) {
GF_Node *n = (GF_Node *) ((XMLRI *)b->far_ptr)->target;
/*TODO Check if assigning IRI from # scenegraph can happen*/
if (n) gf_node_register_iri(gf_node_get_graph(n), (XMLRI*)a->far_ptr);
}
return GF_OK;
case SVG_Focus_datatype:
{
((SVG_Focus *)a->far_ptr)->type = ((SVG_Focus *)b->far_ptr)->type;
if ( ((SVG_Focus *)b->far_ptr)->target.string)
((SVG_Focus *)a->far_ptr)->target.string = gf_strdup( ((SVG_Focus *)b->far_ptr)->target.string);
}
return GF_OK;
case SMIL_Times_datatype:
{
u32 i, count;
GF_List *dst = *(GF_List **)a->far_ptr;
GF_List *src = *(GF_List **)b->far_ptr;
while (gf_list_count(dst)) {
SMIL_Time *t = gf_list_get(dst, 0);
gf_list_rem(dst, 0);
gf_free(t);
}
count = gf_list_count(src);
for (i=0; i<count; i++) {
SMIL_Time *t2;
SMIL_Time *t = gf_list_get(src, i);
t2 = (SMIL_Time*)gf_malloc(sizeof(SMIL_Time));
memcpy(t2, t, sizeof(SMIL_Time));
gf_list_add(dst, t2);
}
}
return GF_OK;
case SMIL_AttributeName_datatype:
{
SMIL_AttributeName *saa = (SMIL_AttributeName *)a->far_ptr;
SMIL_AttributeName *sab = (SMIL_AttributeName *)b->far_ptr;
saa->tag = sab->tag;
saa->type = sab->type;
saa->name = sab->name ? gf_strdup(sab->name) : NULL;
}
break;
case SMIL_Duration_datatype:
{
SMIL_Duration *da = (SMIL_Duration*)a->far_ptr;
SMIL_Duration *db = (SMIL_Duration*)b->far_ptr;
da->type = db->type;
da->clock_value = db->clock_value;
}
break;
case SMIL_AnimateValue_datatype:
{
SMIL_AnimateValue *sa = (SMIL_AnimateValue*)a->far_ptr;
SMIL_AnimateValue *sb = (SMIL_AnimateValue*)b->far_ptr;
sa->type = sb->type;
if (sb->value) {
GF_FieldInfo ava, avb;
sa->value = gf_svg_create_attribute_value(sa->type);
ava.fieldIndex = avb.fieldIndex = 0;
ava.fieldType = avb.fieldType = sb->type;
ava.far_ptr = sa->value;
avb.far_ptr = sb->value;
gf_svg_attributes_copy(&ava, &avb, 0);
}
}
break;
/* Unsupported types */
case XMLRI_List_datatype:
case DOM_StringList_datatype:
case SVG_GradientOffset_datatype:
case SVG_Clock_datatype:
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
case SMIL_AnimateValues_datatype:
case SMIL_RepeatCount_datatype:
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_INTERACT, ("[SVG Attributes] copy of attributes %s of type %s not supported\n", a->name, gf_svg_attribute_type_to_string(a->fieldType)));
return GF_OK;
}
return GF_OK;
}
/* c = a + b */
GF_Err gf_svg_attributes_add(GF_FieldInfo *a, GF_FieldInfo *b, GF_FieldInfo *c, Bool clamp)
{
return gf_svg_attributes_muladd(FIX_ONE, a, FIX_ONE, b, c, clamp);
}
Bool gf_svg_attribute_is_interpolatable(u32 type)
{
switch (type) {
/* additive types which can really be interpolated */
case SVG_Color_datatype:
case SVG_Paint_datatype:
case SVG_Number_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_FontSize_datatype:
case SVG_ViewBox_datatype:
case SVG_Points_datatype:
case SVG_Numbers_datatype:
case SVG_Coordinates_datatype:
case SVG_PathData_datatype:
case SVG_Motion_datatype:
case SVG_Transform_datatype:
case SVG_Transform_Translate_datatype:
case SVG_Transform_Scale_datatype:
case SVG_Transform_Rotate_datatype:
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
case LASeR_Size_datatype:
return 1;
}
return 0;
}
GF_Err gf_svg_attributes_interpolate(GF_FieldInfo *a, GF_FieldInfo *b, GF_FieldInfo *c, Fixed coef, Bool clamp)
{
if (!a->far_ptr || !b->far_ptr || !c->far_ptr) return GF_BAD_PARAM;
c->fieldType = a->fieldType;
switch (a->fieldType) {
/* additive types which can really be interpolated */
case SVG_Color_datatype:
case SVG_Paint_datatype:
case SVG_Number_datatype:
case SVG_Length_datatype:
case SVG_Coordinate_datatype:
case SVG_FontSize_datatype:
case SVG_ViewBox_datatype:
case SVG_Points_datatype:
case SVG_Numbers_datatype:
case SVG_Coordinates_datatype:
case SVG_PathData_datatype:
case SVG_Motion_datatype:
case SVG_Transform_datatype:
case SVG_Transform_Translate_datatype:
case SVG_Transform_Scale_datatype:
case SVG_Transform_Rotate_datatype:
case SVG_Transform_SkewX_datatype:
case SVG_Transform_SkewY_datatype:
case LASeR_Size_datatype:
return gf_svg_attributes_muladd(FIX_ONE-coef, a, coef, b, c, clamp);
/* discrete types: interpolation is the selection of one of the 2 values
using the coeff and a the 0.5 threshold */
/* Keyword types */
case SVG_Boolean_datatype:
case SVG_FillRule_datatype:
case SVG_StrokeLineJoin_datatype:
case SVG_StrokeLineCap_datatype:
case SVG_FontStyle_datatype:
case SVG_FontWeight_datatype:
case SVG_FontVariant_datatype:
case SVG_TextAnchor_datatype:
case SVG_Display_datatype:
case SVG_Visibility_datatype:
case SVG_GradientUnit_datatype:
case SVG_PreserveAspectRatio_datatype:
case SVG_TransformType_datatype:
case XML_Space_datatype:
case XMLEV_Propagate_datatype:
case XMLEV_DefaultAction_datatype:
case XMLEV_Phase_datatype:
case SMIL_SyncBehavior_datatype:
case SMIL_SyncTolerance_datatype:
case SMIL_AttributeType_datatype:
case SMIL_CalcMode_datatype:
case SMIL_Additive_datatype:
case SMIL_Accumulate_datatype:
case SMIL_Restart_datatype:
case SMIL_Fill_datatype:
case SVG_Overflow_datatype:
case SVG_ZoomAndPan_datatype:
case SVG_DisplayAlign_datatype:
case SVG_TextAlign_datatype:
case SVG_PointerEvents_datatype:
case SVG_RenderingHint_datatype:
case SVG_VectorEffect_datatype:
case SVG_PlaybackOrder_datatype:
case SVG_TimelineBegin_datatype:
/* Other non keyword types but which can still be discretely interpolated */
case DOM_String_datatype:
case SVG_ContentType_datatype:
case SVG_LanguageID_datatype:
case SVG_FontFamily_datatype:
case XMLRI_datatype:
case XMLRI_List_datatype:
case DOM_StringList_datatype:
case SVG_Clock_datatype:
case SVG_ID_datatype:
case SVG_GradientOffset_datatype:
case LASeR_Choice_datatype:
if (coef < FIX_ONE/2) {
gf_svg_attributes_copy(c, a, clamp);
} else {
gf_svg_attributes_copy(c, b, clamp);
}
return GF_OK;
/* Unsupported types */
case SMIL_KeyTimes_datatype:
case SMIL_KeyPoints_datatype:
case SMIL_KeySplines_datatype:
case SMIL_AnimateValue_datatype:
case SMIL_AnimateValues_datatype:
case SMIL_AttributeName_datatype:
case SMIL_Times_datatype:
case SMIL_Duration_datatype:
case SMIL_RepeatCount_datatype:
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_INTERACT, ("[SVG Attributes] interpolation for attributes %s of type %s not supported\n", a->name, gf_svg_attribute_type_to_string(a->fieldType)));
return GF_OK;
}
return GF_OK;
}
Bool gf_svg_is_current_color(GF_FieldInfo *a)
{
switch (a->fieldType) {
case SVG_Color_datatype:
return (((SVG_Color *)a->far_ptr)->type == SVG_COLOR_CURRENTCOLOR);
break;
case SVG_Paint_datatype:
if ( ((SVG_Paint *)a->far_ptr)->type == SVG_PAINT_COLOR) {
return (((SVG_Paint *)a->far_ptr)->color.type == SVG_COLOR_CURRENTCOLOR);
} else {
return 0;
}
break;
}
return 0;
}
char *gf_svg_attribute_type_to_string(u32 att_type)
{
switch (att_type) {
case SVG_FillRule_datatype:
return "FillRule";
case SVG_StrokeLineJoin_datatype:
return "StrokeLineJoin";
case SVG_StrokeLineCap_datatype:
return "StrokeLineCap";
case SVG_FontStyle_datatype:
return "FontStyle";
case SVG_FontWeight_datatype:
return "FontWeight";
case SVG_FontVariant_datatype:
return "FontVariant";
case SVG_TextAnchor_datatype:
return "TextAnchor";
case SVG_TransformType_datatype:
return "TransformType";
case SVG_Display_datatype:
return "Display";
case SVG_Visibility_datatype:
return "Visibility";
case SVG_Overflow_datatype:
return "Overflow";
case SVG_ZoomAndPan_datatype:
return "ZoomAndPan";
case SVG_DisplayAlign_datatype:
return "DisplayAlign";
case SVG_PointerEvents_datatype:
return "PointerEvents";
case SVG_RenderingHint_datatype:
return "RenderingHint";
case SVG_VectorEffect_datatype:
return "VectorEffect";
case SVG_PlaybackOrder_datatype:
return "PlaybackOrder";
case SVG_TimelineBegin_datatype:
return "TimelineBegin";
case XML_Space_datatype:
return "XML_Space";
case XMLEV_Propagate_datatype:
return "XMLEV_Propagate";
case XMLEV_DefaultAction_datatype:
return "XMLEV_DefaultAction";
case XMLEV_Phase_datatype:
return "XMLEV_Phase";
case SMIL_SyncBehavior_datatype:
return "SMIL_SyncBehavior";
case SMIL_SyncTolerance_datatype:
return "SMIL_SyncTolerance";
case SMIL_AttributeType_datatype:
return "SMIL_AttributeType";
case SMIL_CalcMode_datatype:
return "SMIL_CalcMode";
case SMIL_Additive_datatype:
return "SMIL_Additive";
case SMIL_Accumulate_datatype:
return "SMIL_Accumulate";
case SMIL_Restart_datatype:
return "SMIL_Restart";
case SMIL_Fill_datatype:
return "SMIL_Fill";
case SVG_GradientUnit_datatype:
return "GradientUnit";
case SVG_InitialVisibility_datatype:
return "InitialVisibility";
case SVG_FocusHighlight_datatype:
return "FocusHighlight";
case SVG_Overlay_datatype:
return "Overlay";
case SVG_TransformBehavior_datatype:
return "TransformBehavior";
case SVG_SpreadMethod_datatype:
return "SpreadMethod";
case SVG_TextAlign_datatype:
return "TextAlign";
case SVG_Number_datatype:
return "Number";
case SVG_FontSize_datatype:
return "FontSize";
case SVG_Length_datatype:
return "Length";
case SVG_Coordinate_datatype:
return "Coordinate";
case SVG_Rotate_datatype:
return "Rotate";
case SVG_Numbers_datatype:
return "Numbers";
case SVG_Points_datatype:
return "Points";
case SVG_Coordinates_datatype:
return "Coordinates";
case DOM_StringList_datatype:
return "StringList";
case XMLRI_List_datatype:
return "ListOfIRI";
case SMIL_KeyTimes_datatype:
return "SMIL_KeyTimes";
case SMIL_KeySplines_datatype:
return "SMIL_KeySplines";
case SMIL_KeyPoints_datatype:
return "SMIL_KeyPoints";
case SMIL_Times_datatype:
return "SMIL_Times";
case SMIL_AnimateValue_datatype:
return "SMIL_AnimateValue";
case SMIL_AnimateValues_datatype:
return "SMIL_AnimateValues";
case SMIL_Duration_datatype:
return "SMIL_Duration";
case SMIL_RepeatCount_datatype:
return "SMIL_RepeatCount";
case SMIL_AttributeName_datatype:
return "SMIL_AttributeName";
case SVG_Boolean_datatype:
return "Boolean";
case SVG_Color_datatype:
return "Color";
case SVG_Paint_datatype:
return "Paint";
case SVG_PathData_datatype:
return "PathData";
case SVG_FontFamily_datatype:
return "FontFamily";
case SVG_ID_datatype:
return "ID";
case XMLRI_datatype:
return "IRI";
case XML_IDREF_datatype:
return "IDREF";
case SVG_StrokeDashArray_datatype:
return "StrokeDashArray";
case SVG_PreserveAspectRatio_datatype:
return "PreserveAspectRatio";
case SVG_ViewBox_datatype:
return "ViewBox";
case SVG_GradientOffset_datatype:
return "GradientOffset";
case SVG_Focus_datatype :
return "Focus";
case SVG_Clock_datatype :
return "Clock";
case DOM_String_datatype :
return "String";
case SVG_ContentType_datatype:
return "ContentType";
case SVG_LanguageID_datatype:
return "LanguageID";
case XMLEV_Event_datatype:
return "XMLEV_Event";
case SVG_Motion_datatype:
return "Motion";
case SVG_Transform_datatype:
return "Transform";
case SVG_Transform_Translate_datatype:
return "Translate";
case SVG_Transform_Scale_datatype:
return "Scale";
case SVG_Transform_SkewX_datatype:
return "SkewX";
case SVG_Transform_SkewY_datatype:
return "SkewY";
case SVG_Transform_Rotate_datatype:
return "Rotate";
case LASeR_Choice_datatype:
return "LASeR_Choice";
case LASeR_Size_datatype:
return "LASeR_Size";
default:
return "UnknownType";
}
}
#endif /*GPAC_DISABLE_SVG*/
|
#include "Entity/EnemyTwo.h"
#include "Manager/Map.h"
#include "Constants/TextureEnemyConstants.h"
EnemyTwo::EnemyTwo(SDL_Texture* tex, unsigned int tile_size, unsigned int val_x, unsigned int val_y)
: Enemy(tex, tile_size, val_x, val_y)
{
m_speed = 74; //timer speed
m_move_speed = m_move_speed *m_tile_size/32; //speed according to 32px tile size
m_rotation_const = TEXTURE_ENEMY_TWO_COUNT;
m_enemy_size_w = TEXTURE_ENEMY_TWO_SIZE_W *tile_size/32;
m_enemy_size_h = TEXTURE_ENEMY_TWO_SIZE_H *tile_size/32; //size according to 32px tile size
}
void EnemyTwo::Draw(SDL_Renderer *renderer)
{
SDL_Rect SrcR;
SDL_Rect DestR;
SrcR.x = TEXTURE_ENEMY_TWO_X + (m_status % m_rotation_const) * TEXTURE_ENEMY_TWO_TEXTURE_OFFSET;
SrcR.y = TEXTURE_ENEMY_TWO_Y;
SrcR.w = TEXTURE_ENEMY_TWO_SOURCE_W;
SrcR.h = TEXTURE_ENEMY_TWO_SOURCE_H;
DestR.x = m_x;
DestR.y = m_y;
DestR.w = m_enemy_size_w;
DestR.h = m_enemy_size_h;
SDL_RenderCopy(renderer, m_tex, &SrcR, &DestR);
}
|
Multiple hypothesis tests in multiple investigations. Inferential statistical methods have traditionally been based on the assumption that one experiment is performed and that interest centres on one or more predetermined hypothesis tests. Exploratory research, on the other hand, often involves multiple hypotheses or repeated investigations under similar or different conditions or both. Several techniques have been proposed to deal with multiple or simultaneous hypothesis testing in single investigations, and procedures to combine observed significance levels for an individual hypothesis test from two or more investigations have been suggested. In this paper we propose a method for identifying important results from multiple statistical tests in multiple investigations. The method is illustrated by using high performance liquid chromatography to identify potential aetiologic contaminants in L-tryptophan samples. |
Only those who are committed to rejecting truth deny the successful response of Venezuelan citizens to the proposal made by President Nicolás Maduro (which is based on the 1999 Bolivarian Constitution) to elect a National Constituent Assembly. They stubbornly deny that, majoritarily, the country backed his project in unquestionable elections held on July 30 and that the opposition made a political mistake by choosing not to participate.
If—as happened afterwards—most of the MUD’s parties decided to participate in the electoral process to choose state governors, wouldn’t it have been more beneficial and coherent for the country and for the opposition to also participate in the process of electing the members of the National Constituent Assembly? Wouldn’t the MUD have been able to solve the problems it now faces, and be in better conditions to act in the current scenario? I don’t intend to give lessons in politics to experienced people, but just reflect on this fact to make things clear.
Acting legally requires coherence. It’s not advisable to act with ambiguity, eluding truth and seeking ways to deceive the adversary. I write this with emphasis, and it’s related to the current situation where the attitude of opposition leaders keeps their followers in tenterhooks. How can we explain this people that what they didn’t do in better circumstances than now (participate in the constituent election) is now done in a more difficult context?
But there is, in the way, another element of doubt that affects the credibility of the opposition. Both in the blatant declarations of some of their spokesmen as in their recent and past activity. I’m talking about the warning that those spokesmen slip, constantly, about a potential combination of “peaceful”,“democratic” ways with violent ones. In other words, they threaten to continue to act like they have done so far, for over 100 days, under the pretext of exercising their “right to protest peacefully”, on one hand, and the use of the most abhorrent forms of terrorism on the other.
The opposition constantly exhorts their followers to not let the streets “go cold”. They want permanent protests. But the country is already fully conscious (due to the experience of the latest terrorist activity) of what that means. That’s why the people actively participated in the July 30 elections—over eight million rejected violence and voted for peace. It would be against the will of the people to accept the thesis of the “double way”: acting in the realm of democracy and simultaneously using violence.
In the legal, political and institutional framework that was just created in Venezuela after this categorical national pronouncement in favor of peace and against violence, dualism is inadmissible. A choice has to be made between acting in the realm of violence or in the realm of peace. No-one can have both things. Whoever intends to break this basic principle of democracy, which is the rule of law, will be sanctioned according to the Constitution and the laws of the Republic, and whoever respects the juridical organization of the nation will enjoy every single one of the guarantees it provides. Venezuelans are beginning to enjoy the new climate that has been created after the people expressed themselves through the polls in July. These are the renovating effects of the Constituent process.
Clumsiness has been installed in the White House. President Donald Trump increasingly resembles a bull in a china shop. In the short time he has been in charge he has opened dangerous fronts in foreign policy, internal policy, finance and economy. He shows himself to the world as a thug. He easily falls for the routine provocations of the North Korean leader, who always manages to exasperate him. He toughens relations with Russia and China, and then backpedals with a levity that is improper for a president of the largest power in the world.
Trump’s banalization of power is shocking. Regarding Venezuela, his attitude has made Maduro a favor. With his threats of invasion, he has managed to change the stance—at least the public one—of the neoliberal leaders of the region: Colombia, Chile, Argentina, Brazil, Peru and Mexico. They went from a position of encouragement of interference in Venezuela’s internal affairs, and even military intervention, to condemning any such attempts after Trump spoke. The US president also left Venezuela’s internal opposition out on a limb: they had to come up with an absurd statement in which they reject a military intervention that they had previously demanded through a convoluted and ambiguous argument, which is revealing of the economic nature of that relation.
But we mustn’t underestimate this man. He is too powerful and represents an alliance of the darkest interests in the US. He’s the man of the most aggressive and voracious financial sector, a leader of the hawks of the Armed Forces and the intelligence and “security” organisms. The same ease with which he builds a clothing business for him or his daughter anywhere in the world, he can use to invade nations or use immoral commercial practices to his own interest. The destiny of the world in the hands of this son of the Empire is uncertain and unpredictable.
Venezuela is a target. We mustn’t forget that. Buet we must accept this challenge with intelligence, with creative audacity and with courage. As we Venezuelans have always been able to do when we face a challenge.
In the early hours of Sunday 13 this month, a group of mercenaries, paramilitaries, and retired and active officials of the Bolivarian Armed Forces of Venezuela, broke into this military unit and managed to get hold of about a hundred rifles and other weapons.
Of course, those who planned and executed this operation underestimated the troops’ ability to respond. That reaction, which frustrated other dark purposes of the plan, confirms that putschism has no future, and that those who act in those lines should reflect on its consequences.
The military institution has an answer, and everything indicates their willingness to repel any aggression and to sanction the wrongdoers with all the force of military justice. The High Command is aware of its responsibility, and also united in their respect for the law and in their defense of national sovereignty.
Until now, after this terrorist attack, some local political leaders have been proven to be involved, but the research also reveals names of renowned political figures. |
Amedeo Mecozzi
Early life and World War I
Amedeo Mecozzi was born on 17 January 1892 in Rome. Mecozzi was orphaned when young, and consequently raised by his grandparents. He joined the Italian Army as an engineer, and spent a year as a volunteer in Somalia before applying for pilot's training in 1915. In June 1915, he was accepted, and began training at Malpensa on 2 September. January 1916 saw him qualifying on Maurice Farman 12 and Maurice Farman 14 machines. On 1 February 1916 he received his pilot's certificate. In March 1916 he began flying reconnaissance missions for 45a Squadriglia, at some personal hazard; he often brought home an airplane damaged by enemy fire.
On 1 January 1917, he was commissioned as a sottotenente and reassigned to 50a Squadriglia. His determination to continue fighting despite battle damaged aircraft won him renown; on both 8 January and 19 February, he was granted a Bronze Medal for Military Valor. On 19 June 1917, he was shot down by bullets through his Farman's radiator. That same day, he was awarded the Croce di Guerra. In September 1917, he was forwarded to fighter pilot's training in Malpensa. On 4 October, he was promoted to tenente. He was then assigned back to the front with 76a Squadriglia on 12 October. The next month, he was assigned to 78a Squadriglia for his final wartime posting.
He scored his first victory the day after Christmas, 1917, teaming with his wingman to send an enemy reconnaissance plane down in flames. Mecozzi eagerly rushed off to the wreckage of his victim, only to find outraged farmers whose barn was burning along the wrecked plane.
On 26 May 1918, he used his Hanriot HD.1 to pick off a second recce machine with a hundred round burst, then ran his guns dry to down an Austro-Hungarian Albatros D.III from Fliegerkompanie 42j. On 15 June 1918, he teamed with Antonio Riva to down a Hansa-Brandenburg C.I. Also in June, Mecozzi was noted as changing his aircraft's insignia from a question mark on a black ball to two blue bands around the fuselage.
On 27 July, in conjunction with another pilot, he shot down Hansa-Brandenburg C.I No. 169.14 for his fifth victory. Mecozzi would go on to claim an observation balloon in June and three more planes in October 1918, but these four wins went unconfirmed. Mecozzi served with 78a Squadriglia past war's end, until February 1919.
Post World War I
Mecozzi was awarded the Silver Medal for Military Merit in the postwar honors list. The committee evaluating aerial victories confirmed five of his victories. He stayed in the military postwar and ascended through the ranks. Mecozzi was accepted for permanent service on 31 October 1919. He was a member of the Italian Aviation Mission to Paris. He also served with the Technical Directorate of the Italian Air Force at Montecelio; there he had opportunity to fly confiscated airplanes, such as German Fokker D.VIIs, Albitri, Pfalzes, and Fokker D.VIIIs, as well as Phönixs. In 1916, he began a stint at public relations for the Italian Air Ministry. On 29 July 1927, he was promoted to maggiore. On 10 October 1929, he was given command of 7 Gruppo.
Mecozzi developed his own theory of military aviation usage which was dubbed the "Attack air force" or "Assault aviation" doctrine. Its emphasis was on attacking military targets rather than civilians and civil industry. This put him in frequent opposition to Douhet and his theory of strategic bombing. Mecozzi nevertheless continued to be promoted, becoming a generale di Brigata on 8 April 1937. However, Mecozzi was invalided from duty and became president of the national aviation club. He also published the Editoriale Aeronautica of the Air Ministry.
After World War II, he retired at the rank of Generale. For some years after that, he edited Rivista Aeronautica, a supposedly independently magazine covertly supported by the air force. Mecozzi also campaigned for a national air museum for Italy. Mecozzi became eccentric; he wore his flying suit to the magazine's offices. Towards the end of his life, he escaped talking about his early combat experiences by becoming mute. He died on 2 November 1971 in his native Rome. |
1658 Innes
Discovery
Innes was discovered on 13 July 1953, by South African astronomer Jacobus Bruwer at Johannesburg Observatory in South Africa.
It was the first numbered discovery of astronomer Jacobus Bruwer. In addition, he also discovered the minor planets 1660 Wood, 1794 Finsen, and 3284 Niebuhr. The asteroid 1811 Bruwer was named in his honour by the Dutch, Dutch-American astronomer trio of the Palomar–Leiden survey.
Orbit and classification
It orbits the Sun in the central main-belt at a distance of 2.1–3.0 AU once every 4 years and 1 month (1,495 days). Its orbit has an eccentricity of 0.18 and an inclination of 9° with respect to the ecliptic. Innes was first identified as 1940 GB at Turku Observatory in 1940, extending the body's observation arc by 13 years prior to its official discovery observation.
Physical characteristics
In the Tholen taxonomy, Innes has an AS-spectral type, an intermediate form of the rare A-types to the common stony asteroids (also see category listing).
Rotation period
In May 2005, astronomers Robert Stephens at the Center for Solar System Studies, California, and Lorenzo Franco at Balzaretto Observatory, near Rome, each obtained a rotational lightcurve of Innes. The photometric observations gave an identical rotation period of 3.191±0.001 hours with a brightness variation of 0.22 and 0.25 magnitude, respectively (U=3/3).
Diameter and albedo
According to the 2014-revised survey result of NASA's Wide-field Infrared Survey Explorer with its subsequent NEOWISE mission, Innes measures 13.35 kilometers in diameter and its surface has an albedo of 0.248, while the Collaborative Asteroid Lightcurve Link assumes a standard albedo for stony asteroids of 0.20 and calculates a diameter of 14.76 kilometers with an absolute magnitude of 11.52.
Naming
This minor planet was named for Scottish–South African astronomer Robert T. A. Innes (1861–1933), first director of the discovering Union Observatory from 1903 to 1927 (originally named Transvaal Observatory). He was a skilled observational astronomer, famous for his deliberate search and discovery of the nearest star, Proxima Centauri, in 1915. He also made important theoretical and computational contributions to celestial mechanics and to the irregular rotation of the Earth. The astronomer is also honored by the lunar crater Innes. The official naming citation was published by the Minor Planet Center on 1 July 1972 (M.P.C. 3297). |
<filename>01_trainee/trainee_chapter_01/src/main/java/ru/job4j/loop/Factorial.java
package ru.job4j.loop;
class Factorial {
int calc(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}
}
|
<gh_stars>1-10
import setuptools
import pathlib
import pkg_resources
with pathlib.Path('turing/version.py').open() as version_py:
_locals = locals()
exec(version_py.read(), globals(), _locals)
version = _locals['VERSION']
with pathlib.Path('requirements.txt').open() as requirements_txt:
requirements = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(requirements_txt)
]
with pathlib.Path('requirements.dev.txt').open() as dev_requirements_test:
dev_requirements = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(dev_requirements_test)
]
setuptools.setup(
name='turing-sdk',
version=version,
packages=setuptools.find_packages(),
install_requires=requirements,
extras_require={
'dev': dev_requirements
},
python_requires='==3.7.*',
long_description=pathlib.Path('./docs/README.md').read_text(),
long_description_content_type='text/markdown'
)
|
Ontogeny of the pancreatic islet parenchymal cells in the rabbit--an immunohistochemical and ultrastructural study with particular regard to the earliest appearance of argyrophil insulin-immunoreactive cells. Six early developmental stages of the rabbit pancreas were selected, viz. the embryonic ages 10 days 10 hours, 10 days 18 hours, 11 days 14 hours, 13 days, 15 days, and 18 days. Both non-immunological (histologic-tinctorial features, including argyrophilia, and transmission electron microscopy) and immunohistochemical (the indirect immunofluorescence and/or the peroxidase-anti-peroxidase procedure) methods were used to follow the time-course for the appearance and differentiation of both endocrine (islet) cells and exocrine acinar epithelium. The immunological procedures were, however, limited to the 3 later developmental stages. In the first 3 developmental stages only the dorsal anlage of the pancreas could be found. It was just investigated ultrastructurally. Then, a few parenchymal cells were observed, equipped with secretory granules of endocrine type, indicating that an early differentiation of islet cells had already begun. In the later 3 developmental stages a ventral pancreas anlage was present and at least 2 types of argyrophil islet cells, equipped with secretory granules, were observed. In the pancreas anlage of 13-day-old embryos these early endocrine cells were found to be glucagon-immunoreactive. At the developmental age of 15 days argyrophil insulin-immunoreactive cells were also present, and in the 18-day-old embryos a few somatostatin cells could occasionally be discovered, too. No PP cells were found. Any exocrine acinar differentiation (with zymogen granules) was not observed until at the developmental age of 18 days. |
#pragma once
#include <map>
#include <chrono>
#include <mutex>
#include "GameObjectComponent.h"
#include "DeusCore/Logger.h"
namespace DeusServer
{
template<typename T>
class TimeLineComponent : public GameObjectComponent
{
#define WANT_DATA_BEFORE_TIMESTAMP true
#define WANT_DATA_AFTER_TIMESTAMP false
public:
TimeLineComponent(EComponentType type, Id parentObjectId);
virtual std::shared_ptr<const T> GetValue(uint32_t timeWantedMs = 0) const;
void InsertData(std::shared_ptr<const T> data);
void InsertData(std::shared_ptr<const T> data, uint32_t ms);
inline std::shared_ptr<const T> GetValueAtTime(uint32_t wantedTimeStampMS, uint32_t& timeStampOfData, bool wantDataBeforeTimestamp) const;
protected:
virtual std::shared_ptr<T> Interpolate(const T& beforeValue, uint32_t beforeValueTimestamp, const T& afterValue, uint32_t afterValueTimestamp, uint32_t currentMs) const = 0;
virtual std::shared_ptr<T> Extrapolate(const T& beforeValue, uint32_t beforeValueTimestamp, uint32_t currentMs) const = 0;
std::map<uint32_t, std::shared_ptr<const T>> m_dataWithTime;
const uint32_t MAX_DATAS_SAVED = 10000;
private:
mutable std::mutex m_componentLocker;
};
template<typename T>
inline void TimeLineComponent<T>::InsertData(std::shared_ptr<const T> data)
{
uint32_t ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
InsertData(data, ms);
}
template<typename T>
inline void TimeLineComponent<T>::InsertData(std::shared_ptr<const T> data, uint32_t ms)
{
m_componentLocker.lock(); // <---------------- LOCK
// We delete all the futur datas that arn't valid anymore
auto it = m_dataWithTime.begin();
while (it != m_dataWithTime.end()) {
if (it->first > ms)
{
it = m_dataWithTime.erase(it);
}
else
++it;
}
// insert data
m_dataWithTime.insert(std::make_pair(ms, data));
m_componentLocker.unlock(); // <---------------- UNLOCK
}
template<typename T>
inline TimeLineComponent<T>::TimeLineComponent(EComponentType type, Id parentObjectId)
: GameObjectComponent(type, parentObjectId)
{
}
template<typename T>
inline std::shared_ptr<const T> TimeLineComponent<T>::GetValue(uint32_t timeWantedMs) const
{
uint32_t currentMs = timeWantedMs == 0 ? std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() : timeWantedMs;
uint32_t timeStampBeforeDataFound = 0;
std::shared_ptr<const T> p_objectInTimeLineBefore = GetValueAtTime(currentMs, timeStampBeforeDataFound, WANT_DATA_BEFORE_TIMESTAMP);
uint32_t timeStampAfterDataFound = 0;
std::shared_ptr<const T> p_objectInTimeLineAfter = GetValueAtTime(currentMs, timeStampAfterDataFound, WANT_DATA_AFTER_TIMESTAMP);
std::shared_ptr<const T> p_value = nullptr;
if (timeStampBeforeDataFound > 0 && timeStampAfterDataFound > 0) // we are between 2 value -> interpolate
p_value = Interpolate(*p_objectInTimeLineBefore, timeStampBeforeDataFound, *p_objectInTimeLineAfter, timeStampAfterDataFound, currentMs);
else if (timeStampBeforeDataFound > 0) // we have value only before the timestamp requested but not after
p_value = Extrapolate(*p_objectInTimeLineBefore, timeStampBeforeDataFound, currentMs);
else // no data found or only after the timestamp
p_value = nullptr;
return p_value;
}
template<typename T>
inline std::shared_ptr<const T> TimeLineComponent<T>::GetValueAtTime(uint32_t wantedTimeStampMS, uint32_t & timeStampOfData, bool wantDataBeforeTimestamp) const
{
m_componentLocker.lock(); // <---------------- LOCK
if (m_dataWithTime.size() <= 0)
{
m_componentLocker.unlock(); // <---------------- UNLOCK
return nullptr;
}
if (wantDataBeforeTimestamp)
{
// start from the end
for (auto it = m_dataWithTime.rbegin(); it != m_dataWithTime.rend(); ++it)
{
if (it->first < wantedTimeStampMS)
{
timeStampOfData = it->first;
m_componentLocker.unlock(); // <---------------- UNLOCK
return it->second;
}
}
}
else {
// start from the begining
for (auto it = m_dataWithTime.begin(); it != m_dataWithTime.end(); ++it)
{
if (it->first > wantedTimeStampMS)
{
timeStampOfData = it->first;
m_componentLocker.unlock(); // <---------------- UNLOCK
return it->second;
}
}
}
m_componentLocker.unlock(); // <---------------- UNLOCK
return nullptr;
}
}
|
Genome-Based Characterization of Plant-Associated Rhodococcus qingshengii RL1 Reveals Stress Tolerance and PlantMicrobe Interaction Traits Stress tolerant, plant-associated bacteria can play an important role in maintaining a functional plant microbiome and protecting plants against various (a)biotic stresses. Members of the stress tolerant genus Rhodococcus are frequently found in the plant microbiome. Rhodococcus qingshengii RL1 was isolated from Eruca sativa and the complete genome was sequenced, annotated and analyzed using different bioinformatic tools. A special focus was laid on functional analyses of stress tolerance and interactions with plants. The genome annotation of RL1 indicated that it contains a repertoire of genes which could enable it to survive under different abiotic stress conditions for e.g., elevated mercury concentrations, to interact with plants via root colonization, to produce phytohormones and siderophores, to fix nitrogen and to interact with bacterial signaling via a LuxR-solo and quorum quenching. Based on the identified genes, functional analyses were performed in vitro with RL1 under different growth conditions. The R. qingshengii type strain djl6 and a closely related Rhodococcus erythropolis BG43 were included in the experiments to find common and distinct traits between the strains. Genome based phylogenetic analysis of 15 available and complete R. erythropolis and R. qingshengii genome sequences revealed a separation of the R. erythropolis clade in two subgroups. First one harbors only R. erythropolis strains including the R. erythropolis type strain. The second group consisted of the R. qingshengii type strain and a mix of R. qingshengii and R. erythropolis strains indicating that some strains of the second group should be considered for taxonomic re-assignment. However, BG43 was clearly identified as R. erythropolis and RL1 clearly as R. qingshengii and the strains had most tested traits in common, indicating a close functional overlap of traits between the two species. INTRODUCTION Anthropogenic activities over the past decades, including pollution with heavy metals, pesticides and chemical fertilizer, as well as improper soil exploitation coupled with climate change have led to immense global soil degradation (). This has resulted in loss of soil biodiversity, increase in pathogens and has created harsh biotic and abiotic conditions for plants and their associated microbes (;Brevik and Burgess, 2014;;;). To survive difficult environmental conditions and maintain a functional plant holobiont (stress resistant) beneficial bacteria are important. Over the last decades, several mechanisms have been identified which are involved in beneficial associations between plant and microbes. They either involve plant growth promotion based on production of plant hormones and providing enhanced nutrients to the plants or plant protection against plant pathogens by producing antimicrobial compounds (a,b) or acting indirectly by inducing host systemic resistance (Kloepper and Beauchamp, 1992;;Bahramisharif and Rose, 2019). Apart from that, beneficial bacteria have been shown to support plants as stress protecting agents under abiotic stress conditions like salt and drought stress ;Kaushal and Wani, 2016;) or by supporting plant growth in contaminated soils (;a,b). However, not only plant-microbe interactions, but also microbemicrobe interactions influence the functionality of the plant holobiont. For example, it has been shown that members of the genus Variovorax play a major role in shaping the microbiome and with this influence root growth in Arabidopsis by balancing auxin production (). This report emphasizes the importance to understand the role of all relevant members in the plant holobiont. The multifaceted interactions of plants and several plant-associated bacteria have been widely studied to understand the underlying molecular mechanisms and to exploit plant beneficial traits for sustainable agriculture (;;;). In this context it is important to further the knowledge of the functional repertoire also of yet lesser known members of the plant microbiome such as Rhodococcus to understand what enables them to interact with the plant as well as other microbes and which traits could be useful for an application in specifically demanding agricultural scenarios. The here studied closely plant associated Rhodococcus qingshengii RL1 was isolated from surface sterilized Rucola (Eruca sativa L.) leaves and the genome was recently sequenced (). The type strain of species R. qingshengii djl-6 was isolated from a carbendazim polluted soil (). Other R. qingshengii isolates have been shown to possess nitrogen fixing capacity improving growth of chick pea plants () and to produce high amounts of IAA in vitro (). In combination with the genetic traits for bioremediation, stress resistance, and biocontrol on plants widely distributed across the whole Rhodococcus genus these reports clearly warrant a characterization of our new isolate R. qingshengii RL1. We were able to assess the genomic potential of RL1 by characterizing beneficial traits in the genome () and found that RL1 is well equipped with genes essential for survival under different abiotic stress conditions and for microbial interactions with other microbes and plants. In vitro assays were used to assess if these genomic potential was actually transferred into functional traits. To our knowledge, this is the first report of a R. qingshengii, which survives under mercury stress and degrades quorum quenching signals (AHLs). Additionally, for the first time we could identify a potential gibberellin producing operon in an actinobacterial genus as well as indications for existence of alternative nitrogen fixation pathways. For establishment of the taxonomic position of RL1 we performed a whole genome based phylogenetic analysis of 15 available and complete R. erythropolis and R. qingshengii genome sequences and included the R. qingshengii type strain djl6 and a closely related R. erythropolis BG43 in the in vitro experiments. Thus, this work contributes to the elucidation of molecular mechanisms and underlying genetic determinants of plant-microbe interactions and possible functions in the plant holobiont of R. qingshengii RL1 and closely related strains. Genome Comparison The genome of Rhodococcus qingshengii RL1 () was compared to the genomes of the type strain Rhodococcus qingshengii djl6 (;;), as well as the closely related soil isolate Rhodococcus erythropolis BG43 (). The genome djl6 is based on the species R. jialingiae () which was later identified as a synonym of the type strain R. qingshengii (). For the genome comparison and the identification of orthologous and unique genes in the three different genomes the efficient database framework for comparative Genome Analyses using BLAST score Ratios -EDGAR was used. Functional Annotation of RL1 Genome The RL1 genome was annotated upon submission to NCBI with the NCBI prokaryotic Genome Annotation Pipeline (PGAP) with the annotation method best-placed reference protein set with GeneMarkS-2+ and the Rapid Annotation using Subsystem Technology 2.0 (RAST) with default parameter of the classicRAST annotation scheme plus frameshift fixing and backfilling of gaps allowed, where the annotated genome was browsed afterward in the SEED environment (;). Functional annotation by grouping genes in clusters of orthologous groups (COG) of proteins according to Tatusov et al. was performed with eggNOG v5.0 (). Genes were annotated with the KEGG (Kyoto Encyclopedia of Genes and Genomes) orthology (KO) identifiers, or the K numbers, and directly linked to the KEGG pathways with the KEGG automatic annotation server (KAAS) () and KEGG Mapper. Further functional annotation was performed by identifying plant microbe interaction factors and gene clusters for biosynthesis of secondary metabolites with Plant-bacteria Interaction Factors Resource (PIFAR) () and the antibiotics and secondary metabolite analysis shell -antiSMASH () using the default parameters. Phylogenetic Analysis Sixty-one complete genomes of the genus Rhodococcus and the genome of the out-group Streptomyces albus NBRC 13014 (type strain), were used for the full-genome approximately maximumlikelihood phylogenetic tree build in EDGAR. 15 genomes identified in the phylogenetic tree as members of the Rhodococcus erythropolis clade and two out-group genomes were used for the approximately maximum-likelihood phylogenetic tree calculated in EDGAR using FastTree Software with the Shimodaira-Hasegawa test for bootstrap values. Average nucleotide identity (ANI) and Average amino acid identity (AAI) was calculated in EDGAR as described in Konstantinidis and Tiedje and Goris et al.. Evaluation of Growth and Tolerance to Different Stress Factors If not indicated otherwise all Rhodococcus strains were precultured in liquid TSB overnight. Mercury Tolerance Overnight grown cultures were transferred to fresh TSB medium with increasing mercury levels 0.001, 0.01, 0.1, and 1 mM adjusted with mercury-II-chloride (HgCl 2, Roth, Germany) according to Dziewit et al. and incubated at 28 C. Growth rates were evaluated by spectrophotometric measurement of optical density at 600 nm (OD 600 ) after 24 and 48 h. For treatments without detectable growth (=0.1 mM and 1 mM mercury), the recovery of cells was evaluated by the ability to form colonies on TSB agar plates without mercury. Hundred microliter of cultures from the treatments with 0.1 and 1 mM mercury were plated on TSB without mercury and incubated at 28 C for 24 and 48 h. Experiment was repeated three times. Nonmercury-tolerant strains Herbaspirillum frisingense GSF30 and Bacillus velezensis FZB42 served as negative controls. Salt Stress Tolerance Overnight grown cultures were transferred to fresh TSB medium with increasing sodium chloride (NaCl, Merck, Germany) levels 0, 1, 2.5, 3.5, 5.5, 7.5, 12, and 15% according to De Carvalho et al. and incubated at 28 C. Growth rates were evaluated by spectrophotometric measurement of optical density at 600 nm (OD 600 ) after 24 and 48 h. For treatments without detectable growth (12 and 15% NaCl), the recovery of cells was evaluated by the ability to form colonies on TSB agar plates without NaCl. Hundred microliter of cultures from the treatments 12 and 15% were plated on TSB agar without NaCl and incubated at 28 C for 24 and 48 h. Experiment was repeated three times. Less salt tolerant Herbaspirillum frisingense GSF30 and Bacillus velezensis FZB42 served as negative controls. pH Tolerance Overnight grown cultures were transferred to fresh TSB medium with pH values 8, 7, 6, 5, 4, 3, 2 adjusted with hydrochloric acid (HCl, Merck, Germany) or sodium hydroxide (NaOH, Sigma, United States) and incubated at 28 C. Growth rates were evaluated by spectrophotometric measurement optical density at 600 nm (OD 600 ) after 24 and 48 h. Recovery was evaluated by the ability to form colonies on TSB agar plates at pH 7.3 after 48 h in treatments without detectable growth (pH 4, 3 and 2). Hundred microliter of medium from the treatments pH 4, 3, and 2 were plated on TSB and incubated at 28 C for 24 and 48 h. The experiment was repeated three times. Herbaspirillum frisingense GSF30 and Bacillus velezensis FZB42 which did not grow in low pH (below 5) served as negative controls. Osmotic Stress Tolerance Overnight grown cultures were transferred to fresh TSB medium with increasing osmotic stress levels 0, -0.25, -0.5, -0.75, -1, -1.25, and -1.5 MPa and incubated at 28 C. Increasing osmotic stress was adjusted with polyethylene glycol 6000 (PEG6000, Serva Electrophoresis GmbH, Heidelberg, Germany) based on decreasing water potential with the formula of Kaufmann and Michel, according to Kumar et al. and Jayakumar et al.. -1.5 MPa is the water potential plants in regular soil start to wilt irreversibly. Growth rates were evaluated by spectrophotometric measurement optical density at 600 nm (OD 600 ) after 24 and 48 h. Experiment was repeated three times. Gram-negative Herbaspirillum frisingense GSF30 and grampositive Bacillus velezensis FZB42 served as controls. Bacterial strains were streaked on a fresh TSB or NB plate from glycerol stocks and grown overnight. A single colony of RL1 was picked and streaked on nutrient broth (NB) agar plates with 100 g/ml potassium tellurite trihydrate (K 2 TeO 3 * 3H 2 O, Sigma, United States) for 48 h. Dark gray colony growth was evaluated as positive growth. The strain Rhizobium radiobacter F4 AHL-aiiA-genetically modified to tolerate a tellurite concentration of 100 g/ml served as positive control. Characterization of Traits Involved in Microbe-Plant Interactions If not indicated otherwise all Rhodococcus strains were precultured in liquid TSB overnight. Indole-Acetic Acid Production Indole-acetic acid (IAA) production was determined by the colorimetric method of Gordon and Weber. Overnight grown cultures were transferred to fresh TSB medium with and without the IAA precursor 5 mM tryptophan (1 mg/mL, Sigma) and grown for 48 h. Liquid cultures were centrifuged for 2 min at 5000 g. Hundred microliter of supernatant were mixed with 100 l of Salkowski reagent (Loper and Schroth, 1986) and 1 l of orthophosphoric acid (Sigma, United States). After incubation in the dark for 30 min amounts of IAA in the supernatant were analyzed in a plate reader (Spectra Max iD3, Molecular Devices) at 530 nm wavelength. A standard curve was prepared from commercial indole-3-acetic acid (Fluka Biochemika, Germany) in TSB with concentrations ranging from 0 to 100 g/ml and Herbaspirillum frisingense GSF30 was used as positive control. Supernatant measurements were performed in triplicates. Evaluation was based on the amount of produced IAA normalized to an OD 600 = 1. Siderophore Production Siderophore production was analyzed according to Prez-Miranda et al. and Lynne et al. with modifications. Twenty-five microliter of overnight grown cultures were spotted on TSB agar plate and grown for 48 h. Dye solutions were prepared and mixed according to Lynne et al.. Piperazin-N,N'-bis-(2-ethanesulfonic acid) (Pipes, Roth, Germany) was added to H 2 O with 0.9 % agar and pH was adjusted to 6.8. After autoclaving separately, the dye solution was slowly mixed with the Pipes-Agar mix. Cooled but still liquid overlay agar (10 ml) was poured on plates with bacteria. After 2 h siderophore production was analyzed by detection of color change from blue to orange. The experiment was repeated three times. Phosphate Solubilization Overnight grown cultures were washed twice in 1x PBS and 25 l were spotted on National Botanical Research Institute's phosphate growth medium (NBRIP) according to Nautiyal and incubated at 28 C. After 6 days, phosphate solubilization activity was determined according to the formation of a clear halo surrounding the spotted colony using the Phosphate Solubilization Index (SI): (Colony diameter + Halo zone diameter)/colony diameter). The phosphate-solubilizing Luteibacter sp. Cha2324a_16 served as positive control. The experiment was repeated three times. Nitrogen Fixation Nitrogen fixation was analyzed with nitrogen-free semisolid Nfb-medium according to Dbereiner, on Ashby's mannitol medium (Mannitol 20 g/l, K 2 HPO 4 0.2 g/l, MgSO 4 * 5H 2 O 0.2 g/l, NaCl 0.2 g/l, K 2 SO 4 0.1 g/l, CaCO 3 5 g/l, Agar 15 g/l) and on Jensen's medium (Sucrose 20 g/l, K 2 HPO 4 1 g/l, MgSO 4 * 5H 2 O 0.5 g/l, NaCl 0.5 g/l, FeSO 4 0.1 g/l, Na 2 MoO 4 0.005 g/l, CaCO 3 2 g/l, Agar 15 g/l). Overnight grown cultures were washed twice in 1x PBS and 10 l were spotted on nitrogen-free semi-solid Nfb-medium and incubated at 28 C. Pellicle formation was evaluated after 48 h. Ten microliter of washed overnight cultures were streaked on Ashby's mannitol agar. Bacterial strains were streaked on a fresh TSB or NB plate from glycerol stocks and grown overnight. A single colony of each strain was picked and streaked on Jensen's agar. Bacteria on Ashby's medium and Jensen's medium were incubated at 28 C and growth was evaluated after 3 days. The experiments were repeated three times. Nitrogen-fixing Azospirillum brasilense Sp7 served as positive control. Biofilm Formation Biofilm formation was analyzed according to O'Toole. Overnight grown cultures were washed in 1xPBS and OD 600 was adjusted to 0.1. Bacterial strains were cultivated in a microtiter plate in 100 l modified M9 minimal medium with 0.5% casamino acids (Biozol Diagnostica Vertrieb GmbH, Germany) without shaking at 28 C. After incubation OD 600 was measured in the plate reader (SpectraMax iD3, Molecular Devices). After 24 h OD 600 was measured and unattached cells were dumped out of the plate. The plate was washed twice by submerging it in MilliQ water to further remove unattached cells. Hundred and twenty-five microliter of 0.1% crystal violet (Roth, Germany) solution was added to each well. After 15 min the plate was rinsed three times in MilliQ water and dried for 1.5 h before visual inspection of biofilm production. For quantification of the biofilm 125 l of 30% acetic acid (Roth, Germany) was added to each well and incubated for 15 min at room temperature. The solution was transferred to a new microtiter plate and color intensity was quantified at the plate reader (SpectraMax iD3, Molecular Devices) with absorbance at 550 nm and 30% acetic acid as blank. Biofilm-forming Pseudomonas simiae WCS417 served as positive control and non-biofilm-producing Escherichia coli DH5 served as negative control. The experiment was repeated three times with 6-12 replicates per strain. Confrontation Assay Against Plant-Pathogenic Fungi The interaction of RL1 with the well-known plant pathogenic fungi Rhizoctonia solani, Fusarium culmorum, and Fusarium oxysporum was investigated with an in vitro confrontation assay. The following pathogenic fungi were used: Rhizoctonia solani, causing potato stem cancer and black scurf (Yang and Li, 2012), wheat pathogenic fungus Fusarium culmorum G2191 causing seedling blight, foot rot, and head blight (Wagacha and Muthomi, 2007) and the wilt-causing Fusarium oxysporum DSM62297 (). Fungi were cultivated on potato dextrose agar (PDA, Sigma, United States) (potato extract 4.0 g/L, glucose 20.0 g/L) at room temperature in the dark and stored at 4 C until further use. RL1 was pre-grown in TSB. Overnight grown culture was diluted to OD 600 = 0.1 with fresh TSB medium and 10 l were dripped on the plate. Approximately 1 mm 3 PDA pieces grown with fungi were aseptically transferred to TSB plates at a distance of approximately 3 cm. After 9 days of growth the zone of inhibition formation was visually analyzed and documented photographically. Sterile water served as negative control and Bacillus velezensis FZB42, a known fungal antagonistic strain served as positive control. Confrontation assays were performed in triplicates. Degradation of Synthetic and Bacterial N-Acyl-Homoserine Lactones (AHLs) The identified qsdA gene sequence of the RL1 genome encoding the AHL lactonase was used to construct a phylogenetic tree with nearest relatives with MEGA X. Rhodococcus strains were analyzed with a well diffusion agar-plate assay () and a V-shaped assay () with modifications. Well diffusion plate assay For the experiments with synthetic AHL Rhodococcus strains were pre-grown in TSB. Overnight grown cultures were transferred to fresh TSB liquid medium supplemented with 10 M C12-HSL (Biomol GmbH, Germany) and incubated at 28 C 180 rpm. Cell-free TSB medium supplemented with 10 M C12-HSL served as control. For the co-cultivation experiment RL1 and Acidovorax radicis N35e overnight cultures were adjusted to OD 600 = 0.2 and co-cultured in fresh liquid NB medium. Pure culture of Acidovorax radicis N35e served as control. The well diffusion plates were prepared as follows: The AHL biosensor strain Agrobacterium tumefaciens A136 was pregrown in NB. NB plates were overlaid with soft NB agar (0.5% agar) supplemented with the biosensor strain A136 and 80 g/ml 5-bromo-4-chloro-3-indolyl--D-galactopyranoside (X-gal, Life Technologies GmbH, Germany). Twenty microliter of each supernatant from the co-cultivation or synthetic AHL experiment were filled in wells prepared in the soft agar and incubated at 28 C for 30 h. Remaining AHLs were detected by color change. Pure NB was used as negative control for presence of AHLs. V-shaped plate assay The AHL biosensor strain Agrobacterium tumefaciens A136 was pre-grown in NB. Agrobacterium tumefaciens A136 and 80 g/ml 5-bromo-4-chloro-3-indolyl--D-galactopyranoside (X-gal, Life Technologies GmbH, Germany) were spread on NB plates. Rhodococcus strains were pre-grown in TSB. The AHL producing strains Acidovorax radicis N35e was pre-grown in NB, non-AHLproducing mutant strain Acidovorax radicis N35 AHL-araI::tet was pre-grown in NB with tetracyclin 20 g/ml and kanamycin 50 g/ml. Overnight grown cultures were washed in 1x PBS and optical density was adjusted to OD 600 = 0.1. Eight times 1 l of each culture was dripped in a diagonal row on the prepared NB plates in V-shape with increasingly closer inoculation sites. Plates were incubated for 30 h at 28 C. AHL degradation was detected by color change. Root Inoculation in Axenic System Rucola (Eruca sativa L.) seeds were washed in Tween 80 1% (Sigma, United States) for 2 min, surface sterilized with sodium hypochlorite 12% (NaOCl, Roth, Germany) for 8 min and washed three times in sterile deionized water for 2 min. Sterilized seeds were placed on Hoagland's solution (Sigma, United States) with 0.8% agar to germinate 4 days. Rhodococcus strains were pregrown in TSB. Overnight grown cultures were washed two times in 1x PBS (AppliChem, Germany) and diluted to a concentration of 10 7 CFUs. Seedlings were inoculated in the prepared bacterial solution of RL1, BG43, and djl6 for 1 h under shaking at 160 rpm at 28 C. Seedlings inoculated in 1x PBS served as negative control. Inoculated seedlings were transferred to an axenic system with 80 ml sterile quartz sand and 20 ml Hoagland's solution in a sterile Phytatray II (Sigma, United States). Seedlings inoculated with RL1 were additionally transferred on plates with 0.5x Murashige and Skoog Medium (0.5x MS) including vitamins (Duchefa Biochemie, Netherlands); pH was adjusted to 5.7 with 2N KOH. No additional sucrose was added to 0.5x MS. The axenic system was placed in a Phytochamber (Weiss Technik, Modell SGC120PG2, Germany) with 23 C, 55% humidity, day-night-cycle 12 h : 12 h. After seven and 14 days freshly harvested roots were washed in 1x PBS, fixed in 55% EtOH and 1x PBS mix and stored at -20 C until further use. Confocal Laser Scanning Microscopy (CLSM) FISH stained roots and bacterial cells were investigated at the Zeiss confocal laser scanning microscope LSM880 (Zeiss, Oberkochen, Germany) with argon ion laser and helium neon laser for excitation of FITC (488 nm), Cy3 (561 nm) and an unlabeled control channel (633 nm). Cells were observed with a 64x C-Apochromat water immersion objective. Micrographs were recorded using the software Zen Black Edition (Zeiss, Oberkochen, Germany). Quantitative Evaluation Rhizosphere competence of the investigated bacterial strains were estimated via counting of colony forming units (CFU). Sterilized Rucola (Eruca sativa L.) seedlings were inoculated in bacterial solution and planted in the axenic system as described above. After 7 days three roots per treatment were harvested, weighed and ground in a sterilized mortar with 1 ml 1x PBS. Ground roots were diluted three times (10 −3 ), 100 l of each dilution was plated in triplicates on TSB plates and incubated at 28 C. After 48 h CFUs of dilution 10 −3 were counted and mean values were compared between treatments. Plating of dilutions 10 −1 and 10 −2 resulted in too many CFUs for counting. Statistical Analysis Sample size was not predetermined using statistical methods. Statistical analysis was performed with RStudio 3.6.1. Data were tested for normal distribution with Shapiro-Wilk-Test and analyzed with the non-parametric Fligner-Killeen-Test or with analysis of variances (ANOVA) followed by the post-hoc analysis with Tukey's test. Significance level was 5% marked in the graphs by asterisks. Phylogenetic Analysis The full genome based phylogenetic tree of Rhodococcus was constructed on a core genome of 633 genes from 39246 genes in total (Supplementary Figure 1). Based on this phylogenetic tree 15 genomes of the R. erythropolis clade were chosen to calculate the full genome based phylogenetic tree of the R. erythropolis clade. It was built on a core genome of 1211 genes from 20587 genes in total and revealed that the clade can be separated into two groups (Figure 1). The first group includes R. erythropolis strains only. The second group harbors a mix of R. erythropolis and R. qingshengii strains. ANI values between all analyzed R. erythropolis or R. qingshengii genomes were higher than 94% (Supplementary Figure 2). The ANI value within the first group was 98.02-98.8% and within the second group 97.17-99.3%. The outgroups Rhodococcus aethiovorans and Streptomyces albus had ANI values of 72.13-72.57% and 66.79-67.9%, compared to the first group and the second group, respectively. AAI values between the first and the second group of the R. erythropolis clade were all above 98% (Supplementary Figure 3), and between both groups and the outgroups R. aethiovorans and S. albus AAI values were 56.45-57.33% and 76.71-76.81, respectively. R. qingshengii djl6 and RL1 grouped together in the second group. R. erythropolis BG43 was allocated to the first group. Comparing the RL1 genome with the genomes of R. qingshengii djl6 and R. erythropolis BG43, 5293 genes could be identified that were shared between all three strains (Figure 2). RL1 and djl6 shared more genes than each of them with BG43 (69; 70). For RL1 39 singleton genes could be identified of which 17 were annotated as hypothetical proteins (Table 1). Functional Annotation of RL1 Genome A total of 6,554 protein coding sequences were predicted from the genome of RL1 with (RAST) and 6,328 genes with PGAP ( Table 2). 5918 of the predicted genes could be annotated to an assigned function and 92.4% of them were classified into 21 clusters of orthologous groups (COG) identified with eggNOG (Figure 3). Genes involved in metabolism represented the largest fraction (37.1%), followed by information and storage processing (19.2%), and cellular processes and signaling (12.7%) (Figure 3). In more details, the highest number of genes could be assigned to be involved in transcription (K, 11.5%), followed by amino acid transport and metabolism (E, 7.5%) and energy production and conversion (C, 6.9%). 3.6% of the genes could be assigned to the category of secondary metabolites biosynthesis, transport, and catabolism (Q). 9.4% of the genes were assigned to more than one category (>1 cat.). 21.4% of the genes could not be assigned to a known function (S). 35% of the coding sequences in the RL1 genome were sorted in 23 main RAST subsystems and 424 subsystems (subsystem coverage). With KEGG pathway analysis genes involved in 273 pathways were identified (Supplementary Table 1). The genome was further analyzed for presence of genes known to be involved in interactions with plants using the webbased tool PIFAR and 45 genes representing 14 categories could be identified (Supplementary Table 2). Using the tool antiSMASH 17 biosynthetic gene clusters (BGC) with the potential to produce secondary metabolites, such as ectoine, erythrochelin, and heterobactin A/heterobactin S2, could be identified (Supplementary Table 3). In this study we focused on the cluster with highest similarity (>50%) to known secondary metabolite biosynthesis pathways. The genome annotation of RL1 revealed several genes which have been previously identified to be involved in stress tolerance under different abiotic stress conditions, bioremediation of toxic compounds, rhizosphere colonization and (beneficial) plant-microbe interactions and were partly verified by manual annotation with blastp alignment (Supplementary Table 4). In more details, the RL1 genome harbors many genes, which can be expressed to withstand osmotic, salt, oxidative and acidic stress and are relevant for heavy metal tolerance (mercury, lead, cadmium, arsenic) and bioremediation of aromatic hydrocarbons (alkB, catA) and fossil fuels (dszB). Moreover, genes potentially involved in multiple drug resistance, DNA repair by phosphorothioation, antibiotic resistance and degradation of CO and hydrogen could be identified, for example the complete carbon monoxide dehydrogenase (CODH) and a -hydrogenase cluster. The RL1 genome annotation indicated that it is equipped with several genes which could enable it to interact with the plant and survive in the plant environment via plant hormone and siderophore production of the siderophores enterobactin, bacillibactin, arthrobactin, and heterobactin as well FIGURE 3 | Functional classification of genes encoding proteins in RL1 based on cluster of orthologous groups (COG) (). All alphabets represent different COG functional classes: A, RNA processing and modification; B, Chromatin structure and dynamics; C, energy production and conversion; D, cell cycle control, cell division, and chromosome partitioning; E, amino acid transport and metabolism; F, nucleotide transport and metabolism; G, carbohydrate transport and metabolism; H, coenzyme transport and metabolism; I, lipid transport and metabolism; J, translation, ribosomal structure, and biogenesis; K, transcription; L, replication, recombination, and repair; M, cell wall, cell membrane, and cell envelope biogenesis; N, cell motility; O, posttranslational modification, protein turnover, and chaperones; P, inorganic ion transport and metabolism; Q, secondary metabolites biosynthesis, transport, and catabolism; S, no functional prediction; T, signal transduction mechanisms; U, intracellular trafficking, secretion, and vesicular transport; and V, defense mechanisms; >1 cat, classified in more than 1 category. as nitrogen fixation, iron acquisition, phosphate solubilization, biofilm formation, and stress protection. Additionally, the RL1 genome harbors genes involved in quorum quenching, glucosinolate metabolism, aldoxime, isothiocyanate (ITC) and nitrile degradation, as well as genes important for the production of volatiles, exopolysaccharides (EPS), proteases and microbe-associated molecular patterns (MAMP). Therefore, we analyzed functional traits with focus on stress tolerance and plant-microbe interactions. Mercury Tolerance The RL1 genome harbors genes for alkylmercury lyase and merR family DNA-binding protein (Supplementary Table 4). Active growth determined by optical density was detectable in the medium with 0.001 mM mercury for djl6 and BG43. RL1 was able to grow in the medium with up to 0.01 mM mercury. RL1 and BG43 could recover from up to 1 mM mercury in the medium, whereas djl6 recovered from up to 0.1 mM mercury. The gram-positive control strain Bacillus velezensis FZB42 could grow in the medium with up to 0.01 mM mercury and the gramnegative control strain Herbaspirillum frisingense GSF30 only in medium with 0.001 mM mercury. Both control strains did not recover from medium containing 0.1 mM mercury. Salt Stress Tolerance The RL1 genome harbors genes for the complete Na+/H+ antiporter operon (Supplementary Table 4). RL1 and BG43 were able to grow in medium with 7.5% NaCl, whereas djl6 could grow up to 5.5% NaCl in the medium. Although there was no visible growth, all tested Rhodococcus strains were able to recover from salt stress of 15% NaCl in the medium. The grampositive control strain Bacillus velezensis FZB42 could grow up to 7.5% NaCl in the medium and did not recover from medium with 15% NaCl. The gram-negative control strain Herbaspirillum frisingense GSF30 could grow in medium with up to 3.5% NaCl and could not recover from 7.5% NaCl in the medium. pH Tolerance Genes encoding for squalene cyclase and the ADI cluster were identified in the RL1 genome (Supplementary Table 4). The Rhodococcus strains were able to grow up to pH 5 and recovered after 48 h in pH 3 and 4 h in pH 2. Control strains Herbaspirillum frisingense GSF30 and Bacillus velezensis FZB42 were able to grow up to pH 5 and recovered from pH 4. Osmotic Stress Tolerance The gene cluster for ectoine biosynthesis was identified in RL1 with 75% identity to the ectoine biosynthetic cluster of Streptomyces anulatus. The Rhodococcus strains RL1, djl6, BG43, and the control strains FZB42 and GSF30 were able to grow under PEG 6000 induced osmotic stress of -1.5 MPa, which was the tested maximum. Antibiotic Resistance Genes involved in antibiotic resistance and tellurite resistance were identified in the RL1 genome (Supplementary Table 4). RL1 was tolerant to Kanamycin up to the concentration of 96 g/ml, Ampicillin up to 6 g/ml, Rifampicin up to 0.025 g/ml, but not tolerant to Vancomycin. Djl6 was tolerant to Kanamycin up to 12 g/mL, Ampicillin up to 3 g/mL, Rifampicin up to 0.047 g/ml and Vancomycin up to 0.023 g/ml. BG43 was tolerant to Kanamycin up to 48 g/ml, Ampicillin up to 2 g/ml, Rifampicin up to 0.023 g/ml and Vancomycin up to 0.5 g/ml. RL1 was able to grow on NB plates containing 100 g/ml potassium tellurite trihydrate. The other strains were not tested for this trait. Traits Involved in Microbe-Plant Interactions Indole-Acetic Acid Production The genes encoding for amidase amiE and amine oxidase iaaM as well as genes involved in tryptophan metabolism were identified in the RL1 genome (Supplementary Table 4). RL1 produced 16 ± 2.6 g/ml of IAA which is the highest amount compared to djl6 and BG43 with 10.7 ± 2.4 g/ml and 10.9 ± 3.8 g/ml, respectively. The positive control strain Herbaspirillum frisingense GSF30 produced 41 ± 9.8 g/ml IAA. Phosphate Solubilization The RL1 genome harbors genes involved in organic acid production (Supplementary 1-Aminocyclopropane-1-Carboxylate Utilization Growth on M9 and M9 with ACC and no growth on nitrogenfree M9 indicate ACC utilization. RL1, BG43, and djl6 could grow on plates with ACC, on regular M9 medium and on nitrogen-free medium. The positive control Variovorax sp. M92526_27 grew on M9 and M9 with ACC, but not on M9 without nitrogen ( Figure 5A). ACC deaminase activity remained unclear, because Rhodococcus strains could also grow on M9 without nitrogen. The gene acdS was not present in the RL1 genome. Biofilm Formation Genes encoding for a phosphoglucomutase and a signal peptidase I were identified in the RL1 genome (Supplementary Table 4). The strains RL1, djl6 and BG43 were able to produce biofilms in varying intensities (Figure 6), but stronger than the negative control Escherichia coli DH5. Djl6 showed the strongest biofilm formation. Positive Depicted as arrows are the core biosynthetic genes in dark red, additional biosynthetic genes in light red, transport-related genes in blue and additional genes in gray. The biosynthetic genes (dark and light red) are presented in order of their appearance from right to left encoding for isochorismate synthase, isochorismatase, 2,3-dihydro-2,3-dihydroxybenzoate dehydrogenase, 2,3-dihydroxybenzoate-AMP ligase, isochorismatase, and an amino acid adenylation domain-containing protein. Numbers indicate percentage of similarity to PR4. (B) In vitro assay for siderophore production of RL1, BG43, djl6 and Bacillus sp. detected with Chrome Azurol Blue overlay agar. Siderophore production is indicated by color change of the medium from blue to orange. control Pseudomonas simiae WCS417 normalized biofilm formation was lower compared to djl6, but stronger compared to RL1 and BG43. FIGURE 6 | Ability to produce Biofilms with averaged results from 3 experiments normalized to OD600 = 1. Significant difference is indicated by asterisks representing * P < 0.05. Confrontation Assay Against Plant-Pathogenic Fungi RL1 inhibited the plant-pathogenic fungus Fusarium oxysporum in vitro. The positive biocontrol strain FZB42 inhibited the plant-pathogenic fungi Rhizoctonia solani, Fusarium oxysporum, and Fusarium culmorum indicated by inhibition zones (Supplementary Figure 4). Degradation of Synthetic and Bacterial N-Acyl-Homoserinelactones (AHLs) A qsdA gene (QEM30276) could be identified in the RL1 genome, which belongs to a class of large-spectrum quorum-quenching lactonases also present in other Rhodococcus sp. (Figure 7A). Therefore, AHL degradation ability was tested in RL1, djl6 and BG43 using the sensor strain A136. In this set-up it could be clearly shown that RL1, djl6 and BG43 were able to degrade synthetic C12-HSL (Figures 7B-D). Additionally, co-culturing of Acidovorax radicis N35e with RL1 resulted in no visible blue color formation by the sensor strain, indicating degradation of produced AHL ( Figure 7B). Finally, V-shaped spotting of Acidovorax radicis N35e and RL1, djl6 and BG43 showed an inhibition of blue color formation where strains were in direct contact (Figures 7E-H). Root Colonization in Axenic System Root colonization was analyzed with fluorescence in situ hybridization using probes EUB Mix Fluos and HGC69A Atto550 or HGC69A Cy3. Single cells of RL1 could be found on the root surface of its host plant Rucola (Eruca sativa L.) when grown in the axenic system (Figures 8A-C), while dense cell patches were identified on roots from MS agar plates ( Figure 8D). Similar colonization patterns were found for strains djl6 and BG43. All strains were localized rather in the basal mature part of the root in areas of emergence of root hairs. No endophytic colonization was observed. Evolutionary analyses were conducted in MEGA X. (B-D) Well-diffusion plate assays on NB plates all supplemented with the sensor strain A136 and X-Gal. Except for the cultures containing AHL producing strain A. radicis N35e, C12-HSL was added during cultivation of all bacteria. Supernatants of these cultures were added to the wells and blue color formation by the sensor strain indicated remaining AHL in the tested supernatant. NB with C12-HSL (+) served as positive control, and NB without C12-HSL (-) as negative control. (E-H) V-shaped assays on NB after 30 h supplemented with the sensor strain A136 and X-Gal. AHL negative mutant A. radicis N35e AHL-served as control. Presence of AHLs is detected by the sensor strain Agrobacterium tumefaciens A136 indicated by blue color change of X-Gal. Quantitative estimation based on CFU/mg root mass ( Figure 8E) showed significantly higher colonization numbers for RL1 and djl6 (p-value = 0.012) than BG43. Djl6 showed a trend toward higher root colonization compared to RL1. All strains were significantly higher than the uninoculated control. DISCUSSION The genus Rhodococcus is frequently found in the plant microbiome (Francis and Vereecke, 2019;). Therefore, it is important to analyze and understand functions of the plant-associated members of this genus, such as RL1 isolated from Eruca sativa leaves. Additionally, as mentioned in the introduction, the genus Rhodococcus is well-known for stress tolerant strains (). For these reasons, we wanted to elucidate genomic properties with a special focus on functional analyses of stress tolerance and interaction with plants to understand the possible functions that the plant-associated R. qingshengii RL1 could provide within the plant holobiont and also compare it to the closely related strains djl6 and BG43. RL1 Genome Harbors Several Genes Involved in Survival and Tolerance to Different Stress Conditions Genes involved in acidic pH tolerance were identified in RL1, either involved in the production of the compound squalene, (D) RL1 on 2 weeks old Eruca sativa roots grown on MS agar without additional sucrose. (E) Quantification of root colonization 1 week after inoculation. Arrows indicate bacterial cells identified by yellow color from overlaying channels of probes EUB (green) and HGC (red). Root autofluorescence is assigned in green and red. Scale bar represents 10 m. Significant difference is indicated by asterisks representing * P < 0.05 and * * * P < 0.001. such as squalene cyclase, a precursor of hopanoid () or based on the expression of the ADI cluster (in the presence of arginine). The latter is a mechanism to overcome acidic stress often found in gram-positive bacteria (Cotter and Hill, 2003). The experimental evidence proved the ability of Rhodococcus strain RL1 to survive and recover from acidic pH conditions. This trait was also shared by the closely related strains djl6 and BG43, indicating that this trait may be widespread amongst the genus Rhodococcus. In the genus Rhodococcus tolerance to acidic pH was reported for R. qingshengii BBG1 () and for the mammalian pathogen Rhodococcus equi, which can withstand a pH of 4 (). Conventional agricultural practices and soil exploitation can lead to increased soil acidity (). Therefore, acidic pH tolerance is an important trait of plant-associated and soil bacteria to maintain a functional plant microbiome also under acidic soil conditions. Ectoine is a compound associated with osmoregulation in bacteria (Bremer and Krmer, 2019) and important for survival during osmotic stress. The gene cluster for ectoine biosynthesis and transporters were identified in RL1, indicating the ability of RL1 to synthesize ectoine under osmotic stress. Alternative to biosynthesis, bacteria can take up compatible solutes, such as proline or betaine from their environment (Bremer and Krmer, 2019). Genes encoding the respective transporters were found in the RL1 genome. Additionally, the full operon of Na+/H+ antiporter was identified in the RL1 genome, which could play a role in salt stress tolerance (;). Results of the in vitro experiments of the tested Rhodococcus strains growing under high salt and osmotic stress confirmed previous reports of osmotic and salt stress tolerant members of the genus Rhodococcus. For example, an upregulation of genes involved in ectoine biosynthesis was observed in Rhodococcus jostii RHA1 under desiccation () and rapid adaptation to salt stress was described for R. erythropolis DSM 1069 (De ). Moreover, plant associated bacteria tolerant to osmotic and salt stress could also be beneficial for the plant via support of ion homeostasis (;) and upregulation of osmoprotective compound biosynthesis in the plant. For example, Bacillus sp. can directly influence proline biosynthesis in plants to improve osmotolerance (Kaushal and Wani, 2016;). Heavy metals, such as mercury, are highly persistent environmental pollutants and a threat to all living organisms (Boyd and Barkay, 2012). Organomercury compounds were used in several agricultural applications, for example as common pest control agent in the 1900's. Although its use has been banned in several countries, it is still used in Australia to treat the plant pathogenic fungus Ceratocystis paradoxa. Mercury resistant bacteria can convert organomercury compounds or Hg(II) to gaseous Hg to reduce the mercury concentration in their environment (Boyd and Barkay, 2012). Mercury resistance was described in R. erythropolis BD2 and Pseudomonas fluorescens SBW25 to be located and transferred on a plasmid (;) containing the mer-operon (Boyd and Barkay, 2012). Loss of this plasmid caused a loss of mercury resistance (;). However, in RL1 the identified mercury resistance genes, such as a transcriptional regulator MerR and a unique alkylmercury lyase involved in the degradation of toxic organomercury compounds (e.g., MeHg) (), are located in the chromosome. We report for the first time that mercury tolerance is also present in an isolate of R. qingshengii based on the results of the in vitro experiment. BG43 and RL1 were both able to survive up to 1 mM of mercury in the growth medium. Survival and detoxification of heavy metals have been reported for other members of the genus Rhodococcus (;), emphasizing the exceptional stress tolerance of this genus. Heavy metal resistance in bacteria in combination with a close association with plants could indicate the adaptation to toxic heavy metal residues of such compounds previously used as pesticides. Apart from tolerance to heavy metals, we could identify several operons in the genome of RL1 which show that this bacterium has the ability to survive under selective environmental conditions by metabolizing trace gasses like CO and H 2. Comparison of deduced amino acid sequences revealed that the identified CODH belongs to the functional type1-CODH enzymes, which catalyze the unidirectional conversion of CO to CO 2 (King and Weber, 2007). This type of enzyme has been extensively studied in aerobic CO-oxidizers, or carboxydotrophic Actinobacteria (). Sequence similarity revealed that the identified -hydrogenase cluster belongs to the high-affinity group 1 h/5 Actinobacteria type of hydrogenases which have been shown to scavenge electrons from tropospheric H 2 to sustain aerobic respiration during starvation (;). Interestingly, less is known about plant associated atmospheric H 2 -oxidizing bacteria. Atmospheric H 2 may serve as the maintenance energy during starvation and sporulation of high-affinity H 2 -oxidizing Actinobacteria, providing them the advantage of survival in plant tissues, as was shown for endophytic Streptomyces spp. (;). The simultaneous presence of the carbon monoxide dehydrogenase (CODH) genes and the hydrogenase cluster indicate that RL1 can use CO and H 2 as energy source. The functional annotation of RL1 genome also revealed that it harbors genes involved in multidrug resistance, tellurite resistance and antibiotic resistance. Tellurite is a metalloid often used as antibiotic compound in in vitro experiments and is toxic to eukaryotic and prokaryotic cells (Chien and Han, 2009). Resistance against tellurite can be mediated by a reduction of tellurite (TeO 3 2− ) to elemental tellurium, indicated by the color change of the colonies, which was also observed in RL1. Moreover, the RL1 genome harbors genes potentially involved in protection against oxidative stress. These genes could be involved in detoxification of tellurite, because the toxicity of tellurite is eventually caused through intracellular generation of reactive oxygen species (ROS). In vitro tests with antibiotics revealed resistance of RL1 against kanamycin and ampicillin, whereas djl6 and BG43 are more resistant to rifampicin and vancomycin respectively. Antibiotic resistance was mainly investigated and is widespread in the horse pathogen Rhodococcus equi (), because of its relevance in livestock animal infections. Antibiotic resistance in plant-associated Rhodococcus species was not intensively studied yet and could confer them a competitive advantage in surviving against other antibiotic-producing microbes in specialized niches like the rhizosphere (;). RL1 Genome Reveals Successful Interaction and Survival Strategies in Association With Plants The genome annotation of RL1 and functional analysis revealed a large repertoire of traits involved in plant-microbe and microbemicrobe interactions, which can be relevant for the role of RL1 in the plant microbiome. An important trait of plant-associated bacteria is the ability to colonize plant roots to facilitate, e.g., the exchange of metabolites (Kloepper and Beauchamp, 1992;). For successful root colonization it can be beneficial for the bacteria to be able to produce biofilms (), which was demonstrated for RL1, djl6, and BG43. Accordingly, the RL1 genome harbors genes encoding for enzymes involved in biofilm formation. Qualitative evaluation of rhizosphere competence revealed that all three strains were able to colonize the roots of E. sativa epiphytically. However, quantitative evaluation revealed that RL1 and djl6 had significantly more CFUs per mg E. sativa root than BG43, which indicates a better root colonization ability of R. qingshengii species. Verification of endo-or epiphytic leaf colonization of RL1 analyzed with FISH (data not shown) did not deliver clear results due to high auto-fluorescence of the leaves and transformation of fluorescent markers in RL1 was not successful. Therefore, final conclusions upon leaf colonization of RL1 cannot be drawn. The leaves of Brassicacea, such as Rucola (Eruca sativa L.) contain glucosinolates (GSLs), which are sulfur-containing secondary metabolites involved in the protection of plants against herbivores (Textor and Gershenzon, 2009;). Since RL1 was isolated from the leaves of Rucola (Eruca sativa L.), we were interested if the genome reveals some interesting information about its ability to metabolize glucosinolates. Our results showed that the genome harbors genes potentially involved in the metabolic pathways of GSLs, such as myrosinase, methionine sulfoxide reductase (msrA, msrB) or aldoxime dehydratase oxd (Supplementary Table 4). Degradation of GSLs was investigated for gut microbes regarding beneficial effects of ITC production as a chemoprotective function against cancer (a,b;Bessler and Djaldetti, 2018;). An in vitro experiment with Rucola (Eruca sativa L.) leaf extract and pure GSLs (data not shown) did not reveal clear and consistent results on GSL synthesis, bioconversion or degradation by RL1, djl6, and BG43. The RL1 genome harbors genes related to the production of volatiles, exopolysaccharides and proteases, which are important in microbial communication, plant colonization and microbial detection by the host (;). The chemotaxis protein CheY relevant for the transmission of sensory signals from the chemoreceptors to the flagella motors, which is additionally a microbe-associated molecular pattern (MAMP) () was identified in the RL1 genome. As Rhodococcus is a non-motile genus CheY has a rather different function, e.g., in sensory signal transduction in another pathway or interaction with the plant. Additionally, in the RL1 genome genes encoding for a LacI transcription regulator and an aldo-keto reductase were identified, which were found to be enriched in genomes of plant beneficial microbes (). Plant associated bacteria in general can influence root growth, germination, flowering and developmental stages via balancing or producing plant hormones, such as gibberellin (;;) or indole-3-acetic acid (IAA) (). In the in vitro assay RL1 produced a higher amount of IAA in comparison to the strains djl6 and BG43. The best-known pathway for IAA production includes the enzyme indolepyruvate decarboxylase (ipdC), which is not present in the RL1 genome. Instead genes of the alternative indole-3-acetamide pathway for IAA production () were identified in the RL1 genome. The ability to produce IAA in vitro was not only shown for RL1 but also in another R. qingshengii strain () and other members of the genus Rhodococcus (Francis and Vereecke, 2019). Bacterial production of IAA can be beneficial for the plant by increasing the root system (Spaepen and Vanderleyden, 2011) and balancing IAA production is an important function of the root microbiome (). Gibberellin production is encoded by a conserved operon, which was characterized in and -proteobacteria (). Essential parts of the gibberellin operon were identified in the RL1 genome. To our knowledge, this is the first report about the presence of genes of the gibberellin operon in any Actinobacteria. Some plantpathogenic bacteria produce bioactive GA4, which can have a detrimental effect on seedling development. Beneficial bacteria only produce the precursor GA9 as they lack the cytochrome P450 (CYP115) for the final step in the production of the bioactive GA4 (Nagel and Peters, 2017). As RL1 also lacks the cytochrome P450 (CYP115) this indicates its allocation to the plant beneficial bacteria. Verification of the production of gibberellin by RL1 with gas chromatography was beyond the scope of this work. The bacterially produced polyamine spermidine increases biofilm formation and overall bacterial fitness (;). Additionally, it is the plant growth-promoting compound in strains such as B. subtilis OKB105 or Klebsiella sp. D5A (;) and the upregulation of spermidine export proteins in Stenotrophomonas rhizophila DSM14405 upon salt stress in combination with exposure to root exudates emphasizes the role of spermidine as key substance in stress protection in roots. Presence of genes encoding for the enzymes involved in the biosynthesis of spermidine, such as arginine decarboxylase, agmatinase, spermidine synthase in the RL1 genome indicate the ability of RL1 to function as stress-protecting agent and support plants under abiotic stress. The degradation of 1-amino-cyclopropane-1-carboxylate (ACC), the precursor of the plant hormone ethylene, by bacterial ACC deaminase can protect the plant from detrimental effects of long exposure to ethylene (Glick, 2012;). In a standard in vitro assay RL1, djl6, and BG43 were able to grow on nitrogen-free M9 plates with ACC in the medium, indicating ACC deaminase activity ( Figure 5A). However, the essential gene acdS encoding for ACC deaminase is missing in the RL1 genome. Additionally, all three tested Rhodococcus strains were able to grow on all tested nitrogen free media. The results indicate that the isolates grow on N-free media through utilization of atmospheric nitrogen rather than using ACC as a nitrogen source. Biological nitrogen fixation is defined as the bacterial conversion of dinitrogen to ammonia through the expression of canonical nif gene products (Dos ;). In the RL1 genome the SUF system FeS assembly protein of the nifU family was identified (MSMEG_2718, Supplementary Table 4), which stabilizes the nitrogenase complex and is relevant for diazotrophy especially under low temperature conditions (). The nifH gene was previously identified in a diazotrophic R. qingshengii strain (;) and used as molecular marker to directly link to a diazotrophic lifestyle. However, no nifH gene was identified in the RL1 genome. In a large scale genome analysis Higdon et al. identified three distinct groups of diazotrophic bacteria defined by nif gene content and structural variation. The genus Rhodococcus was classified as DS-negative (=no Dos Santos model nif gene homolog present in genome). This implies the presence of alternative nif genes and metabolic pathways relevant for nitrogen fixation in Rhodococcus genomes beyond the currently known models. Transcriptome analysis and mutant construction would reveal insights to alternative nitrogen fixation mechanisms in RL1 as representative of the genus Rhodococcus. Siderophores not only chelate iron and have beneficial effects in plant growth, they are also involved in bioremediation, function as biosensors and are relevant in microbial competition and defense against other microbes, which can lead to a beneficial biocontrol effect for the plant (Ahmed and Holmstrm, 2014;;Pollak and Cordero, 2020). Genes involved in iron acquisition and siderophore production were identified in the RL1 genome, for example for the siderophore heterobactin, which is unique to the Rhodococcus genus (;;). The in vitro assay for siderophore production was positive for RL1, corroborating that the identified genes were actually expressed. These results were in contrast to djl6 and BG43, where the functional analysis was negative. Iron acquisition and ferrous iron transport can occur via two systems, the FeoABC and EfeUOB transporters (). The EfeUOB was reported to be low-pH-induced () and was predicted in the genome of a Leptospirillum sp. tolerant to acidic pH (). RL1 harbors the genes encoding for the EfeUOB operon, which could contribute to the low pH tolerance of RL1, because it allows iron acquisition also under low pH. The RL1 genome harbors genes relevant for organic acid production, which are involved in phosphate solubilization and genes potentially relevant for phosphate metabolism and transport. However, genes involved in gluconic acid production, which is the main driver in phosphate solubilization could not be identified (). Despite of that, the in vitro assay for this trait was positive for RL1 which suggests the presence of alternative organic acids involved in phosphate solubilization. Phosphate solubilization capacity was previously reported for Rhodococcus globerulus isolated from Plectranthus amboinicus (). RL1 Genome Reveals Competitive Potential Against Other Microorganisms Members of the genus Rhodococcus have been reported to show antifungal activity in vitro against plant-pathogenic fungi (;;) and RL1 reduced growth of F. oxysporum in vitro, but showed no inhibition against R. solani and F. culmorum (Supplementary Figure 4). Further studies using model plants will reveal the full potential of RL1 as biocontrol agent against plant pathogenic fungi. Degradation or interference with quorum sensing molecules can disturb bacterial communication and is called quorum quenching (). The qsdA gene, encoding for a N-acyl-HSL lactonase was first described by Uroz et al. for the strain R. erythropolis W2 and could also be identified in the RL1 genome ( Figure 7A). Moreover, the RL1 genome harbors a two-component transcriptional AHL responsive regulator from the LuxR family. However, as RL1 is not producing AHLs this regulator is likely a so-called LuxR-solo, which allows bacteria to respond to quorum sensing signals from neighboring cells without itself contributing to signal synthesis. This was also previously described for the genus Rhodococcus and other gram-positive bacteria (Subramoni and Venturi, 2009;). In vitro experiments showed the ability of RL1 to degrade AHLs. To our knowledge, this is the first report of an AHL-degrading R. qingshengii. Also it is the first description of functional AHL degradation by BG43, which was previously reported only to interfere with the quinolone signal of Pseudomonas aeruginosa. Quorum quenching ability was intensively studied in R. erythropolis R138 (;;;), which was able to reduce the soft-rot pathogen Pectobacterium in potatoes and most likely use the degraded AHLs as carbon source. Quorum quenching can also be a beneficial trait in other crop-pathogen systems as reported for example in Pseudomonas segetis () or Bacillus thuringensis (). Further analysis of RL1 quorum quenching abilities, e.g., against plant pathogens such as Pectobacterium or Pseudomonas syringae, would reveal its full potential as plant biocontrol agent. Genome Comparison of Related R. erythropolis and R. qingshengii Isolates Show Potential for Re-classification of Clade Members Rhodococcus is a genus well-known for its high potential to produce versatile secondary metabolites and the RL1 genome annotation confirms previous studies (;). The number of genes from the genome of RL1, which were assigned to the COG group for secondary metabolites, were higher compared to other bacteria, for example Stenotrophomonas or Enterobacter (;). Additionally, 17 BGC for secondary metabolites were identified in RL1. The average number of BGCs in the R. erythropolis clade are 13-24 BGCs and are mostly shared by R. erythropolis and R. qingshengii strains (). Four BGC cluster were highly conserved among the R. erythropolis clade and three of them were also identified in RL1 (Supplementary Table 3). The remaining unknown BGCs in the RL1 genome are potentially capable of producing novel compounds which could be analyzed in future studies. Rhodococcus is a heterogeneous genus with eight identified phylogenetic clades. Phylogenetic analysis based on complete genome sequences of the R. erythropolis clade reveals a clear separation into two subgroups at an ANI value of 97% (Figure 1 and Supplementary Figure 2). The first one includes sequences belonging to only R. erythopolis, the second includes R. qingshengii and R. erythropolis strains. Based on the clear separation we can confirm previous recommendations to separate the R. erythropolis clade into the two groups consisting of the species R. qingshengii and R. erythropolis respectively (;;). We also suggest that the R. erythropolis strains assigned to the R. qingshengii group should be re-named as previously recommended (;). The genomes of RL1 and djl6 were clearly identified as belonging to the R. qingshengii cluster (;) and had more genes in common with each other than with BG43 (Figure 2), whereas the BG43 genome was classified as R. erythropolis ). Despite the clear separation the strains RL1 and BG43 had many functional traits in common, indicating a close functional overlap between the species. At the same time, djl6 and RL1 showed different results in the in vitro experiment for siderophore production and mercury tolerance, indicating differences on the genetic and functional level also within the species R. qingshengii (Figure 4). RL1 showed overall the best performance in the tested traits. This emphasizes the importance of RL1 and the necessity to analyze the genetic and functional potential of individual strains to understand the role also of lesser known members of the plant microbiome. CONCLUSION AND OUTLOOK The study shows the remarkable genomic potential of the isolate R. qingshengii RL1 for tolerating various abiotic stresses, plantmicrobe and microbe-microbe interactions, many of which could be confirmed by functional analysis in vitro. By this thorough characterization we aim to contribute to a better understanding of relevant attributes for interactions in the plant holobiont as well as provide selection criteria for using strains, such as RL1, in specific agricultural or biotechnological applications. Furthermore, we provided phylogenetic evidence based on whole genome comparisons to justify a taxonomic separation of the R. erythropolis and R. qingshengii cluster and re-name some members of the R. erythropolis cluster. However, the functional analysis also indicates many shared traits between the two species R. qingshengii and R. erythropolis, some of them also described for the first time for the strains djl6 and BG43, but also different traits within the same species. Further experiments involving inoculation of different plants with RL1 under various conditions, which were beyond the scope of this study, would reveal insights into its plant beneficial functions. This could be coupled with transcriptome analysis of RL1 to reveal such intriguing aspects as an alternative nitrogen fixation pathway. Further investigation of the quorum quenching ability against various plant-pathogenic bacteria could advance the understanding of the role of RL1 in biological control. AUTHOR CONTRIBUTIONS TK, SC, and MR contributed to conception and design of the study. TK performed the experiments and wrote the first draft of the manuscript. JU contributed parts of the experimental data. SC and TK analyzed the data. SC and MR wrote sections of the manuscript. All authors contributed to manuscript revision, read, and approved the submitted version. |
AB1169-HPRThe Relationship between Pain and Health-Related Quality of Life in Patients with Juvenile-Onset Systemic Lupus Erythematosus Background Juvenile-onset systemic lupus erythematosus (JSLE) is an autoimmune disorder with multisystem involvement, leading to inflammatory damage to the joints, kidney, central nervous system, and hematopoietic system affecting children and adolescents. According to these multisystem deteriorations lead reduction in health-related quality of life (HRQL) in patients with JSLE. Objectives The aim of this study was to assess the relationship between HRQL and pain in patients with JSLE. Methods 19 patients (female=16, male=3) with JSLE and their parents were enrolled in the study. The subjects were recruited in a pediatric rheumatology clinic. They were diagnosed with JSLE by a pediatric rheumatologist based on the clinical diagnostic criteria. Patients with recent diagnoses of JSLE and those with mental deficits were excluded. Visual Analog Scale (VAS) was used to evaluate pain (during rest, activity and exercise) and well being. Functional ability was evaluated with Childhood Health Assessment Questionaire (CHAQ). Also, the Turkish version of PedsQL 3.0 Arthritis Module was used to evaluate HRQL. Results The mean age was 14.16±2.66 years (range 1218 years). The mean disease duration was 3.42±2.76 years (range 0.0815 years). The mean of number of affected joint was 2.16±2.92. Significant relationships were found between score of VAS-pain (during activity) and number of affected joint (r=0.801 p=0,000) and score of PedsQL-patient's report (r=-0.655 p=0,002) and score of PedsQL-parent's report (r=-0.670 p=0,002) and score of VAS-well being (r=0.759 p=0,000). Conclusions This study demonstrated that there is significant relationship between increased pain and reduction health-related quality of life in patients with JSLE. Due to number of affected joint increasing pain may results impairment daily functions and reduction health-related quality of life in patients with JSLE. Therefore, we concluded that reduction of pain has substantial role on improving of health-related quality of life in treatment of patients with JSLE. Disclosure of Interest None declared DOI 10.1136/annrheumdis-2014-eular.6056 |
The antimicrobial susceptibility of Pseudomonas pseudomallei. Emergence of resistance in vitro and during treatment. We have measured the in-vitro activity of 27 antimicrobials against 211 clinical and ten reference strains of Pseudomonas pseudomallei. Imipenem was the most active antibiotic tested, followed by piperacillin, doxycycline, amoxycillin/clavulanic acid, cefixime, cefetamet, azlocillin and ceftazidime, all of which had MICs of less than or equal to 2 mg/l for the majority of strains. The measured MICs were dependent on the media and inocula used, to an extent which varied with the antibiotic class under test; MICs of ureidopenicillins were particularly inoculum-dependent. The beta-lactams and ciprofloxacin were bactericidal, whereas the agents conventionally used to treat melioidosis (doxycycline, chloramphenicol, sulphamethoxazole and trimethoprim) had bacteriostatic activity only. Strains highly resistant to chloramphenicol (MIC greater than or equal to 256 mg/l) emerged during treatment in 7.1% of patients. These strains were fully virulent, and frequently showed cross-resistance to tetracyclines, sulphamethoxazole, trimethoprim and ciprofloxacin, with paradoxical increased susceptibility to beta-lactams and aminoglycosides. Similar resistance patterns were seen in mutants generated in vitro and two reference strains. One strain with isolated ceftazidime resistance, reversible by clavulanic acid, emerged during treatment. Several of the new beta-lactam antibiotics are of potential value in the therapy of P. pseudomallei infections. Patients should be carefully monitored for the emergence of antibiotic-resistant strains during treatment of melioidosis. |
"In the course of their dignified campaign for justice, Doreen and Neville Lawrence have changed many lives, and altered the terms of how we think about racism in our country. Institutions and individuals, including of course the Metropolitan police, had to re-examine how they work.
"At the heart of this is the case of a young man killed because he was black. Our thoughts today should be first and foremost with Stephen’s family." |
/*D************************************************************
* Modul: GRAPHIC gupdcurs.c
*
* Update the cursor, the temporary objects,
* the region name and coordinates when motion
*
*
* Copyright: yafra.org, Basel, Switzerland
**************************************************************
*/
/*R
RCS Information:
$Header: /yafra/cvsroot/mapo/source/gui/gupdcurs.c,v 1.2 2008-11-02 19:55:43 mwn Exp $
Log Information:
$Log: gupdcurs.c,v $
Revision 1.2 2008-11-02 19:55:43 mwn
re branded code - tested with oracle instant client 11.1 under ubuntu linux - add deploy to main makefile
Revision 1.1.1.1 2002-10-26 21:10:43 mwn
inital release
Revision 3.1 1997/04/02 06:50:03 mw
NT 4.0 release und WWW Teil
Revision 2.1 1994/03/28 11:03:10 ja
general version
* Revision 1.3 94/02/18 10:38:35 10:38:35 ja (<NAME>)
* Name conversion for DOS
*
* Revision 1.2 93/08/21 00:26:16 00:26:16 ja (<NAME>)
* update
*
*
*/
#include <uinclude.h>
#include <ginclude.h>
static char rcsid[]="$Header: /yafra/cvsroot/mapo/source/gui/gupdcurs.c,v 1.2 2008-11-02 19:55:43 mwn Exp $";
/**************************************************************************/
/* Up update_cursor erstellt */
/* 1. zeichnet ein Fadenkreuz an der zuletzt registrierten Stelle */
/* 2. zeichnet das Fadenkreuz an der Stelle, an der ein Pointer Motion */
/* Event im Grafik Window empfangen wurde, */
/* 3. schreibt diese Koordinaten in mm umgerechnet ins Koordinatenwidget. */
/* Da der Graphicalcursor als Zeichenfunktion das exklusive Oder GXxor */
/* verwendet, wird immer abwechselnd mit Hinter- und Vordergrundfarbe */
/* gezeichnet, das zuletzt gezeichnete Kreuz also geloescht. */
/* */
/* Nach Expose Events kann es vorkommen, dass ein EnterNotify Event */
/* geschickt wird, und kurz darauf ein PointerMotion Event. Wenn das */
/* PointerMotion Event frueher ankommt, bleibt ein Fadenkreuz stehen. */
/* Es muss hier also ueberprueft werden, ob ein EnterNotify Event in der */
/* Queue ist. */
/* */
/* Eingabeparameter : w = rufendes Widget, Grafik3 */
/* coord = ID des CoordinatenLabelWidgets */
/* event = bei EnterNotify uebergebene Event Struktur*/
/* */
/* Erstellt : Sept. 1991 WSp */
/**************************************************************************/
XtCallbackProc xGRupdate_cursor(
Widget w,
XtPointer Input,
XtPointer Output
)
{
extern GRAWIDGETS grawidgets;
extern GRAWINDOWS grawindows;
extern GRAGLOB graglob;
extern Display *display;
extern XPoint punkt[];
extern Boolean undraw;
extern REGOBJ *regObj;
static GRAFOBJ tempObj;
static int xi[2];
static XArc xa;
static XRectangle xr;
static XPoint xp[2];
static Boolean temp = False;
static Boolean zooming = False; /*no cursor while zooming */
static Boolean firstenter=True;
XArc arcus;
WCVALUE r;
XEvent *event = (XEvent *)Output;
Arg args[1];
REGOBJ *region;
int x, y;
XmString label;
char buf[XGRCOORDLEN+1];
int nr;
Boolean ok;
long aktnummer;
char strleer3[XGRREGIONLEN+1] = "*";
if (event->type == EnterNotify) { /*--------- EnterNotify */
if (firstenter) {
firstenter=False;
} else {
return;
}
} else { /*--------- PointerMotion */
firstenter=True;
if (undraw) {
if ((graglob.mode == XGRINPGRAFIC) && (!zooming))
xGRdraw_cursor();
if (graglob.showPickbox)
xGRdraw_pickbox();
if (temp)
xGRdraw_object(&tempObj);
}
}
if (event->type == LeaveNotify) {
return;
}
/*--- defaults --------*/
zooming = False;
temp = False;
undraw = True;
x = event->xmotion.x;
y = event->xmotion.y;
graglob.cursor_data.x = x;
graglob.cursor_data.y = y;
if (graglob.eingabe > 0) {
switch (graglob.aktbox) {
case BUTTONZOOM:
if (graglob.akttog == BUTTONZOOM_ZOOM && graglob.eingabe == 2) {
tempObj.was = TEMP_RECTANGLE;
tempObj.xpoints = (int *)&xr;
punkt[1].x = x;
punkt[1].y = y;
ok = xGRcheck_rectangle();
if (ok) {
xGRobjkoord_rectangle(&xr); /*get rect params*/
temp = True;
zooming = True;
}
}
break;
case BUTTONCREATE:
switch (graglob.akttog) {
case BUTTONCREATE_TEXT:
if (graglob.eingabe == 2) {
tempObj.was = TEMP_TEXT;
tempObj.xpoints = xi;
xi[0] = x;
xi[1] = y;
tempObj.text = graglob.antwort;
tempObj.gc3=(unsigned char)strlen(graglob.antwort);
temp = True;
}
break;
case BUTTONCREATE_POINT:
break;
case BUTTONCREATE_ARC:
case BUTTONCREATE_FILLEDARC:
/*if (graglob.eingabe == 3) {
tempObj.was = TEMP_CIRCLE;
punkt[2].x = x;
punkt[2].y = y;
ok = xGRget_arc(punkt, &arcus);
if (ok) {
tempObj.xpoints = (int *)&xa;
xa.x = arcus.x - arcus.r;
xa.y = arcus.y - arcus.r;
xa.width = 2. * arcus.r;
xa.height = 2. * arcus.r;
xa.angle1 = 64. * arcus.a1;
xa.angle2 = 64. * arcus.a2;
temp = True;
} else {
temp = False;
}
}*/
break;
case BUTTONCREATE_LINE:
if (graglob.eingabe == 2) {
tempObj.was = TEMP_LINE;
tempObj.xpoints = (int *)punkt;
punkt[1].x = x;
punkt[1].y = y;
temp = True;
}
break;
case BUTTONCREATE_CIRCLE:
case BUTTONCREATE_FILLEDCIRCLE:
if (graglob.eingabe == 2) {
tempObj.was = TEMP_RECTANGLE;
tempObj.xpoints = (int *)&xr;
punkt[1].x = x;
punkt[1].y = y;
if (fabs((double)(punkt[0].y - punkt[1].y)) < EPS &&
fabs((double)(punkt[0].x - punkt[1].x)) < EPS) {
temp = False;
} else {
r = (WCVALUE)hypot((double)(punkt[0].y - punkt[1].y),
(double)(punkt[0].x - punkt[1].x));
tempObj.xpoints = (int *)&xr;
xr.x = punkt[0].x - r;
xr.y = punkt[0].y - r;
xr.width = 2 * r;
xr.height = 2 * r;
/*xa.angle1 = 0.;
xa.angle2= 64. * 360.;*/
temp = True;
}
}
break;
case BUTTONCREATE_RECTANGLE:
case BUTTONCREATE_ELLIPSE:
case BUTTONCREATE_FILLEDRECTANGLE:
case BUTTONCREATE_FILLEDELLIPSE:
if (graglob.eingabe == 2) {
tempObj.was = TEMP_RECTANGLE;
tempObj.xpoints = (int *)&xr;
punkt[1].x = x;
punkt[1].y = y;
ok = xGRcheck_rectangle();
if (ok) {
xGRobjkoord_rectangle(&xr);
temp = True;
}
}
break;
}
break;
case BUTTONEDIT:
switch (graglob.akttog) {
case BUTTONEDIT_MOVE:
case BUTTONEDIT_COPY:
if (graglob.eingabe == 2) {
tempObj.was = TEMP_LINE;
tempObj.xpoints = (int *)punkt;
punkt[1].x = x;
punkt[1].y = y;
temp = True;
}
break;
case BUTTONEDIT_DELETE:
break;
}
break;
case BUTTONSELECT:
nr = graglob.eingabe-2;
if (nr < 0) {
tempObj.was = TEMP_TEXT;
tempObj.xpoints = xi;
xi[0] = x;
xi[1] = y;
tempObj.text = graglob.antwort;
tempObj.gc3=(unsigned char)strlen(graglob.antwort);
temp = True;
} else if (nr > 0) {
tempObj.was = TEMP_LINE;
tempObj.xpoints = (int *)xp;
xp[0].x = punkt[0].x;
xp[0].y = punkt[0].y;
xp[1].x = x;
xp[1].y = y;
temp = True;
}
break;
}
}
/*--- Draw what ---------------------------------------------------*/
if ((graglob.mode == XGRINPGRAFIC) && (!zooming))
xGRdraw_cursor();
if (graglob.showPickbox)
xGRdraw_pickbox();
if (temp)
xGRdraw_object(&tempObj);
/*--- aktuelle Pointerregion bestimmen -----------------------------*/
aktnummer = xGRfind_region_koord(x, y);
if(aktnummer != NOVATER) {
region = ®Obj[aktnummer];
/*--- Pointer war beim letzten up_curs Aufruf in anderer Region */
if (region != graglob.aktregion) {
graglob.aktregion = region;
label = xGRregion_name( region, 0); /* XGRREGIONLEN */
XtSetArg(args[0], XmNlabelString, label);
XtSetValues(grawidgets.aktregion, args, 1);
XmStringFree(label);
}
} else {
/*--- clear Region val --------*/
/* xGRstringpos( strleer3, XGRREGIONLEN, XGRLEFT); */
label = XmStringCreateSimple(strleer3);
XtSetArg(args[0], XmNlabelString, label);
XtSetValues(grawidgets.aktregion, args, 1);
XmStringFree(label);
graglob.aktregion = 0;
}
/*--- Koordinatenlabel setzen ------------------------------------*/
if (graglob.mode == XGRINPGRAFIC) {
sprintf(buf, "%6.1fmm / %6.1fmm",
(WCVALUE)x/graglob.xfak, (WCVALUE)y/graglob.yfak);
xGRstringpos( buf, XGRCOORDLEN, XGRRIGHT);
label = XmStringCreateSimple(buf);
XtSetArg(args[0], XmNlabelString, label);
XtSetValues(grawidgets.koord, args, 1);
XmStringFree(label);
}
}
|
Two students in Delhi have developed a web tool that can help people with dyslexia and visual impairments access the internet. This is how it works.
Delhi-based teenagers Anand Chowdhary and Nishant Gadihoke have been freelancing as web designers for a few years now. They design and develop websites for clients, individually and as a team. Recently, however, Anand was struck by a new and innovative thought that changed the way he looked at website design.
“All these years I was just making good websites – they were functional and pretty. But I was ignoring a certain section of the population – those living with disabilities and senior citizens who often find it difficult to read. However, it is not practical to add accessibility features on every website individually. So I came up with the idea of developing a Chrome extension that would help everyone access content on the web,” says the 18-year-old.
He shared the idea with his friend Nishant and they decided to develop the extension during the Delhi AngelHack Hackathon, 2016. AngelHack is an organization that conducts hackathons for coders and developers to innovate tech products for diverse categories.
The duo decided to learn more about web accessibility features for people with dyslexia and learning disabilities, discussed suitable colours and fonts, and finally came up with Oswald in June this year. The Chrome extension helps people with dyslexia and visual impairment, as well as senior citizens. Currently, the tool is an add-on for only those web browsers that support extensions from the Chrome Web Store – such as Chrome, Opera, Chromium, etc.
You May Also Like: ‘Get a Didi, Not a Maid’ – How an App Is Helping Mumbaikars Hire Domestic Help Easily & Fairly
This free and open-source extension changes the entire look of pages across the web, based on the readers’ preferences.
“Every new Oswald user has the option to choose his/her disability or preference to customise the experience. Imagine a student with dyslexia using a tool to access content on Wikipedia, or gaining access to any required piece of information on the internet. This is what Oswald facilitates,” says Anand.
People who can use the app include:
Users with dyslexia:
Anand and Nishant went through the research carried out by the British Dyslexia Association and the World Wide Web Consortium (W3C) to understand how the mind of a person with dyslexia works. These studies provide specific information on the kinds of fonts and patterns that make it easy for people with learning disabilities to read. According to the research, black text on a bright yellow background in a dyslexic-friendly font called Open Dyslexic is useful. Once a person selects dyslexia as the preference, the font and format for all the websites he/she opens in that web browser change. Oswald corrects the typography, contrast ratios, and other visual elements on the web pages to make reading easier. Users can also customize the quality of text based on their personal preferences.
You May Also Like: Don’t Let the Shopkeeper Give You Toffees Instead of Change – Donate It for a Cause with This App
Users with visual impairments:
On selecting visual impairment, Oswald goes into the reading mode. Users just have to press a keyboard shortcut, which is usually easily accessible like the spacebar, and they can hear the entire content on the web page. For people with partial blindness or hypermetropia, everything that is not important disappears from the website. The extension uses an algorithm to find relevant content and everything else – like ads, the navigation bar, etc. – are removed. Oswald reads out the content in a language of the user’s choice.
Senior Citizens: Senior citizens usually have eyesight problems. The extension provides a paragraph during the initial selection. Users have the option to drag and change the font size of the paragraph according to what is comfortable for their eyes. Once they’ve done this, Oswald adjusts the font, font size, letter spacing, line height, etc., for all websites.
For everyone else:
Regular users of the internet can also use Oswald to customize their experience. They can change the font size, reading mode, colour, etc.
Nishant is a student of Class 11 and Anand recently gave his Class 12 board exams. They are in the same school and similar interests brought them together to work on this project. “We are now taking steps to encourage all our previous clients to include accessibility features on their websites. We also plan to go to hospitals that cater to dyslexic people and install Oswald as their go-to-solution on all computers,” says Anand, adding that the duo never wants to convert Oswald into a business. They want the extension to be free so that everyone around the world can use it. They are also working on an Oswald mobile app.
“My grandfather is over 70 years old. He is not even used to computers. But if he can start using computers for easy reading instead of browsing through newspapers, it will be so much better. I don’t want anyone to have to pay for using Oswald,” concludes Anand.
Oswald received an award at the AngelHack competition under the Code4Impact category where participants had to design a technology that can lead to social change. You can download the extension here.
You can download Oswald here.
You May Also Like: Waste to Valuable: Discarded Mobile Phones Are Getting Recycled & Making Money for These 2 Friends
Like this story? Or have something to share? Write to us: [email protected], or connect with us on Facebook and Twitter (@thebetterindia). |
// NewGetSelectedTipCmd returns a new instance which can be used to issue a
// getSelectedTip JSON-RPC command.
func NewGetSelectedTipCmd(verbose, verboseTx *bool) *GetSelectedTipCmd {
return &GetSelectedTipCmd{
Verbose: verbose,
VerboseTx: verboseTx,
}
} |
Book Review: Sex Radicals and the Quest for Womens Equality ethnic writers but with women writers in Italy, so suggesting the possibility of a transnational approach to the study of Italian American women writers. This recommendation for future avenues of investigation closes Giuntas study, which, in the space of a little above 140 pages, has emphasized the need to establish a literary tradition through the work of recovery and literary analysis, analyzed the causes of past critical silence and repositioned Italian American women writers within the multicultural heritage of the USA, identified the common denominators of this literature, and rejoined it to its transatlantic place of origin. Needless to say, this is a lot to do in a relatively short book. But while this study inevitably lacks depth at times, it is useful precisely because of its comprehensiveness. Writing with an Accent is a must-read not only for specialists in Italian American literature, but for a more general audience as well. |
#from urllib.request import urlretrieve
#url='http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv'
#urlretrieve(url,'winequality-white.csv')
#now with red wine
# Import package
#from urllib.request import urlretrieve
# Import pandas
#import pandas as pd
# Assign url of file: url
#url='https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'
# Save file locally
#urlretrieve(url,'winequality-red.csv')
# Read file into a DataFrame and print its head
#df = pd.read_csv('winequality-red.csv', sep=';')
#print(df.head())
# Import packages
#import matplotlib.pyplot as plt
#import pandas as pd
# Assign url of file: url
#url='https://s3.amazonaws.com/assets.datacamp.com/production/course_1606/datasets/winequality-red.csv'
# Read file into a DataFrame: df
#df=pd.read_csv(url,sep=';')
# Print the head of the DataFrame
#print(df.head())
# Plot first column of df
#pd.DataFrame.hist(df.ix[:, 0:1])
#plt.xlabel('fixed acidity (g(tartaric acid)/dm$^3$)')
#plt.ylabel('count')
#plt.show()
# Import package
#import pandas as pd
# Assign url of file: url
#url='http://s3.amazonaws.com/assets.datacamp.com/course/importing_data_into_r/latitude.xls'
# Read in all sheets of Excel file: xl
#xl=pd.read_excel(url,sheetname=None)
# Print the sheetnames to the shell
#print(xl.keys())
# Print the head of the first sheet (using its name, NOT its index)
#print(xl['1700'].head())
#retrieve data from web pages
#from urllib.request import urlopen,Request
#url='https://www.wikipedia.org'
#request=Request(url)
#response=urlopen(request)
#html=response.read()
#print(urlopen(Request(url='https://www.wikipedia.org')).read())
#urlopen(Request(url='https://www.wikipedia.org')).close()
# Import packages
#from urllib.request import urlopen,Request
# Specify the url
#url = "http://www.datacamp.com/teach/documentation"
# This packages the request: request
#request=Request(url)
# Sends the request and catches the response: response
#response=urlopen(request)
# Print the datatype of response
#print(type(response))
# Be polite and close the response!
#response.close()
# Import packages
#from urllib.request import urlopen, Request
# Specify the url
#url = "http://www.datacamp.com/teach/documentation"
# This packages the request
#request = Request(url)
# Sends the request and catches the response: response
#response=urlopen(request)
# Extract the response: html
#html=response.read()
# Print the html
#print(html)
# Be polite and close the response!
#response.close()
#requests package as the most popular python package
#import requests
#url='https://www.wikipedia.org'
#r=requests.get(url)
#text=r.text
#print(text)
# Import package
#import requests
# Specify the url: url
#url='http://www.datacamp.com/teach/documentation'
# Packages the request, send the request and catch the response: r
#r=requests.get(url)
# Extract the response: text
#text=r.text
# Print the html
#print(text)
#BEAUTIFUL SOUP
#from bs4 import BeautifulSoup
#import requests
#url='https://www.crummy.com/software/BeautifulSoup'
#r=requests.get(url)
#html_doc=r.text
#soup=BeautifulSoup(html_doc)
#soup.prettify()
#getting url resources as text
#print(soup.title)
#print(soup.get_text())
#for link in soup.find_all('a'):
# print(link.get('href'))
# Import packages
#import requests
#from bs4 import BeautifulSoup
# Specify url: url
#url='https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
#r=requests.get(url)
# Extracts the response as html: html_doc
#html_doc=r.text
# Create a BeautifulSoup object from the HTML: soup
#soup=BeautifulSoup(html_doc)
# Prettify the BeautifulSoup object: pretty_soup
#pretty_soup=soup.prettify()
# Print the response
#print(pretty_soup)
#GETTING TITLE AND TEXT FROM A WEBSITE
# Import packages
#import requests
#from bs4 import BeautifulSoup
# Specify url: url
#url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
#r = requests.get(url)
# Extract the response as html: html_doc
#html_doc = r.text
# Create a BeautifulSoup object from the HTML: soup
#soup=BeautifulSoup(html_doc)
# Get the title of Guido's webpage: guido_title
#guido_title=soup.title
# Print the title of Guido's webpage to the shell
#print(guido_title)
# Get Guido's text: guido_text
#guido_text=soup.get_text()
# Print Guido's text to the shell
#print(guido_text)
#GETTING HTTP LINKS FROM A WEBSITE
# Import packages
#import requests
#from bs4 import BeautifulSoup
# Specify url
#url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
#r = requests.get(url)
# Extracts the response as html: html_doc
#html_doc = r.text
# create a BeautifulSoup object from the HTML: soup
#soup = BeautifulSoup(html_doc)
# Print the title of Guido's webpage
#print(soup.title)
# Find all 'a' tags (which define hyperlinks): a_tags
#a_tags=soup.find_all('a')
# Print the URLs to the shell
#for link in a_tags:
# print(link.get('href'))
#APIS AND JSON
#import json
#with open('snakes.json','r') as json_file:
# json_data=json.load(json_file)
#the data will be loaded as a dictionary
#for key,value in json_data.items():
# print(key+':',value)
#iterate ke-value pairs by key
# Load JSON: json_data
#with open("a_movie.json") as json_file:
# json_data = json.load(json_file)
# Print each key-value pair in json_data
#for k in json_data.keys():
# print(k + ': ', json_data[k])
#Print values for specific keys
#with open("a_movie.json") as json_file:
# json_data = json.load(json_file)
#print(json_data['Title'])
#print(json_data['Title'])
#CONNECTING TO IMDB API
#import requests
#url='http://www.omdbapi.com/?t=hackers'
#r=requests.get(url)
#now time to decode the json data
#json_data=r.json()
#for key,value in json_data.items():
# print(key+':',value)
#PRINT OUT A TEXT RESPONSE
# Import requests package
#import requests
# Assign URL to variable: url
#url='http://www.omdbapi.com/?apikey=ff21610b&t=social+network'
# Package the request, send the request and catch the response: r
#r = requests.get(url)
# Print the text of the response
#print(r.text)
#PRINT OUT ALL ITEMS OF THE MOVIE INFO
# Import package
#import requests
# Assign URL to variable: url
#url = 'http://www.omdbapi.com/?apikey=ff21610b&t=social+network'
# Package the request, send the request and catch the response: r
#r = requests.get(url)
# Decode the JSON data into a dictionary: json_data
#json_data=r.json()
# Print each key-value pair in json_data
#for k in json_data.keys():
# print(k + ': ', json_data[k])
#CALLING THE WIKIPEDIA API
# Import package
#import requests
# Assign URL to variable: url
#url = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=pizza'
# Package the request, send the request and catch the response: r
#r = requests.get(url)
# Decode the JSON data into a dictionary: json_data
#json_data=r.json()
# Print the Wikipedia page extract
#pizza_extract = json_data['query']['pages']['24768']['extract']
#print(pizza_extract)
#TWITTER API
#import tweepy,json
#access_token= "<KEY>"
#access_token_secret="<KEY>"
#consumer_key="jMiZ6yAleXUHfrjsgSqeKI5PD"
#consumer_secret="<KEY>"
#auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
#auth.set_access_token(access_token,access_token_secret)
#class MyStreamListener(tweepy.StreamListener):
# def __init__(self, api=None):
# super(MyStreamListener, self).__init__()
# self.num_tweets = 0
# self.file = open("tweets.txt", "w")
# def on_status(self, status):
# tweet = status._json
# self.file.write( json.dumps(tweet) + '\n' )
# self.num_tweets += 1
# if self.num_tweets < 100:
# return True
# else:
# return False
# self.file.close()
# def on_error(self, status):
# print(status)
#l=MyStreamListener()
#stream=tweepy.Stream(auth,l)
#stream.filter(track=['apples','oranges'])
# Import package
#import tweepy
# Store OAuth authentication credentials in relevant variables
#access_token = "<KEY>"
#access_token_secret = "<KEY>"
#consumer_key = "nZ6EA0FxZ293SxGNg8g8aP0HM"
#consumer_secret = "<KEY>"
# Pass OAuth details to tweepy's OAuth handler
#auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
#auth.set_access_token(access_token,access_token_secret)
# Import package
import json
# String of path to file: tweets_data_path
tweets_data_path = 'tweets.txt'
# Initialize empty list to store tweets: tweets_data
tweets_data = []
# Open connection to file
tweets_file = open(tweets_data_path, "r")
# Read in tweets and store in list: tweets_data
for line in tweets_file:
tweet = json.loads(line)
tweets_data.append(tweet)
# Close connection to file
tweets_file.close()
# Import package
import pandas as pd
# Build DataFrame of tweet texts and languages
df = pd.DataFrame(tweets_data, columns=['text', 'lang'])
# Print head of DataFrame
print(df.head())
#create a class that counts words
import re
def word_in_text(word, tweet):
word = word.lower()
text = tweet.lower()
match = re.search(word, tweet)
if match:
return True
return False
# Initialize list to store tweet counts
[clinton, trump, sanders, cruz] = [0, 0, 0, 0]
# Iterate through df, counting the number of tweets in which
# each candidate is mentioned
for index, row in df.iterrows():
clinton += word_in_text('clinton', row['text'])
trump += word_in_text('trump', row['text'])
sanders += word_in_text('sanders', row['text'])
cruz += word_in_text('cruz', row['text'])
# Import packages
import matplotlib.pyplot as plt
import seaborn as sns
# Set seaborn style
sns.set(color_codes=True)
# Create a list of labels:cd
cd = ['clinton', 'trump', 'sanders', 'cruz']
# Plot histogram
ax = sns.barplot(cd, [clinton,trump,sanders,cruz])
ax.set(ylabel="count")
plt.show()
|
The global distribution of physicians and nurses. AIM To explore the global distribution of physicians and nurses and the influence of gross national product per capita on this distribution, using available United Nations' (UN) sources. OBJECTIVES to compare the international distribution of physicians and nurses by country; to examine the influence of gross national product per capita (GNP) on the global distribution of physicians and nurses; to explore the assumptions underlying the recommendations of The World Development Report 1993 Investing in Health for health workforce substitution; and to consider the implications for future studies of global health labour distribution. DESIGN A database was compiled from various UN sources on 147 countries. Using some of the variables from this database, a general linear regression model for log GNP per capita on each of the two dependent variables (log nurses and log physicians per 1000 population) was produced. Standardized residuals obtained from these bivariate regressions were calculated and plotted against each other to determine the relationship between the global distribution of physicians to population and that of nurses. From this analysis outlying countries could also be identified. RESULTS Ratios of physicians to population by country varied from 0. 02 to 4.4 per 1000 population (or from 1 to 227 and 1-50,000 population), and nurses from 0.03 to 16.4 (or from 1 to 61 and 1-33, 000 population). There was a positive correlation (r = 0.84, P < 0. 001) between the number of physicians per 1000 population and the number of nurses per 1000 population. GNP explained 49% of the variation in physicians and 40% in nurses. Ranking of countries according to their standardized deviation from mean regression lines for GNP against health personnel in countries with both the lowest incomes and lowest numbers of health personnel, resulted in little change from the original rankings of ratios of physicians and nurses relative to population. For some of the wealthiest countries, there was a marked fall in global ranking and for some middle income countries a marked improvement in ranking. CONCLUSION 70% of the distribution of nurses globally can be explained by the distribution of physicians, and the influence of GNP per capita on the global distribution of physicians and nurses appears to be substantial. In only a minority of the world's very poorest countries is there evidence to suggest that higher numbers of nurses substitute for low numbers of physicians. Standardization of the distributions by GNP demonstrates that many countries (but not the poorest) regress to within one standard deviation of the mean expected distribution. This suggests that countries could set optimum levels of physicians and nurses within the limits of their GNP. More realistically, the findings suggest that recommendations for modification of the structure of countries' health labour forces as a component of health care reform may be more difficult to achieve than at first appears. The potential unreliability of the data sources used, and the implications for the accuracy of the findings, are discussed. |
import {Component, EventEmitter, Input, Output} from "@angular/core";
import { Project} from "../../../models/project";
import {ProjectService} from "../../_services/projects.service";
@Component({
selector: 'project-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditProjectComponent{
constructor (private projectService: ProjectService) {}
@Input() project:Project;
@Output() editProject = new EventEmitter<String>();
onSubmit(event) {
let project = JSON.parse(JSON.stringify(this.project));
this.project.name = event.target.value;
this.projectService.editProject(this.project)
.subscribe(res => {
this.editProject.emit(res.project.name);
},error =>{ this.project = JSON.parse(JSON.stringify(project));}
);
event.target.blur();
}
}
|
The Active Surveillance for Low-Risk Prostate Cancer: Case Series of Single Center dard of care for most patients diagnosed with lowrisk prostate cancer (PCa).1 I read with great interest the article by Akarken et al. discussing their initial results with AS for low risc PCa patients.2 In their retrospective study, the data of 36 patients who were included in the AS program in a single center, with the median follow-up period of 18.4 months, have been evaluated. After reading the article, I propose some considerations for which clarification would be helpful. Although the inclusion criteria were stated as lowrisk PCa patients, there were no patients in the study with involvement of more than 3 cores. There is only 1 patient with involvement of 3 biopsy cores. Under this circumstances, these results of the study mostly reflect the results of very low risk patient group. Although patients with low risk PCa were specified as the inclusion criterion in the study, the absence of patients with more than 3 biopsy core involvements in the study suggests that there may be a bias in inclusion of very low risk patients in the study. |
<gh_stars>0
import * as CFRichTextTypes from '@contentful/rich-text-types';
import * as Contentful from 'contentful';
import { TypePageFields } from './TypePage';
export interface TypeComponent_heroFields {
name: Contentful.EntryFields.Symbol;
title: Contentful.EntryFields.Symbol;
text?: CFRichTextTypes.Block | CFRichTextTypes.Inline;
image: Contentful.Asset;
ctaText: Contentful.EntryFields.Symbol;
ctaLink?: Contentful.Entry<TypePageFields>;
slider?: Contentful.Entry<any>;
posts?: Contentful.Entry<any>[];
}
export type TypeComponent_hero = Contentful.Entry<TypeComponent_heroFields>;
|
/*
** EPITECH PROJECT, 2021
** my_put_nbr.c
** File description:
** a function that displays the number given as a parameter.
*/
int my_put_nbr(int nb);
static int my_put_nbr_in_long(long nb);
int my_putchar(char c);
static int handling_negatives(int nb);
static int handling_negatives(int nb)
{
if (nb == 0) {
my_putchar('0');
}
my_putchar('-');
my_put_nbr_in_long(-nb);
return (0);
}
static int my_put_nbr_in_long(long nb)
{
long result = nb;
long multiplier = 1;
if (nb <= 0) {
handling_negatives(nb);
}
while (result > 10) {
result = nb / 10;
multiplier = multiplier * 10;
}
nb = nb - result * multiplier;
if (result != 0 || multiplier != 1) {
my_putchar(result + '0');
}
if (result == 0) {
return (0);
} else {
my_put_nbr(nb % 10);
}
return (0);
}
int my_put_nbr(int nb)
{
my_put_nbr_in_long(nb);
return (0);
}
|
Lower autolytic activity in a homogeneous methicillin-resistant Staphylococcus aureus strain compared to derived heterogeneous-resistant and susceptible strains. It has been proposed that in addition to production of a penicillin-binding protein with low affinity for beta-lactam antibiotics, control of autolysin activity is involved in the mechanism of staphylococcal methicillin resistance. A homogeneous methicillin-resistant Staphylococcus aureus strain (DU4916) had lower rates of unstimulated, NaCl- and Triton X-100-stimulated autolysis, and daptomycin (LY146032)-induced lysis than a heterogeneous methicillin-resistant strain (DU4916-K7) and a methicillin-susceptible strain (DU4916S) derived from DU4916. |
AN EXPLORATORY STUDY OF THE EFFECTS OF BUOYANCY ON TURBULENT NONPREMIXED ETHYLENE JET FLAMES IN CROSSFLOW A new study has been initiated to examine the effect of buoyancy on the structure of turbulent non-premixed jet flames in crossflow (JFICF). In the work presented here, ethylene JFICF were investigated under normal and lowgravity conditions, where the low-gravity was achieved by using the 1.25-second droptower facility at UT-Austin. Eight cases were studied, at momentum flux ratios of 6, 8.5 and 10, and at jet exit Reynolds numbers ranging from 3000 to 4930. The principal diagnostic employed was time-resolved imaging of the visible soot luminosity. An analysis of JFICF trajectories based on mean soot luminosity images, suggests both normal and low gravity JFICF exhibit a power law scaling, but all of the normal gravity cases deviate from such a scaling at some point downstream. This deviation from power law scaling is likely a result of buoyancy effects. Three-dimensional volume rendering of sequential images is used to study the characteristics of large-scale structures in the flame and the influence of these structures on flame tip oscillation. Low-gravity JFICF were observed to have a more regular and coherent far-field than their normal-gravity counterparts. Strong coupling between the large-scale structures and the flame tip oscillations is observed. |
<reponame>sebi5361/micropython
"""
Process raw qstr file and output qstr data with length, hash and data bytes.
This script works with Python 2.6, 2.7, 3.3 and 3.4.
"""
from __future__ import print_function
import re
import sys
# Python 2/3 compatibility:
# - iterating through bytes is different
# - codepoint2name lives in a different module
import platform
if platform.python_version_tuple()[0] == '2':
bytes_cons = lambda val, enc=None: bytearray(val)
from htmlentitydefs import codepoint2name
elif platform.python_version_tuple()[0] == '3':
bytes_cons = bytes
from html.entities import codepoint2name
# end compatibility code
codepoint2name[ord('-')] = 'hyphen';
# add some custom names to map characters that aren't in HTML
codepoint2name[ord(' ')] = 'space'
codepoint2name[ord('\'')] = 'squot'
codepoint2name[ord(',')] = 'comma'
codepoint2name[ord('.')] = 'dot'
codepoint2name[ord(':')] = 'colon'
codepoint2name[ord(';')] = 'semicolon'
codepoint2name[ord('/')] = 'slash'
codepoint2name[ord('%')] = 'percent'
codepoint2name[ord('#')] = 'hash'
codepoint2name[ord('(')] = 'paren_open'
codepoint2name[ord(')')] = 'paren_close'
codepoint2name[ord('[')] = 'bracket_open'
codepoint2name[ord(']')] = 'bracket_close'
codepoint2name[ord('{')] = 'brace_open'
codepoint2name[ord('}')] = 'brace_close'
codepoint2name[ord('*')] = 'star'
codepoint2name[ord('!')] = 'bang'
codepoint2name[ord('\\')] = 'backslash'
codepoint2name[ord('+')] = 'plus'
codepoint2name[ord('$')] = 'dollar'
codepoint2name[ord('=')] = 'equals'
codepoint2name[ord('?')] = 'question'
codepoint2name[ord('@')] = 'at_sign'
codepoint2name[ord('^')] = 'caret'
codepoint2name[ord('|')] = 'pipe'
codepoint2name[ord('~')] = 'tilde'
# static qstrs, should be sorted
static_qstr_list = [
"",
"__dir__", # Put __dir__ after empty qstr for builtin dir() to work
"\n",
" ",
"*",
"/",
"<module>",
"_",
"__call__",
"__class__",
"__delitem__",
"__enter__",
"__exit__",
"__getattr__",
"__getitem__",
"__hash__",
"__init__",
"__int__",
"__iter__",
"__len__",
"__main__",
"__module__",
"__name__",
"__new__",
"__next__",
"__qualname__",
"__repr__",
"__setitem__",
"__str__",
"ArithmeticError",
"AssertionError",
"AttributeError",
"BaseException",
"EOFError",
"Ellipsis",
"Exception",
"GeneratorExit",
"ImportError",
"IndentationError",
"IndexError",
"KeyError",
"KeyboardInterrupt",
"LookupError",
"MemoryError",
"NameError",
"NoneType",
"NotImplementedError",
"OSError",
"OverflowError",
"RuntimeError",
"StopIteration",
"SyntaxError",
"SystemExit",
"TypeError",
"ValueError",
"ZeroDivisionError",
"abs",
"all",
"any",
"append",
"args",
"bool",
"builtins",
"bytearray",
"bytecode",
"bytes",
"callable",
"chr",
"classmethod",
"clear",
"close",
"const",
"copy",
"count",
"dict",
"dir",
"divmod",
"end",
"endswith",
"eval",
"exec",
"extend",
"find",
"format",
"from_bytes",
"get",
"getattr",
"globals",
"hasattr",
"hash",
"id",
"index",
"insert",
"int",
"isalpha",
"isdigit",
"isinstance",
"islower",
"isspace",
"issubclass",
"isupper",
"items",
"iter",
"join",
"key",
"keys",
"len",
"list",
"little",
"locals",
"lower",
"lstrip",
"main",
"map",
"micropython",
"next",
"object",
"open",
"ord",
"pop",
"popitem",
"pow",
"print",
"range",
"read",
"readinto",
"readline",
"remove",
"replace",
"repr",
"reverse",
"rfind",
"rindex",
"round",
"rsplit",
"rstrip",
"self",
"send",
"sep",
"set",
"setattr",
"setdefault",
"sort",
"sorted",
"split",
"start",
"startswith",
"staticmethod",
"step",
"stop",
"str",
"strip",
"sum",
"super",
"throw",
"to_bytes",
"tuple",
"type",
"update",
"upper",
"utf-8",
"value",
"values",
"write",
"zip",
]
# this must match the equivalent function in qstr.c
def compute_hash(qstr, bytes_hash):
hash = 5381
for b in qstr:
hash = (hash * 33) ^ b
# Make sure that valid hash is never zero, zero means "hash not computed"
return (hash & ((1 << (8 * bytes_hash)) - 1)) or 1
def qstr_escape(qst):
def esc_char(m):
c = ord(m.group(0))
try:
name = codepoint2name[c]
except KeyError:
name = '0x%02x' % c
return "_" + name + '_'
return re.sub(r'[^A-Za-z0-9_]', esc_char, qst)
def parse_input_headers(infiles):
qcfgs = {}
qstrs = {}
# add static qstrs
for qstr in static_qstr_list:
# work out the corresponding qstr name
ident = qstr_escape(qstr)
# don't add duplicates
assert ident not in qstrs
# add the qstr to the list, with order number to retain original order in file
order = len(qstrs) - 300000
qstrs[ident] = (order, ident, qstr)
# read the qstrs in from the input files
for infile in infiles:
with open(infile, 'rt') as f:
for line in f:
line = line.strip()
# is this a config line?
match = re.match(r'^QCFG\((.+), (.+)\)', line)
if match:
value = match.group(2)
if value[0] == '(' and value[-1] == ')':
# strip parenthesis from config value
value = value[1:-1]
qcfgs[match.group(1)] = value
continue
# is this a QSTR line?
match = re.match(r'^Q\((.*)\)$', line)
if not match:
continue
# get the qstr value
qstr = match.group(1)
# special cases to specify control characters
if qstr == '\\n':
qstr = '\n'
elif qstr == '\\r\\n':
qstr = '\r\n'
# work out the corresponding qstr name
ident = qstr_escape(qstr)
# don't add duplicates
if ident in qstrs:
continue
# add the qstr to the list, with order number to retain original order in file
order = len(qstrs)
# but put special method names like __add__ at the top of list, so
# that their id's fit into a byte
if ident == "":
# Sort empty qstr above all still
order = -200000
elif ident == "__dir__":
# Put __dir__ after empty qstr for builtin dir() to work
order = -190000
elif ident.startswith("__"):
order -= 100000
qstrs[ident] = (order, ident, qstr)
if not qcfgs:
sys.stderr.write("ERROR: Empty preprocessor output - check for errors above\n")
sys.exit(1)
return qcfgs, qstrs
def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr):
qbytes = bytes_cons(qstr, 'utf8')
qlen = len(qbytes)
qhash = compute_hash(qbytes, cfg_bytes_hash)
if all(32 <= ord(c) <= 126 and c != '\\' and c != '"' for c in qstr):
# qstr is all printable ASCII so render it as-is (for easier debugging)
qdata = qstr
else:
# qstr contains non-printable codes so render entire thing as hex pairs
qdata = ''.join(('\\x%02x' % b) for b in qbytes)
if qlen >= (1 << (8 * cfg_bytes_len)):
print('qstr is too long:', qstr)
assert False
qlen_str = ('\\x%02x' * cfg_bytes_len) % tuple(((qlen >> (8 * i)) & 0xff) for i in range(cfg_bytes_len))
qhash_str = ('\\x%02x' * cfg_bytes_hash) % tuple(((qhash >> (8 * i)) & 0xff) for i in range(cfg_bytes_hash))
return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata)
def print_qstr_data(qcfgs, qstrs):
# get config variables
cfg_bytes_len = int(qcfgs['BYTES_IN_LEN'])
cfg_bytes_hash = int(qcfgs['BYTES_IN_HASH'])
# print out the starter of the generated C header file
print('// This file was automatically generated by makeqstrdata.py')
print('')
# add NULL qstr with no hash or data
print('QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' % ('\\x00' * cfg_bytes_hash, '\\x00' * cfg_bytes_len))
# go through each qstr and print it out
for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]):
qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr)
print('QDEF(MP_QSTR_%s, %s)' % (ident, qbytes))
def do_work(infiles):
qcfgs, qstrs = parse_input_headers(infiles)
print_qstr_data(qcfgs, qstrs)
if __name__ == "__main__":
do_work(sys.argv[1:])
|
// loadLimits loads the consumer quota metric for a given project and the list of services.
// The limits are defined wrt to the regions. If the limit is global, it's location is treated as `global` else the
// region value is used for location.
func loadLimits(ctx context.Context, client *serviceusage.ServicesService, project string, services ...string) ([]record, error) {
parent := fmt.Sprintf("projects/%s/services/", project)
for i := range services {
if !strings.HasPrefix(services[i], parent) {
services[i] = fmt.Sprintf("%s%s", parent, services[i])
}
}
var limits []record
for _, service := range services {
if err := client.ConsumerQuotaMetrics.
List(service).
Context(ctx).
Pages(ctx, func(page *serviceusage.ListConsumerQuotaMetricsResponse) error {
for _, qm := range page.Metrics {
for _, ql := range qm.ConsumerQuotaLimits {
for _, qlb := range ql.QuotaBuckets {
limit := record{
Service: service[strings.LastIndex(service, "/")+1:],
Name: ql.Metric,
Location: "global",
}
region, ok := qlb.Dimensions["region"]
if ok {
limit.Location = region
}
if qlb.EffectiveLimit < 0 {
continue
}
limit.Value = qlb.EffectiveLimit
limits = append(limits, limit)
}
}
}
return nil
}); err != nil {
return nil, err
}
}
return limits, nil
} |
package com.nhn.android.deview.ui.note;
import java.util.Vector;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.nhn.android.deview.AppContext;
import com.nhn.android.deview.R;
import com.nhn.android.deview.core.db.CursorReader;
import com.nhn.android.deview.core.lifecycle.CycleControllerActivity;
import com.nhn.android.deview.core.listview.ListCellViewAdapter;
import com.nhn.android.deview.dao.DeviewUri;
import com.nhn.android.deview.dao.MyMemo;
import com.nhn.android.deview.dao.MyMemoManager;
public class MemoListActivity extends CycleControllerActivity implements OnItemClickListener {
ListView mListView;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_memolist, true);
Vector<MyMemo> list = MyMemoManager.getMemoList();
if (list != null) {
ListCellViewAdapter<MyMemo> adapter =
new ListCellViewAdapter<MyMemo>(MemoCellView.class,list);
mListView.setAdapter(adapter);
}
}
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long arg3) {
MemoCellView cellView = (MemoCellView) view;
if (cellView.mData.mediaUri != null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(cellView.mData.mediaUri), "video/mpeg");
startActivity(intent);
}
}
}
|
#include "Circuit.h"
#include <iostream>
void Circuit::SetLength(int alength)
{
length = alength;
}
Circuit::Circuit()
{
length = 0;
count = 0;
max_count = 20;
w = sunny;
}
void Circuit::SetWeather(Weather w2)
{
w = w2;
}
bool Circuit::AddCar(Car* car)
{
if (count < max_count)
{
vector[count++] = car;
return true;
}
return false;
}
void Circuit::Race()
{
Car* x;
for(int i = 0 ; i < count - 1; i++)
for (int j = i+1; j < count; j++)
if (vector[i]->GetAverageSpeed(w) < vector[j]->GetAverageSpeed(w))
{
x = vector[i];
vector[i] = vector[j];
vector[j] = x;
}
for (int i = 0; i < count; i++)
std::cout << i + 1 << ". " << vector[i]->GetName()<<std::endl;
//n-am avut timp sa implementez altfel functia asta, si nici celelalte doua functii
} |
"""
Valve v2 lighthouse power management over BT LE
"""
# external libs
from bluepy import btle
# standard imports
import signal
import sys
import time
from functools import partial
# globals
#-------------------------------------------------------------------------------
# return error code
EXIT_OK = 0
EXIT_ERR = -1
# verbosity level INFO
INFO = 1
# LHv2 GATT service
LHV2_GATT_SERVICE_UUID = btle.UUID('00001523-1212-efde-1523-785feabcd124')
LHV2_GATT_CHAR_POWER_CTRL_UUID = btle.UUID('00001525-1212-efde-1523-785feabcd124')
LHV2_GATT_CHAR_MODE_UUID = btle.UUID('00001524-1212-efde-1523-785feabcd124')
# Power management
POWER_ON = b'\x01'
POWER_OFF = b'\x00'
# defaults
#-------------------------------------------------------------------------------
TRY_COUNT = 1
TRY_PAUSE = 2
GLOBAL_TIMEOUT = 0
# LHV2 class
#-------------------------------------------------------------------------------
class LHV2:
"""LHv2 abstraction."""
def __init__(self, macAddr, hciIface, verbose = 0):
"""Connect to the BTLE server in LHv2."""
self.dev = btle.Peripheral()
self.macAddr = macAddr
self.hciIface = hciIface
self.verbose = verbose
self.services = None
self.characteristics = None
self.name = None
def connect(self, try_count, try_pause):
"""Connect to LH, try it `try_count` times."""
while True:
try:
if (self.verbose >= INFO):
print(f'Connecting to {self.macAddr} at {time.asctime()} -> ', end='')
self.dev.connect(self.macAddr, iface=self.hciIface, addrType=btle.ADDR_TYPE_RANDOM)
if (self.verbose >= INFO):
print(self.dev.getState())
break
except btle.BTLEDisconnectError as e:
if try_count <= 1:
raise e
if (self.verbose >= INFO):
print(e)
try_count -= 1
time.sleep(try_pause)
continue
except:
raise
# initialize the device topology only at the first connect
# services are not needed at the moment
#if self.services is None:
# self.services = self.dev.discoverServices()
if self.characteristics is None:
chars = self.dev.getCharacteristics()
self.characteristics = dict([(c.uuid, c) for c in chars])
if self.name is None:
self.name = self.getCharacteristic(btle.AssignedNumbers.device_name).read().decode()
if self.verbose >= INFO:
mode = self.getCharacteristic(LHV2_GATT_CHAR_MODE_UUID).read()
print(f'Connected to {self.name} ({self.dev.addr}, mode={mode.hex()})')
def disconnect(self):
if self.verbose >= INFO:
print(f'Diconnecting from {self.name} at {time.asctime()}')
self.dev.disconnect()
def getCharacteristic(self, uuid):
return self.characteristics[uuid]
def writeCharacteristic(self, uuid, val):
charc = self.getCharacteristic(uuid)
charc.write(val, withResponse=True)
if self.verbose >= INFO:
print(f'Writing {val.hex()} to {charc.uuid.getCommonName()}')
def getName(self):
return self.name
def powerOn(self):
self.writeCharacteristic(LHV2_GATT_CHAR_POWER_CTRL_UUID, POWER_ON)
def powerOff(self):
self.writeCharacteristic(LHV2_GATT_CHAR_POWER_CTRL_UUID, POWER_OFF)
# functions
#-------------------------------------------------------------------------------
def wait(secs, verb=0):
if secs != 0:
if (verb >= INFO):
print(f'Sleeping for {secs} sec ... ', end='', flush=True)
time.sleep(secs)
if (verb >= INFO):
print('Done!', flush=True)
else:
if (verb >= INFO):
print(f'Sleeping indefinitely', flush=True)
signal.pause()
def boot(args):
"""Boot the lighthouses."""
try:
for mac in args.lh_mac:
lhv2 = LHV2(mac, args.interface, args.verbose)
lhv2.connect(args.try_count, args.try_pause)
if args.verbose >= INFO:
print(f'Booting up {lhv2.getName()}')
lhv2.powerOn()
lhv2.disconnect()
if not args.no_wait:
wait(args.global_timeout, verb=args.verbose)
except KeyboardInterrupt:
print()
print('Keyboard interrupt caught')
pass
def shutdown(args):
"""Shut down the lighthouses."""
for mac in args.lh_mac:
lhv2 = LHV2(mac, args.interface, args.verbose)
lhv2.connect(args.try_count, args.try_pause)
if args.verbose >= INFO:
print(f'Shutting down {lhv2.getName()}')
lhv2.powerOff()
lhv2.disconnect()
def sigterm_hndlr(args, sigterm_def, signum, frame):
"""Signal wrapper for the shutdown function."""
if args.verbose >= INFO:
print()
print(f'Signal {repr(signum)} caught.')
shutdown(args)
if sigterm_def != signal.SIG_DFL:
sigterm_def(signum, frame)
else:
sys.exit(EXIT_OK)
def main(args):
"""Main runner."""
signal.signal(signal.SIGTERM, partial(sigterm_hndlr, args, signal.getsignal(signal.SIGTERM)))
signal.signal(signal.SIGHUP, partial(sigterm_hndlr, args, signal.getsignal(signal.SIGHUP)))
if not args.shutdown_only:
boot(args)
if not args.start_only:
shutdown(args)
# main
#-------------------------------------------------------------------------------
if __name__ == '__main__':
from argparse import ArgumentParser
ap = ArgumentParser(description='Wakes up and runs Valve v2 lighthouse(s) using BT LE power management')
ap.add_argument('lh_mac', type=str, nargs='+', help='MAC address(es) of the lighthouse(s) (in format aa:bb:cc:dd:ee:ff)')
ap.add_argument('-g', '--global_timeout', type=int, default=GLOBAL_TIMEOUT, help='time (sec) how long to keep the lighthouse(s) alive (0=forever) [%(default)s]')
ap.add_argument('-i', '--interface', type=int, default=0, help='The Bluetooth interface on which to make the connection to be set. On Linux, 0 means /dev/hci0, 1 means /dev/hci1 and so on. [%(default)s]')
ap.add_argument('--try_count', type=int, default=TRY_COUNT, help='number of tries to set up a connection [%(default)s]')
ap.add_argument('--try_pause', type=int, default=TRY_PAUSE, help='sleep time when reconnecting [%(default)s]')
ap.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of the log to stdout')
ap.add_argument('--start_only', action='store_true')
ap.add_argument('--shutdown_only', action='store_true')
ap.add_argument('--no_wait', action='store_true')
args = ap.parse_args()
main(args)
|
//Spring scanning should not be invoked as this should not be loaded during boot.
@org.springframework.context.annotation.Configuration
public class DetectorBeanConfiguration {
//Provided Dependencies
@Autowired
public Gson gson;
@Autowired
public Configuration configuration;
@Autowired
public DocumentBuilder documentBuilder;
@Autowired
public ExecutableRunner executableRunner;
@Autowired
public AirGapManager airGapManager;
@Autowired
public ExecutableFinder executableFinder;
@Autowired
public ExternalIdFactory externalIdFactory;
@Autowired
public DetectFileFinder detectFileFinder;
@Autowired
public DirectoryManager directoryManager;
@Autowired
public DetectConfiguration detectConfiguration;
@Autowired
public ConnectionManager connectionManager;
@Autowired
public CacheableExecutableFinder cacheableExecutableFinder;
@Autowired
public ArtifactResolver artifactResolver;
@Autowired
public DetectInfo detectInfo;
@Bean
public DetectorOptionFactory detectorOptionFactory() {
return new DetectorOptionFactory(detectConfiguration);
}
//DetectorFactory
//This is the ONLY class that should be taken from the Configuration manually.
//Detectors should be accessed using the DetectorFactory which will create them through Spring.
@Bean
public DetectorFactory detectorFactory() {
return new DetectorFactory();
}
//Detector-Only Dependencies
//All detector support classes. These are classes not actually used outside of the bom tools but are necessary for some bom tools.
@Bean
public DependenciesListFileManager clangDependenciesListFileParser() {
return new DependenciesListFileManager(executableRunner, clangCompileCommandParser());
}
@Bean
ClangCompileCommandParser clangCompileCommandParser() {
return new ClangCompileCommandParser();
}
@Bean
public CodeLocationAssembler codeLocationAssembler() {
return new CodeLocationAssembler(externalIdFactory);
}
@Bean
public BazelExtractor bazelExtractor() {
BazelQueryXmlOutputParser parser = new BazelQueryXmlOutputParser(new XPathParser());
BazelExternalIdExtractionSimpleRules rules = new BazelExternalIdExtractionSimpleRules(detectConfiguration.getProperty(DetectProperty.DETECT_BAZEL_TARGET, PropertyAuthority.None));
BazelCodeLocationBuilder codeLocationGenerator = new BazelCodeLocationBuilder(externalIdFactory);
BazelExternalIdExtractionFullRuleJsonProcessor bazelExternalIdExtractionFullRuleJsonProcessor = new BazelExternalIdExtractionFullRuleJsonProcessor(gson);
return new BazelExtractor(detectConfiguration, executableRunner, parser, rules, codeLocationGenerator, bazelExternalIdExtractionFullRuleJsonProcessor);
}
@Bean
public ClangExtractor clangExtractor() {
return new ClangExtractor(detectConfiguration, executableRunner, gson, detectFileFinder, directoryManager, clangDependenciesListFileParser(), codeLocationAssembler());
}
public List<ClangLinuxPackageManager> clangLinuxPackageManagers() {
final List<ClangLinuxPackageManager> clangLinuxPackageManagers = new ArrayList<>();
clangLinuxPackageManagers.add(new ApkPackageManager());
clangLinuxPackageManagers.add(new DpkgPackageManager());
clangLinuxPackageManagers.add(new RpmPackageManager());
return clangLinuxPackageManagers;
}
@Bean
public PodlockParser podlockParser() {
return new PodlockParser(externalIdFactory);
}
@Bean
public PodlockExtractor podlockExtractor() {
return new PodlockExtractor(podlockParser(), externalIdFactory);
}
@Bean
public CondaListParser condaListParser() {
return new CondaListParser(gson, externalIdFactory);
}
@Bean
public CondaCliExtractor condaCliExtractor() {
return new CondaCliExtractor(condaListParser(), externalIdFactory, executableRunner, detectConfiguration, directoryManager);
}
@Bean
public CpanListParser cpanListParser() {
return new CpanListParser(externalIdFactory);
}
@Bean
public CpanCliExtractor cpanCliExtractor() {
return new CpanCliExtractor(cpanListParser(), externalIdFactory, executableRunner, directoryManager);
}
@Bean
public PackratPackager packratPackager() {
return new PackratPackager(externalIdFactory);
}
@Bean
public PackratLockExtractor packratLockExtractor() {
return new PackratLockExtractor(packratPackager(), externalIdFactory, detectFileFinder);
}
@Bean
public GoDepExtractor goDepExtractor() {
return new GoDepExtractor(depPackager(), externalIdFactory);
}
@Bean
public GoInspectorManager goInspectorManager() {
return new GoInspectorManager(directoryManager, executableFinder, executableRunner, detectConfiguration);
}
@Bean
public GoVndrExtractor goVndrExtractor() {
return new GoVndrExtractor(externalIdFactory);
}
@Bean
public GoVendorExtractor goVendorExtractor() {
return new GoVendorExtractor(gson, externalIdFactory);
}
@Bean
public DepPackager depPackager() {
return new DepPackager(executableRunner, externalIdFactory, detectConfiguration);
}
@Bean
public GradleReportParser gradleReportParser() {
return new GradleReportParser(externalIdFactory);
}
@Bean
public GradleExecutableFinder gradleExecutableFinder() {
return new GradleExecutableFinder(executableFinder, detectConfiguration);
}
@Bean
public GradleInspectorExtractor gradleInspectorExtractor() {
return new GradleInspectorExtractor(executableRunner, detectFileFinder, gradleReportParser(), detectConfiguration);
}
@Bean
public GradleInspectorManager gradleInspectorManager() throws ParserConfigurationException {
return new GradleInspectorManager(directoryManager, airGapManager, configuration, detectConfiguration, artifactResolver);
}
@Bean
public Rebar3TreeParser rebar3TreeParser() {
return new Rebar3TreeParser(externalIdFactory);
}
@Bean
public RebarExtractor rebarExtractor() {
return new RebarExtractor(executableRunner, rebar3TreeParser());
}
@Bean
public MavenCodeLocationPackager mavenCodeLocationPackager() {
return new MavenCodeLocationPackager(externalIdFactory);
}
@Bean
public MavenCliExtractor mavenCliExtractor() {
return new MavenCliExtractor(executableRunner, mavenCodeLocationPackager(), detectConfiguration);
}
@Bean
public MavenExecutableFinder mavenExecutableFinder() {
return new MavenExecutableFinder(executableFinder, detectConfiguration);
}
@Bean
public BazelExecutableFinder bazelExecutableFinder() {
return new BazelExecutableFinder(executableRunner, directoryManager, executableFinder, detectConfiguration);
}
@Bean
public NpmCliParser npmCliDependencyFinder() {
return new NpmCliParser(externalIdFactory);
}
@Bean
public NpmLockfileParser npmLockfilePackager() {
return new NpmLockfileParser(gson, externalIdFactory);
}
@Bean
public NpmCliExtractor npmCliExtractor() {
return new NpmCliExtractor(executableRunner, npmCliDependencyFinder(), detectConfiguration);
}
@Bean
public NpmLockfileExtractor npmLockfileExtractor() {
return new NpmLockfileExtractor(npmLockfilePackager(), detectConfiguration);
}
@Bean
public NpmExecutableFinder npmExecutableFinder() {
return new NpmExecutableFinder(directoryManager, executableFinder, executableRunner, detectConfiguration);
}
@Bean
public NugetInspectorPackager nugetInspectorPackager() {
return new NugetInspectorPackager(gson, externalIdFactory);
}
@Bean
public NugetInspectorExtractor nugetInspectorExtractor() {
return new NugetInspectorExtractor(nugetInspectorPackager(), detectFileFinder, detectConfiguration);
}
@Bean
public NugetInspectorManager nugetInspectorManager() {
return new NugetInspectorManager(directoryManager, executableFinder, executableRunner, detectConfiguration, airGapManager, artifactResolver, detectInfo, detectFileFinder);
}
@Bean
public PackagistParser packagistParser() {
return new PackagistParser(externalIdFactory, detectConfiguration);
}
@Bean
public ComposerLockExtractor composerLockExtractor() {
return new ComposerLockExtractor(packagistParser());
}
@Bean
public PearParser pearDependencyFinder() {
return new PearParser(externalIdFactory, detectConfiguration);
}
@Bean
public PearCliExtractor pearCliExtractor() {
return new PearCliExtractor(detectFileFinder, externalIdFactory, pearDependencyFinder(), executableRunner, directoryManager);
}
@Bean
public PipenvGraphParser pipenvGraphParser() {
return new PipenvGraphParser(externalIdFactory);
}
@Bean
public PipenvExtractor pipenvExtractor() {
return new PipenvExtractor(executableRunner, pipenvGraphParser(), detectConfiguration);
}
@Bean
public PipInspectorTreeParser pipInspectorTreeParser() {
return new PipInspectorTreeParser(externalIdFactory);
}
@Bean
public PipInspectorExtractor pipInspectorExtractor() {
return new PipInspectorExtractor(executableRunner, pipInspectorTreeParser(), detectConfiguration);
}
@Bean
public PipInspectorManager pipInspectorManager() {
return new PipInspectorManager(directoryManager);
}
@Bean
public PythonExecutableFinder pythonExecutableFinder() {
return new PythonExecutableFinder(executableFinder, detectConfiguration);
}
@Bean
public GemlockExtractor gemlockExtractor() {
return new GemlockExtractor(externalIdFactory);
}
@Bean
public SbtResolutionCacheExtractor sbtResolutionCacheExtractor() {
return new SbtResolutionCacheExtractor(detectFileFinder, externalIdFactory, detectConfiguration);
}
@Bean
public YarnListParser yarnListParser() {
return new YarnListParser(externalIdFactory, yarnLockParser());
}
@Bean
public YarnLockParser yarnLockParser() {
return new YarnLockParser();
}
@Bean
public YarnLockExtractor yarnLockExtractor() {
return new YarnLockExtractor(externalIdFactory, yarnListParser(), executableRunner, detectConfiguration);
}
@Bean
public GraphParserTransformer graphParserTransformer() {
return new GraphParserTransformer();
}
@Bean
public BitbakeExtractor bitbakeExtractor() {
return new BitbakeExtractor(executableRunner, directoryManager, detectFileFinder, graphParserTransformer(), bitbakeListTasksParser());
}
@Bean
public BitbakeListTasksParser bitbakeListTasksParser() {
return new BitbakeListTasksParser();
}
//BomTools
//Should be scoped to Prototype so a new Detector is created every time one is needed.
//Should only be accessed through the DetectorFactory.
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public BazelDetector bazelDetector(final DetectorEnvironment environment) {
return new BazelDetector(environment, bazelExtractor(), bazelExecutableFinder(), detectConfiguration);
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public BitbakeDetector bitbakeBomTool(final DetectorEnvironment environment) {
return new BitbakeDetector(environment, detectFileFinder, detectorOptionFactory().createBitbakeDetectorOptions(), bitbakeExtractor(), cacheableExecutableFinder);
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public ClangDetector clangBomTool(final DetectorEnvironment environment) {
return new ClangDetector(environment, executableRunner, detectFileFinder, clangLinuxPackageManagers(), clangExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public ComposerLockDetector composerLockBomTool(final DetectorEnvironment environment) {
return new ComposerLockDetector(environment, detectFileFinder, composerLockExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public CondaCliDetector condaBomTool(final DetectorEnvironment environment) {
return new CondaCliDetector(environment, detectFileFinder, cacheableExecutableFinder, condaCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public CpanCliDetector cpanCliBomTool(final DetectorEnvironment environment) {
return new CpanCliDetector(environment, detectFileFinder, cacheableExecutableFinder, cpanCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GemlockDetector gemlockBomTool(final DetectorEnvironment environment) {
return new GemlockDetector(environment, detectFileFinder, gemlockExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GoCliDetector goCliBomTool(final DetectorEnvironment environment) {
return new GoCliDetector(environment, detectFileFinder, cacheableExecutableFinder, goInspectorManager(), goDepExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GoLockDetector goLockBomTool(final DetectorEnvironment environment) {
return new GoLockDetector(environment, detectFileFinder, cacheableExecutableFinder, goInspectorManager(), goDepExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GoVndrDetector goVndrBomTool(final DetectorEnvironment environment) {
return new GoVndrDetector(environment, detectFileFinder, goVndrExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GoVendorDetector goVendorBomTool(final DetectorEnvironment environment) {
return new GoVendorDetector(environment, detectFileFinder, goVendorExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public GradleInspectorDetector gradleInspectorBomTool(final DetectorEnvironment environment) throws ParserConfigurationException {
return new GradleInspectorDetector(environment, directoryManager, detectFileFinder, gradleExecutableFinder(), gradleInspectorManager(), gradleInspectorExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public MavenPomDetector mavenPomBomTool(final DetectorEnvironment environment) {
return new MavenPomDetector(environment, detectFileFinder, mavenExecutableFinder(), mavenCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public MavenPomWrapperDetector mavenPomWrapperBomTool(final DetectorEnvironment environment) {
return new MavenPomWrapperDetector(environment, detectFileFinder, mavenExecutableFinder(), mavenCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public NpmCliDetector npmCliBomTool(final DetectorEnvironment environment) {
return new NpmCliDetector(environment, detectFileFinder, npmExecutableFinder(), npmCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public NpmPackageLockDetector npmPackageLockBomTool(final DetectorEnvironment environment) {
return new NpmPackageLockDetector(environment, detectFileFinder, npmLockfileExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public NugetProjectDetector nugetProjectBomTool(final DetectorEnvironment environment) {
return new NugetProjectDetector(environment, directoryManager, detectFileFinder, nugetInspectorManager(), nugetInspectorExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public NpmShrinkwrapDetector npmShrinkwrapBomTool(final DetectorEnvironment environment) {
return new NpmShrinkwrapDetector(environment, detectFileFinder, npmLockfileExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public NugetSolutionDetector nugetSolutionBomTool(final DetectorEnvironment environment) {
return new NugetSolutionDetector(environment, detectFileFinder, nugetInspectorManager(), nugetInspectorExtractor(), directoryManager);
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PackratLockDetector packratLockBomTool(final DetectorEnvironment environment) {
return new PackratLockDetector(environment, detectFileFinder, packratLockExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PearCliDetector pearCliBomTool(final DetectorEnvironment environment) {
return new PearCliDetector(environment, detectFileFinder, cacheableExecutableFinder, pearCliExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PipenvDetector pipenvBomTool(final DetectorEnvironment environment) {
return new PipenvDetector(environment, detectFileFinder, pythonExecutableFinder(), pipenvExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PipInspectorDetector pipInspectorBomTool(final DetectorEnvironment environment) {
//final String requirementsFile = detectConfiguration.getProperty(DetectProperty.DETECT_PIP_REQUIREMENTS_PATH, PropertyAuthority.None);
return new PipInspectorDetector(environment, detectConfiguration.getProperty(DetectProperty.DETECT_PIP_REQUIREMENTS_PATH, PropertyAuthority.None), detectFileFinder, pythonExecutableFinder(), pipInspectorManager(),
pipInspectorExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public PodlockDetector podLockBomTool(final DetectorEnvironment environment) {
return new PodlockDetector(environment, detectFileFinder, podlockExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public RebarDetector rebarBomTool(final DetectorEnvironment environment) {
return new RebarDetector(environment, detectFileFinder, cacheableExecutableFinder, rebarExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public SbtResolutionCacheDetector sbtResolutionCacheBomTool(final DetectorEnvironment environment) {
return new SbtResolutionCacheDetector(environment, detectFileFinder, sbtResolutionCacheExtractor());
}
@Bean
@Scope(scopeName = BeanDefinition.SCOPE_PROTOTYPE)
public YarnLockDetector yarnLockBomTool(final DetectorEnvironment environment) {
return new YarnLockDetector(environment, detectFileFinder, cacheableExecutableFinder, yarnLockExtractor());
}
} |
Mutagenesis of the K-ras protooncogene in mouse lung tumors induced by N-ethyl-N-nitrosourea or N-nitrosodiethylamine. The role of ras gene activation in the development of lung tumors induced by N-ethyl-N-nitrosourea (ENU) and N-nitrosodiethylamine (DEN) was evaluated in the A/J mouse, a strain susceptible to chemically induced lung tumors. DNAs isolated from both ENU- and DEN-induced lung tumors were screened for activating mutations in the K-ras gene by utilizing the polymerase chain reaction (PCR) and direct sequence analysis. Mutations in the K-ras gene were detected in 11 of 11 ENU-induced tumors and 23 of 28 DEN-induced tumors. In ENU-induced tumors, there were three GC----AT transitions in the second base of codon 12, and seven AT----GC transitions and one AT----TA transversion in the second base of codon 61. A similar spectrum of K-ras mutations was observed in DEN-induced lung tumors: five GC----AT transitions and two GC----TA transversions in the second base of codon 12, and sixteen AT----GC transitions at the second base of codon 61. Ninety-one percent (31/34) of the observed mutations are consistent with the formation of the promutagenic O4-ethylthymine and O6-ethylguanine adducts in DNA. Therefore, lung tumors from the A/J mouse induced by DEN and ENU could be initiated by the interaction of reactive metabolites with specific sites in the K-ras gene. This is the first clear example of activation of the K-ras gene by ethylating agents in a rodent lung tumor system. |
A Study of the Factors Influencing Investors' Expectations in the Chinese Stock Market. With the continuous development of behavior finance, scholars have paid more and more attention to the irrational factors in the stock market, and the research on the psychological factors of investors in the stock market is also more in-depth. The decline of the irrational investment sentiment of the noise investors caused by the decline of the investment value of the stock market has weakened the adverse effects of the investor's non-rational behavior on the stock market, and thus, the negative effects of the investor's non-rational behavior on the stock market are weakened. The expectations of rational institutional investors and some rational individual investors begin to rise. The relevant government departments can use the conclusion of this paper to guide investors to regulate the stock market, and investors can adjust their investment strategies promptly according to the conclusion of this article. Introducation As one of the investment activities with the largest number of participants, the stock market is characterized by its wide coverage, a large number of participants, and a large amount of capital, and is widely influenced by psychological factors such as expectations, which are inseparably linked to the expectations of stock market investors. As an important factor affecting stock market movements, investor expectations largely determine the future direction of stock market development. The development of China's stock market currently requires government departments to take measures to help investors restore confidence in the stock market so that investors can form positive and reasonable expectations and gradually eliminate the negative impact of negative expectations. Research on the role of expectations at home and abroad shows that expectations have a strong influence on investor sentiment, stock market yields, monetary policy, stock prices, interest rate policy and other stock market quality factors, macroeconomics, monetary policy, and investor behavior. Expectations, as a psychological factor, are an important cause of abnormal changes in asset prices and lead to enhanced market speculation. Irrational investor expectations have caused turmoil in financial markets, and heterogeneous expectations of institutional investors have contributed to IPO pricing biases. Domestic and international research on expectations has shown that expectations have a significant impact on stock market returns, monetary policy, the stock index futures market, and IPO pricing bias. This paper presents a theoretical analysis of the factors influencing investors' expectations by summarising the current state of research at home and abroad. This paper presents a theoretical analysis of the factors influencing investors' expectations in the stock market from several perspectives: irrational factors in the stock market, stock market quality, and macroeconomics. It also concludes with policy recommendations for government departments and stock market investors. Keynes felt that investors make decisions based on their expectations of others' choices, Fried proposed adaptive expectations and expressed consumer choice as people forming expectations of how things will develop in the future based on past information. Lucas argued that subjects of economic activity have full access to all available Adam, and Klaus investigated the relationship between investor sentiment and stock market expectations, finding that expectations are higher at the peak (lower) and lower at the bottom. found that expectations are overly optimistic (pessimistic) at peaks (lows), demonstrating that investor expectations are not rational expectations. Annarita Colasante, and Antonio Palestrini analyzed the behavior of experimental subjects in an experimental setting and showed that it is difficult for overall expectations to converge to rational expectations when individuals are all part of adaptive expectations. Investor influences Jorg Bley, Mohsen Saad studied the particular volatility of seven frontier markets in six GCC countries and found that there was a significant negative correlation between stock market expectations and lagged qualitative volatility in individual stocks in Saudi Arabia, but not in the investment markets of Kuwait and Abu Dhabi, while, when using EGARCH or AR models to estimate conditional idiosyncratic volatility, the relationship becomes positive. chunpeng Yang examines the effect of sentiment on stock market expectations by building a sentiment asset pricing model and explores how stock market expectations change when parameters change under different circumstances. When overall market sentiment is low, stock market expectations fall. Omankhanlen Alex Ehimare et al. used the short-term dynamics of macroeconomic indicators and stock prices over the period 1985-2014, the study explored the relationship between stock price movements and macroeconomic activities in the Nigerian stock market The nature of the correlation that exists, concluded that the inflation rate is consistent with the movement of stock prices, in line with theoretical expectations, as a result of investors' perception that the stock market has inflation protection during the later period of structural adjustment, and that even though the exchange rate grows in the same direction as stock prices, as a country's exchange rate rises, stock prices in China will become cheaper and therefore attractive to foreign investors. It is recommended that stock market investors should pay attention to trends in the fluctuation of macroeconomic variables in order to predict stock market price movements. Theoretical analysis of the factors influencing investors' expectations By combing through the literature on factors influencing expectations at home and abroad, it is found that investor irrationality factors, stock market quality factors, and macroeconomic factors all have an impact on stock market investor expectations. Irrational factors in the stock market affect investor expectations Investor sentiment is a kind of psychological expectation of the future trend of the stock market due to the combined influence of various information from various sources, and this expectation of investors actually has a certain bias on the future price of risky assets, and this expectation of investors will have a significant impact on the behavior of investors, which will, in turn, affect the price determination of the relevant assets in the stock market. This has a significant impact on investor behavior, which in turn affects the price determination of the underlying assets in the equity markets. Investor sentiment is essentially an investor's assessment of investment returns on the basis of limited rational expectations, taking into account individual characteristics such as risk, the opportunity cost of capital, and expected returns on investment, and ultimately the results are expressed externally in the form of investor sentiment or action. Macroeconomic influences on investor expectations The development of the stock market not only reflects the development of the macroeconomy but also contributes to the sustainable development of our macroeconomy through capital financing. Studies at home and abroad have shown that there is a clear correlation between a country's macroeconomic development and the degree of stock market development. The impact of macroeconomic performance on the stock market is mainly based on the following path: when the macroeconomic situation is good, it indicates that the country's economic situation tends to be good in the coming period, and the main body of investors in the stock market will have optimistic expectations and increased confidence in the investment. The macroeconomic boom will lead to an increase in the country's GDP and corporate profits, which will be reflected in the growth of stock returns on the stock market. On the other hand, as most investors have good expectations for the future of the country's economy, this may lead to investors increasing the amount and duration of their investment plans, thus further boosting the stock market. In times of macroeconomic downturn, all of the above will show the opposite trend. Stock market volatility directly or indirectly affects investor expectations The volatility of stock market indices represents the riskiness of the stock market, which is an investment market where risk and return co-exist, and Sharp proposed the CAPM model in 1964, which showed a simple linear positive correlation between risk and return in the stock market. used the beta coefficients of all stocks in the New York Stock Exchange from January 1935 to June 1968 as the object of their study, and employed cross-sectional regression analysis on the basis of grouping, and the empirical results showed that there was a significant linear positive correlation between stock market risk and return. Wu Changfeng et al. conducted a cross-sectional comparative analysis of the risk characteristics of China's stock market and found that there is a significant positive correlation between stock market risk and its return in the long run. An increase in stock index volatility implies an increase in risk and return, while a large number of noise traders in China's stock market investors are risk-averse investors who chase risk and dream of short-term riches, and a large number of investors will enter the stock market when the stock market volatility, i.e. risk, becomes greater in pursuit of high returns, which on the one hand will generate herding effects leading investors to form upward expectations, and on the other hand, the stock market, On the other hand, stock market volatility will expand the degree of investors' risk appetite, leading to an increase in the degree of the irrationality of investors, and eventually, the cognitive bias and behavioral bias of investors will intensify at the same time to form an impact on the stock market, making investors' expectations rise, i.e. the volatility of stock indices becomes greater leading to the rise of stock market investors' expectations. Shiller suggests that in the stock trading market, most investors' investment decisions and behavior are not basically due to changes in stock fundamentals, but simply because of changes in stock price trends, which are used to make their investment decisions and investment behavior, a trading behavior known as feedback trading behavior. Positive feedback trading behavior is considered to exist in the stock market if there is a significant positive correlation between investor demand for a particular stock and the historical return on that stock, and negative feedback trading behavior is considered to exist in the stock market if there is a significant negative correlation between investor demand for a particular stock and the historical return on that stock. Stock market returns directly or indirectly affect investor expectations Stock market returns, as a concentrated manifestation of the disorganized information in the stock market, are a product formed under the influence of multiple information, so stock market returns can explain and predict a lot of information. Due to the existence of significant positive feedback trading behavior in China's stock market, with the existence of a large number of noisy retail traders, as well as many rational retail investors and rational institutional investors, stock market returns continue to rise. The stock market due to the existence of positive feedback trading behavior, there will be a large number of bubbles generated, and at any time there is the possibility of bursting, the future development trend of the stock market appeared negative expectations. Policy recommendations In terms of the current situation of the Chinese stock market, it is clear that all aspects are not mature enough. For policymakers, the expectations of stock market investors will affect the development trend and direction of the stock market, so their expectations can be guided by favorable policies or the release of favorable news to enhance investor sentiment and thus influence investor expectations, but also to prevent investors from overheating investment sentiment leading to the formation of pessimistic expectations about the future trend of the stock market; in the stock market earnings rise Initially, the rise in stock market returns will lead to positive investor expectations, while a sustained rise in returns will lead to pessimistic investor expectations, so relevant government units should grasp investor expectations in a timely manner and provide guidance; government departments can also regulate stock market investor expectations by controlling the timing of capital inflows into the stock market through policies. During periods of high stock market volatility, government departments can control risk-averse investors to form positive expectations of the future development trend of the stock market through policies and press measures, so as to promote the healthy operation and development of China's stock market with good expectations. |
Understanding Videogame Cities This paper examines the city of Steelport in Saints Row: The Third as a real-and-imagined space that can be described using an urban framework of constitutional, representational, and experiential components. It relates mediated and physical cities through spatial arrangement, processes of representation, and the factors that contribute to a sense of place in both material and immaterial worlds. |
A reader who wishes to remain anonymous is curious about the structure of DVDs. He or she writes:
A friend has a DVD that he needs to turn into a QuickTime movie. He’s used a program that copies the contents of the DVD to a folder on his Mac. Inside this folder are VIDEO_TS and AUDIO_TS folders. The audio folder is empty, though. Does that mean that the converted movie won’t have audio?
No, it doesn’t. The original DVD standard didn’t include an AUDIO_TS folder. All content was intended to be found within the VIDEO_TS folder. (In case you’re curious, the TS stands for title set.) This includes video as well as the audio that accompanies that video.
The AUDIO_TS folder was added as an option after the standard was established. This folder was created for standalone audio files much like the audio tracks on a CD. The idea was that DVDs would replace CDs as audio media. It never caught on but the folder remains, even though it's invariably empty.
Nothing to see here. The always-empty AUDIO_TS folder.
Why? The very earliest DVD players required the AUDIO_TS folder. Without it, the DVD wouldn’t play. Players haven’t required the thing for years, yet disc manufacturers continue to include it on most DVDs—perhaps as a courtesy to those using ancient hardware or because that’s just the way their replication software works.
Now to your implied question: How do you now turn this content into a QuickTime-compatible movie? The answer remains HandBrake. This free utility lets you convert the content within a VIDEO_TS folder into a movie playable on computers and mobile devices. Simply launch HandBrake, click the Source button, navigate to the VIDEO_TS folder, allow HandBrake to look for the main title, and from the application’s sidebar, choose an appropriate output preset.
For more information on the process, see Jonathan Seff’s How to Rip a DVD With HandBrake. |
<filename>engines/experiment/common/types_test.go
package common
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetFieldSource(t *testing.T) {
// header
fieldSrc, err := GetFieldSource("header")
assert.Equal(t, HeaderFieldSource, fieldSrc)
assert.NoError(t, err)
// payload
fieldSrc, err = GetFieldSource("payload")
assert.Equal(t, PayloadFieldSource, fieldSrc)
assert.NoError(t, err)
// unknown
_, err = GetFieldSource("test")
assert.Error(t, err)
}
func TestUnmarshalJSONFieldSource(t *testing.T) {
var fieldSrc FieldSource
// success
err := json.Unmarshal([]byte(`"header"`), &fieldSrc)
assert.Equal(t, HeaderFieldSource, fieldSrc)
assert.NoError(t, err)
// unknown string
err = json.Unmarshal([]byte(`"test"`), &fieldSrc)
assert.Error(t, err)
// invalid data
err = json.Unmarshal([]byte(`0`), &fieldSrc)
assert.Error(t, err)
}
|
Flow diversion and microvascular plug occlusion for the treatment of a complex unruptured basilar/superior cerebellar artery aneurysm: case report. The authors present the unusual case of a complex unruptured basilar artery terminus (BAT) aneurysm in a 42-year-old symptomatic female patient presenting with symptoms of mass effect. Due to the fusiform incorporation of both the BAT and left superior cerebellar artery (SCA) origin, simple surgical or endovascular treatment options were not feasible in this case. A 2-staged (combined deconstructive/reconstructive) procedure was successfully performed: first occluding the left SCA with a Pipeline embolization device (PED) coupled to a microvascular plug (MVP) in the absence of antiplatelet coverage, followed by reconstruction of the BAT by deploying a second PED from the right SCA into the basilar trunk. Six-month follow-up angiography confirmed uneventful aneurysm occlusion. The patient recovered well from her neurological symptoms. This case report illustrates the successful use of a combined staged deconstructive/reconstructive endovascular approach utilizing 2 endoluminal tools, PED and MVP, to reconstruct the BAT and occlude a complex aneurysm. |
Fourier Multiaperture Emission Tomography: Quantum Noise Calculations Expressions for the mean and variance of the images produced by Fourier Multiaperture Emission Tomography are derived. Only quantum noise (counting statistics) is considered. The signal-to-noise ratio achieved by the system for a thin disc-shaped object is computed from these expresions. An example is used to demonstrate some significant features of this single photon emission tomogrphic imaging system. |
/*
Copyright 2016 The Rook Authors. All rights reserved.
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 rbd
import (
"testing"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/client/clientset/versioned/scheme"
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
"github.com/rook/rook/pkg/operator/ceph/config"
cephtest "github.com/rook/rook/pkg/operator/ceph/test"
cephver "github.com/rook/rook/pkg/operator/ceph/version"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
func TestPodSpec(t *testing.T) {
namespace := "ns"
daemonConf := daemonConfig{
DaemonID: "a",
ResourceName: "rook-ceph-rbd-mirror-a",
DataPathMap: config.NewDatalessDaemonDataPathMap("rook-ceph", "/var/lib/rook"),
}
cephCluster := &cephv1.CephCluster{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
Namespace: namespace,
},
Spec: cephv1.ClusterSpec{
CephVersion: cephv1.CephVersionSpec{
Image: "ceph/ceph:v15",
},
},
}
rbdMirror := &cephv1.CephRBDMirror{
ObjectMeta: metav1.ObjectMeta{
Name: "a",
Namespace: namespace,
},
Spec: cephv1.RBDMirroringSpec{
Count: 1,
Resources: v1.ResourceRequirements{
Limits: v1.ResourceList{
v1.ResourceCPU: *resource.NewQuantity(200.0, resource.BinarySI),
v1.ResourceMemory: *resource.NewQuantity(600.0, resource.BinarySI),
},
Requests: v1.ResourceList{
v1.ResourceCPU: *resource.NewQuantity(100.0, resource.BinarySI),
v1.ResourceMemory: *resource.NewQuantity(300.0, resource.BinarySI),
},
},
PriorityClassName: "my-priority-class",
},
TypeMeta: controllerTypeMeta,
}
clusterInfo := &cephclient.ClusterInfo{
CephVersion: cephver.Nautilus,
}
s := scheme.Scheme
object := []runtime.Object{rbdMirror}
cl := fake.NewFakeClientWithScheme(s, object...)
r := &ReconcileCephRBDMirror{client: cl, scheme: s}
r.cephClusterSpec = &cephCluster.Spec
r.clusterInfo = clusterInfo
d, err := r.makeDeployment(&daemonConf, rbdMirror)
assert.NoError(t, err)
assert.Equal(t, "rook-ceph-rbd-mirror-a", d.Name)
// Deployment should have Ceph labels
cephtest.AssertLabelsContainCephRequirements(t, d.ObjectMeta.Labels,
config.RbdMirrorType, "a", AppName, "ns")
podTemplate := cephtest.NewPodTemplateSpecTester(t, &d.Spec.Template)
podTemplate.RunFullSuite(config.RbdMirrorType, "a", AppName, "ns", "ceph/ceph:myceph",
"200", "100", "600", "300", /* resources */
"my-priority-class")
}
|
<gh_stars>0
package engine
import (
"fmt"
"testing"
)
func BenchmarkH(b *testing.B) {
x := 1
y := 1
n := 30
m := 90
pocet := 1500
for i := 0; i < b.N; i++ {
H(x, y, pocet, n, m)
}
b.ReportAllocs()
}
func TestH(t *testing.T) {
tests := []struct {
x, y, n, m, pocet int
w string
}{
{0, 0, 0, 0, 0, "0.0000000000"},
{1, 1, 5, 35, 122, "0.0026306710"},
{1, 2, 5, 35, 122, "0.0000000000"},
{13, 1, 5, 35, 22, "0.0030075188"},
{13, 2, 5, 35, 60, "0.0032467532"},
{13, 3, 5, 35, 39, "0.0025580480"},
{13, 4, 5, 35, 12, "0.0024793388"},
{13, 5, 5, 35, 2, "0.0040404040"},
{35, 1, 5, 35, 43, "0.0000000000"},
}
for i, x := range tests {
r := fmt.Sprintf("%.10f", H(x.x, x.y, x.pocet, x.n, x.m))
if r != x.w {
t.Errorf("Expected: (%s), Have: (%s) (test %d)", x.w, r, i+1)
}
}
}
|
<reponame>tango4j/Continual-Learning-Benchmark
import torch
import torch.nn as nn
import ipdb
class CNN(nn.Module):
def __init__(self, out_dim=10, in_channel=1, img_sz=32, hidden_dim=1000):
super(CNN, self).__init__()
self.in_dim = in_channel*img_sz*img_sz
self.in_channel = in_channel
### CNN part
self.layer_size = 32
self.z_dim = img_sz ** 2
self.layers = {}
# self.layers[0] = nn.Sequential(
# nn.Conv2d(in_channel, self.layer_size, kernel_size=5, stride=1, padding=2),
# nn.ReLU())
# self.layers[1] = nn.Sequential(
# nn.Conv2d(self.layer_size, self.layer_size, kernel_size=5, stride=1, padding=2),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=2, stride=2))
# self.layers[2] = nn.Sequential(
# nn.Conv2d(self.layer_size, self.layer_size, kernel_size=5, stride=1, padding=2),
# nn.ReLU())
# self.layers[3] = nn.Sequential(
# nn.Conv2d(self.layer_size, self.layer_size, kernel_size=5, stride=1, padding=2),
# nn.ReLU(),
# nn.MaxPool2d(kernel_size=2, stride=2))
self.layers[0]= nn.Sequential(
nn.Conv2d(in_channel, self.layer_size, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layers[1] = nn.Sequential(
nn.Conv2d(self.layer_size, self.layer_size, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.embed_layer= nn.Linear(8 * 8 * self.layer_size, self.z_dim)
### Original MLP part
self.linear = nn.Sequential(
nn.Linear(self.z_dim, hidden_dim),
#nn.BatchNorm1d(hidden_dim),
nn.ReLU(inplace=True),
nn.Linear(hidden_dim, hidden_dim),
#nn.BatchNorm1d(hidden_dim),
nn.ReLU(inplace=True),
)
self.last = nn.Linear(hidden_dim, out_dim) # Subject to be replaced dependent on task
# def features(self, x):
# x = self.linear(x.view(-1,self.in_dim))
# return x
def logits(self, x):
x = self.last(x)
return x
def forward(self, x):
for ldx, layer in self.layers.items():
layer.cuda()
x = layer(x)
x = x.view(x.size(0), -1)
x = self.embed_layer(x)
x = self.linear(x)
x = self.logits(x)
return x
class CNN01(nn.Module):
def __init__(self, out_dim=10, in_channel=1, img_sz=32, hidden_dim=1000):
super(CNN, self).__init__()
self.in_dim = in_channel*img_sz*img_sz
self.in_channel = in_channel
### CNN part
self.layer_size = 16
self.z_dim = img_sz ** 2
# ipdb.set_trace()
self.layers = {}
self.layers[0]= nn.Sequential(
nn.Conv2d(in_channel, self.layer_size, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layers[1] = nn.Sequential(
nn.Conv2d(self.layer_size, self.layer_size, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.embed_layer= nn.Linear(8 * 8 * self.layer_size, self.z_dim)
### Original MLP part
self.linear = nn.Sequential(
nn.Linear(self.z_dim, hidden_dim),
#nn.BatchNorm1d(hidden_dim),
nn.ReLU(inplace=True),
nn.Linear(hidden_dim, hidden_dim),
#nn.BatchNorm1d(hidden_dim),
nn.ReLU(inplace=True),
)
self.last = nn.Linear(hidden_dim, out_dim) # Subject to be replaced dependent on task
# def features(self, x):
# x = self.linear(x.view(-1,self.in_dim))
# return x
def logits(self, x):
x = self.last(x)
return x
def forward(self, x):
for ldx, layer in enumerate(self.layers):
x = layer(x)
x = x.view(x.size(0), -1)
x = self.embed_layer(x)
x = self.linear(x)
x = self.logits(x)
return x
def CNN1000_img_sz(pretrained_model_type, in_channel, img_sz):
return CNN(hidden_dim=1000, in_channel=in_channel, img_sz=img_sz)
def CNN1000_MHA():
return CNN_MHA(hidden_dim=1000)
def CNN100():
return CNN(hidden_dim=100)
def CNN400():
return CNN(hidden_dim=400)
def CNN1000():
return CNN(hidden_dim=1000)
def CNN2000():
return CNN(hidden_dim=2000)
def CNN5000():
return CNN(hidden_dim=5000)
|
<filename>code/Model.hpp
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "stb_image.h"
#include <Importer.hpp>
#include <scene.h>
#include <postprocess.h>
#include "Mesh.hpp"
#include "Shader.hpp"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
namespace example
{
//Este metodo se encaga de extraer la textura de un path dado
unsigned int texture_from_file(const char* path, const string& directory);
class Model
{
private:
//Guarda las texturas cargadas para comprobar que no se cargan mas de una vez
vector<Texture> textures_loaded;
vector <Mesh> meshes;
string directory;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
float angle;
public:
// constructor, espera un path a un modelo 3D
Model(string const& path, glm::vec3 position, glm::vec3 rotation, glm::vec3 scale);
//Dibuja el modelo iterando por todas sus mayas
void render(Shader &shader);
void update();
glm::mat4 calculate_model_view_matrix();
private:
//Carga un modelo con ASSIMP de un path y guarda las meshes en el vector de meshes.
void load_model(string const& path);
//Procesa los nodos recursivamente
void process_node(aiNode* node, const aiScene* scene);
Mesh process_mesh(aiMesh* mesh, const aiScene* scene);
vector<Texture> load_material_textures(aiMaterial* mat, aiTextureType type, string typeName);
};
}
|
<reponame>AncientSouls/Babilon<gh_stars>0
import { TExp } from './babilon';
export interface IRestricting {
(exp: TExp, and: TExp, from: TExp): any;
}
export declare const restrictSelect: (exp: any[], restricting: IRestricting) => any[];
export declare const restrict: (exp: any[], restricting: IRestricting) => any[];
|
<reponame>JSalenger/FTCLib
/*
Copyright (c) 2017 <NAME>
All rights reserved.
Derived in part from information in various resources, including FTDI, the
Android Linux implementation, FreeBsc, UsbSerial, and others.
Redistribution and use in source and binary forms, with or without modification,
are permitted (subject to the limitations in the disclaimer below) 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 <NAME> nor the names of his contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
LICENSE. 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.
*/
package org.firstinspires.ftc.robotcore.internal.ftdi;
import android.support.annotation.Nullable;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.robotcore.external.function.Consumer;
import org.firstinspires.ftc.robotcore.internal.collections.ArrayRunQueueLong;
import org.firstinspires.ftc.robotcore.internal.collections.CircularByteBuffer;
import org.firstinspires.ftc.robotcore.internal.collections.EvictingBlockingQueue;
import org.firstinspires.ftc.robotcore.internal.collections.MarkedItemQueue;
import org.firstinspires.ftc.robotcore.internal.hardware.TimeWindow;
import org.firstinspires.ftc.robotcore.internal.system.Assert;
import org.firstinspires.ftc.robotcore.internal.system.Deadline;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Manager of bulk data received from USB
*/
@SuppressWarnings("WeakerAccess")
public class ReadBufferManager extends FtConstants
{
//----------------------------------------------------------------------------------------------
// State
//----------------------------------------------------------------------------------------------
public static final String TAG = "ReadBufferManager";
private final FtDeviceManagerParams mParams;
private Deadline mReadDeadline;
private final int mAvailableInBuffersCapacity;
private final int mAvailableOutBuffersCapacity;
private final ArrayList<BulkPacketBufferIn> mAvailableInBuffers; // finite capacity
private final ArrayList<BulkPacketBufferOut> mAvailableOutBuffers; // finite capacity
private final ArrayList<BulkPacketBufferIn> mReadableBuffers; // infinite capacity
private final EvictingBlockingQueue<BulkPacketBuffer> mRetainedBuffers;
private final int mEndpointMaxPacketSize;
private final FtDevice mDevice;
private final CircularByteBuffer mCircularBuffer;
private final MarkedItemQueue mMarkedItemQueue;
private final ArrayRunQueueLong mTimestamps;
private boolean mReadBulkInDataInterruptRequested;
private volatile Thread mReadBulkInDataThread;
private volatile boolean mProcessBulkInDataCallInFlight;
private boolean mIsOpen;
private boolean mDebugRetainBuffers;
//----------------------------------------------------------------------------------------------
// Construction
//----------------------------------------------------------------------------------------------
public ReadBufferManager(FtDevice dev, boolean debugRetainBuffers) throws IOException, InterruptedException
{
this.mIsOpen = true;
this.mDevice = dev;
this.mParams = this.mDevice.getDriverParameters();
this.mReadDeadline = new Deadline(this.mParams.getBulkInReadTimeout(), TimeUnit.MILLISECONDS);
this.mEndpointMaxPacketSize = this.mDevice.getEndpointMaxPacketSize();
this.mCircularBuffer = new CircularByteBuffer(this.mEndpointMaxPacketSize * 5 /* a guess */, this.mParams.getMaxReadBufferSize());
this.mMarkedItemQueue = new MarkedItemQueue();
this.mTimestamps = new ArrayRunQueueLong();
this.mAvailableInBuffersCapacity = this.mParams.getPacketBufferCacheSize();
this.mAvailableOutBuffersCapacity = Math.min(this.mAvailableInBuffersCapacity,mParams.getRetainedBufferCapacity());
this.mAvailableInBuffers = new ArrayList<BulkPacketBufferIn>();
this.mAvailableOutBuffers = new ArrayList<BulkPacketBufferOut>();
this.mReadableBuffers = new ArrayList<BulkPacketBufferIn>(); // need effectively infinite capacity to be able to keep servicing USB w/o losing data
this.mRetainedBuffers = new EvictingBlockingQueue<BulkPacketBuffer>(new ArrayBlockingQueue<BulkPacketBuffer>(mParams.getRetainedBufferCapacity())); // don't need the blocking, but do need the eviction action
this.mRetainedBuffers.setEvictAction(new RecentPacketEvicted());
this.mReadBulkInDataThread = null;
this.mReadBulkInDataInterruptRequested = false;
this.mProcessBulkInDataCallInFlight = false;
this.mDebugRetainBuffers = debugRetainBuffers;
verifyInvariants("ctor");
}
//----------------------------------------------------------------------------------------------
// Accessing
//----------------------------------------------------------------------------------------------
public boolean isReadBufferFull()
{
synchronized (mCircularBuffer)
{
return mCircularBuffer.remainingCapacity() == 0;
}
}
public int getReadBufferSize()
{
synchronized (mCircularBuffer)
{
return mCircularBuffer.size();
}
}
public FtDeviceManagerParams getParams()
{
return this.mParams;
}
//----------------------------------------------------------------------------------------------
// Buffer management
//----------------------------------------------------------------------------------------------
// For sufficiently small buffers, we use a fixed allocation size so as to facilitate
// instance reuse and reduce pressure on the GC
public BulkPacketBufferOut newOutputBuffer(byte[] data, int ibFirst, int cbToWrite)
{
BulkPacketBufferOut result = null;
//
if (cbToWrite <= mEndpointMaxPacketSize)
{
synchronized (mAvailableOutBuffers)
{
if (!mAvailableOutBuffers.isEmpty())
{
result = mAvailableOutBuffers.remove(mAvailableOutBuffers.size()-1); // nit: LIFO for better cache locality
}
}
if (result == null)
{
result = new BulkPacketBufferOut(mEndpointMaxPacketSize);
}
}
else
result = new BulkPacketBufferOut(cbToWrite);
//
result.copyFrom(data, ibFirst, cbToWrite);
return result;
}
private void offerAvailableBufferOut(BulkPacketBufferOut packetBuffer)
{
if (packetBuffer.capacity() == mEndpointMaxPacketSize)
{
synchronized (mAvailableOutBuffers)
{
// keep a few around around so as to reduce GC pressure
if (mAvailableOutBuffers.size() < mAvailableOutBuffersCapacity)
{
mAvailableOutBuffers.add(packetBuffer);
}
}
}
}
//--------------
public BulkPacketBufferIn acquireWritableInputBuffer()
{
BulkPacketBufferIn result = null;
synchronized (mAvailableInBuffers)
{
if (!mAvailableInBuffers.isEmpty())
{
result = mAvailableInBuffers.remove(mAvailableInBuffers.size()-1); // nit: LIFO for better cache locality
}
}
if (result == null)
{
/**
* The issue of how big of packet buffer to use is surprisingly complicated. The best
* treatise on this so far located is the FTDI application note entitled:
*
* "AN232B-04 Data Throughput, Latency and Handshaking"
*
* To cut to the chase: the best trade-off is to use the endpoint packet size, which is
* usually (perhaps always?) 64 bytes. If one uses larger than this, if the data comes
* in at just the most inopportune rate, you can wait multiple frames to get your data,
* increasing latency perhaps significantly (see Section 3.3, which illustrates how a
* hypothetical 4KB buffer at a 38.75kbaud could take the full 1.06 before the chip
* returned data to the driver).
*
* Note that FTDI chips seem to have an internal receive buffer of 256 or 512 bytes
* depending on the model.
*/
result = new BulkPacketBufferIn(mEndpointMaxPacketSize);
}
return result;
}
public void releaseReadableBuffer(BulkPacketBufferIn packetBuffer)
{
synchronized (mReadableBuffers)
{
mReadableBuffers.add(packetBuffer); // adds at end
mReadableBuffers.notifyAll();
}
}
public BulkPacketBufferIn acquireReadableInputBuffer() throws InterruptedException
{
for (;;)
{
synchronized (mReadableBuffers)
{
if (!mReadableBuffers.isEmpty())
{
return mReadableBuffers.remove(0);
}
mReadableBuffers.wait();
}
}
}
public void releaseWritableInputBuffer(BulkPacketBufferIn packetBuffer)
{
// Don't retain buffers that have no user data at all
if (packetBuffer.getCurrentLength() <= MODEM_STATUS_SIZE || !retainRecentBuffer(packetBuffer))
{
offerAvailableBufferIn(packetBuffer);
}
}
private void offerAvailableBufferIn(BulkPacketBufferIn packetBuffer)
{
synchronized (mAvailableInBuffers)
{
// keep a few around around so as to reduce GC pressure
if (mAvailableInBuffers.size() < mAvailableInBuffersCapacity)
{
mAvailableInBuffers.add(packetBuffer);
}
}
}
private class RecentPacketEvicted implements Consumer<BulkPacketBuffer>
{
@Override public void accept(BulkPacketBuffer bulkPacketBuffer)
{
if (bulkPacketBuffer instanceof BulkPacketBufferIn)
{
offerAvailableBufferIn((BulkPacketBufferIn)bulkPacketBuffer);
}
else
{
offerAvailableBufferOut((BulkPacketBufferOut)bulkPacketBuffer);
}
}
}
public void setDebugRetainBuffers(boolean retainRecentBuffers)
{
synchronized (mRetainedBuffers)
{
mDebugRetainBuffers = retainRecentBuffers;
if (!mDebugRetainBuffers)
{
mRetainedBuffers.clear();
}
}
}
public boolean getDebugRetainBuffers()
{
return mDebugRetainBuffers;
}
public boolean retainRecentBuffer(BulkPacketBuffer buffer)
{
synchronized (mRetainedBuffers)
{
if (mDebugRetainBuffers)
{
mRetainedBuffers.add(buffer);
// RobotLog.logBytes(TAG, "retained", buffer.arrayOffset(), buffer.getCurrentLength(), buffer.array());
return true;
}
}
return false;
}
public void logRetainedBuffers(long nsOrigin, long nsTimerExpire, String tag, String format, Object...args)
{
synchronized (mRetainedBuffers)
{
RobotLog.vv(tag, format, args);
//
BulkPacketBuffer firstBuffer = null;
TimeUnit timeUnitReport = TimeUnit.NANOSECONDS;
double timeUnitScale = 1.0 / ElapsedTime.MILLIS_IN_NANO;
for (;;)
{
BulkPacketBuffer buffer = mRetainedBuffers.poll();
if (buffer == null)
break;
if (firstBuffer == null)
{
firstBuffer = buffer;
if (nsOrigin == 0)
{
nsOrigin = firstBuffer.getTimestamp(TimeUnit.NANOSECONDS);
}
}
double ns = buffer.getTimestamp(timeUnitReport) - timeUnitReport.convert(nsOrigin, TimeUnit.NANOSECONDS);
String bufferCaption = String.format("%s (ts=%.3f)", buffer instanceof BulkPacketBufferIn ? "read " : "write", ns * timeUnitScale);
RobotLog.logBytes(tag, bufferCaption, buffer.array(), buffer.arrayOffset(), buffer.getCurrentLength());
}
if (nsTimerExpire > 0)
{
RobotLog.vv(tag, "timer expired (ts=%.3f)", timeUnitReport.convert(nsTimerExpire - nsOrigin, TimeUnit.NANOSECONDS) * timeUnitScale);
}
}
}
//----------------------------------------------------------------------------------------------
// I/O
//----------------------------------------------------------------------------------------------
/** Called on {@link ReadBufferWorker} thread */
public void processBulkInData(BulkPacketBufferIn packetBuffer) throws FtDeviceIOException, InterruptedException
{
if (isOpen() && packetBuffer.getCurrentLength() > 0)
{
mProcessBulkInDataCallInFlight = true;
try {
final int cbBuffer = packetBuffer.getCurrentLength();
if (cbBuffer < MODEM_STATUS_SIZE)
{
return;
}
// Wait until we have enough room in the buffer to write the incoming data
// TODO: reexamine policy about when to toss data: where does the back pressure go?
synchronized (mCircularBuffer)
{
for (;;)
{
int cbFree = mCircularBuffer.remainingCapacity();
int cbNeeded = cbBuffer - MODEM_STATUS_SIZE;
if (cbNeeded <= cbFree)
break;
// Wait until the state of the buffer changes
mCircularBuffer.wait();
// Get out of Dodge if things have closed while we were waiting
if (!isOpen()) return;
}
}
this.extractReadData(packetBuffer);
}
finally
{
mProcessBulkInDataCallInFlight = false;
}
}
}
/** called on {@link ReadBufferWorker} thread */
private void extractReadData(BulkPacketBufferIn packetBuffer) throws InterruptedException
{
final int cbBuffer = packetBuffer.getCurrentLength();
if (cbBuffer > 0)
{
verifyInvariants("->extractReadData");
try {
short signalEvents = 0;
short signalLineEvents = 0;
boolean signalRxChar = false;
final int packetCount = cbBuffer / this.mEndpointMaxPacketSize + (cbBuffer % this.mEndpointMaxPacketSize > 0 ? 1 : 0);
// RobotLog.dd(TAG, "packetCount=%d cb=%d", packetCount, cbBuffer);
ByteBuffer byteBuffer = packetBuffer.getByteBuffer();
int cbExtracted = 0;
for (int iPacket = 0; iPacket < packetCount; ++iPacket)
{
int ibFirst;
int ibMax;
if (iPacket == packetCount - 1)
{
// Last packet : use modem status at start of packet
ibFirst = iPacket * this.mEndpointMaxPacketSize;
ibMax = cbBuffer;
setBufferBounds(byteBuffer, ibFirst, ibMax);
//
byte b0 = byteBuffer.get(); // Assert.assertTrue(b0 == 0x01, "b0==0x%02x", b0);
signalEvents = (short) (this.mDevice.mDeviceInfo.modemStatus ^ (short) (b0 & 0xF0));
this.mDevice.mDeviceInfo.modemStatus = (short) (b0 & 0xF0); // this sign extends, which probably isn't what's desired
//
byte b1 = byteBuffer.get(); // Assert.assertTrue(b1==0x60 || b1==0x00, "b1==0x%02x", b1);
this.mDevice.mDeviceInfo.lineStatus = (short) (b1 & 0xFF); // this sign extends, which probably isn't what's desired
//
ibFirst += MODEM_STATUS_SIZE;
//
if (byteBuffer.hasRemaining())
{
signalLineEvents = (short) (this.mDevice.mDeviceInfo.lineStatus & 0x1E);
}
else
{
signalLineEvents = 0;
}
}
else
{
// Not the last packet : ignore modem status at start of packet
ibFirst = iPacket * this.mEndpointMaxPacketSize + MODEM_STATUS_SIZE;
ibMax = (iPacket + 1) * this.mEndpointMaxPacketSize;
setBufferBounds(byteBuffer, ibFirst, ibMax);
}
Assert.assertTrue(byteBuffer.remaining() == ibMax - ibFirst);
int cbPacket = ibMax - ibFirst;
if (cbPacket > 0)
{
synchronized (mCircularBuffer)
{
// Remember the bytes in our linear array of bytes
cbExtracted += mCircularBuffer.write(byteBuffer);
// The first of those was at the start a packet (ie: followed modem status
// bytes) while the remainder were not
mMarkedItemQueue.addMarkedItem();
mMarkedItemQueue.addUnmarkedItems(cbPacket-1);
// Remember when these packets came in
mTimestamps.addLast(packetBuffer.getTimestamp(TimeUnit.NANOSECONDS), cbPacket);
}
}
}
if (cbExtracted > 0)
{
signalRxChar = true;
wakeReadBulkInData();
}
byteBuffer.clear();
this.processEventChars(signalRxChar, signalEvents, signalLineEvents);
}
finally
{
verifyInvariants("<-extractReadData");
}
}
}
private void setBufferBounds(ByteBuffer buffer, int ibFirst, int ibMax)
{
buffer.clear(); // don't assume positions: position <- 0, limit <- capacity
buffer.position(ibFirst);
buffer.limit(ibMax);
}
private void verifyInvariants(String context)
{
/*synchronized (mCircularBuffer)
{
int cbData = mCircularBuffer.size();
int cMarked = mMarkedItemQueue.size();
int cTimestamp = mTimestamps.size();
Assert.assertTrue(cbData == cMarked);
Assert.assertTrue(cbData == cTimestamp);
}*/
}
/**
* Attempt to read cbToRead bytes from the device, subject to a timeout
*
* @param data the buffer into which the data is to be placed, starting at the beginning
* @param cbToRead the number of bytes to read
* @param msTimeout the number of milliseconds to wait for the result
* @param timeWindow optional place into which to record the timestamps that cover the duration of the read data
* @return the number of bytes read (zero means the timeout is reached w/o returning the data
* unless the number of bytes to read was itself zero)
* FT_Device.RC_DEVICE_CLOSED : the device was closed
* @throws InterruptedException
*/
public int readBulkInData(final byte[] data, final int ibFirst, final int cbToRead, long msTimeout, @Nullable TimeWindow timeWindow) throws InterruptedException
{
if (mReadBulkInDataInterruptRequested)
{
throw new InterruptedException("interrupted in readBulkInData()");
}
else if (cbToRead > 0 && isOpen())
{
mReadBulkInDataThread = Thread.currentThread();
try {
verifyInvariants("->readBulkInData");
final Deadline readDeadline = getReadDeadline(msTimeout);
// Loop until we get the amount of data we came for
while (isOpen())
{
// Stop if we've timed out
if (readDeadline.hasExpired())
{
return 0;
}
// If we've been poked, then poke our callers
if (Thread.interrupted())
{
throw new InterruptedException("interrupted reading USB data");
}
// Is there enough data there for us to read?
synchronized (mCircularBuffer)
{
if (mCircularBuffer.size() >= cbToRead)
{
// Yes, read it
int cbRead = mCircularBuffer.read(data, ibFirst, cbToRead);
if (cbRead > 0)
{
mMarkedItemQueue.removeItems(cbRead);
//
if (timeWindow != null)
{
timeWindow.setNanosecondsFirst(mTimestamps.getFirst());
timeWindow.setNanosecondsLast(mTimestamps.removeFirstCount(cbRead));
}
else
{
mTimestamps.removeFirstCount(cbRead); // just discard
}
//
mCircularBuffer.notifyAll();
}
return cbRead;
}
// Not enough data. Wait for more data to come in. In art, the wait system
// complains to the log if you use a non-integer wait interval, so we cap.
long msRemaining = Math.min(readDeadline.timeRemaining(TimeUnit.MILLISECONDS), Integer.MAX_VALUE);
if (msRemaining > 0)
{
mCircularBuffer.wait(msRemaining);
}
}
}
// The device was closed while we were waiting
return FtDevice.RC_DEVICE_CLOSED;
}
finally
{
verifyInvariants("<-readBulkInData");
mReadBulkInDataThread = null;
}
}
else
{
return 0;
}
}
/** We cache in member variable to as to avoid creating oodles of short-lived objects */
protected Deadline getReadDeadline(long msTimeout)
{
if (msTimeout == 0)
{
msTimeout = this.mParams.getBulkInReadTimeout();
}
if (mReadDeadline.getDuration(TimeUnit.MILLISECONDS) == msTimeout)
{
mReadDeadline.reset();
}
else
{
mReadDeadline = new Deadline(msTimeout, TimeUnit.MILLISECONDS);
}
return mReadDeadline;
}
public boolean mightBeAtUsbPacketStart()
{
// If it's empty, then the next data will be the start of a packet, by definition
return mMarkedItemQueue.isAtMarkedItem() || mMarkedItemQueue.isEmpty();
}
public void skipToLikelyUsbPacketStart()
{
synchronized (mCircularBuffer)
{
int cbSkip = mMarkedItemQueue.removeUpToNextMarkedItemOrEnd();
if (cbSkip > 0)
{
mTimestamps.removeFirstCount(cbSkip);
mCircularBuffer.skip(cbSkip);
mCircularBuffer.notifyAll();
}
}
}
private boolean isOpen()
{
return mIsOpen && FtDevice.isOpen(this.mDevice);
}
private void wakeReadBulkInData()
{
synchronized (this.mCircularBuffer)
{
this.mCircularBuffer.notifyAll();
}
}
private boolean extantReadBulkInDataCall()
{
return mReadBulkInDataThread != null;
}
public void requestReadInterrupt(boolean requested)
{
if (requested)
{
mReadBulkInDataInterruptRequested = true;
Thread thread = mReadBulkInDataThread;
if (thread != null)
{
thread.interrupt();
}
}
else
mReadBulkInDataInterruptRequested = false;
}
private void spinWaitNoReadBulkInData()
{
for (;;)
{
if (!extantReadBulkInDataCall())
{
return;
}
Thread.yield();
}
}
private boolean extantProcessBulkInData()
{
return mProcessBulkInDataCallInFlight;
}
public void purgeInputData()
{
synchronized (mCircularBuffer)
{
synchronized (mReadableBuffers)
{
mReadableBuffers.clear();
}
mCircularBuffer.clear();
mMarkedItemQueue.clear();
mTimestamps.clear();
}
}
/**
* The original implementation of processEventChars used an in-process broadcast as notification
* mechanism. That required a whole new external library (implementing LocalBroadcastManager)
* which we'd very much not like to have to link in here. And since we presently don't need such
* a notification mechanism, we'll do without it for now. Recommendation: if we ever DO need
* such a thing, use a better mechanism :-).
*
* From the FTDI D2XX Programmer's Guide:
*
* "The least significant byte of the lpdwModemStatus value holds the modem status. On Windows and
* Windows CE, the line status is held in the second least significant byte of the lpdwModemStatus value.
*
* The modem status is bit-mapped as follows: Clear To Send (CTS) = 0x10, Data Set Ready (DSR) = 0x20,
* Ring Indicator (RI) = 0x40, Data Carrier Detect (DCD) = 0x80.
*
* The line status is bit-mapped as follows: Overrun Error (OE) = 0x02, Parity Error (PE) = 0x04,
* Framing Error (FE) = 0x08, Break Interrupt (BI) = 0x10."
*/
public int processEventChars(boolean fRxChar, short sEvents, short slEvents) throws InterruptedException
{
return 0;
}
void close()
{
if (mIsOpen)
{
// Set a flag so that anyone who notices will get out of the way
mIsOpen = false;
// Caller should ensure that the ProcessRequestWorker is stopped before closing us here
Assert.assertFalse(extantProcessBulkInData());
// If there's any reader out there, wake them up and wait until they leave
wakeReadBulkInData();
spinWaitNoReadBulkInData();
}
}
}
|
/* GStaticProxyResolver tests
*
* Copyright 2011, 2013 Red Hat, Inc.
*
* This 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.
*
* This 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 this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
#include <gio/gio.h>
static void
test_uris (void)
{
GProxyResolver *resolver;
gchar *ignore_hosts[2] = { "127.0.0.1", NULL };
gchar **proxies;
GError *error = NULL;
resolver = g_simple_proxy_resolver_new ("default://", ignore_hosts);
g_simple_proxy_resolver_set_uri_proxy (G_SIMPLE_PROXY_RESOLVER (resolver),
"http", "http://proxy.example.com");
g_simple_proxy_resolver_set_uri_proxy (G_SIMPLE_PROXY_RESOLVER (resolver),
"ftp", "ftp://proxy.example.com");
proxies = g_proxy_resolver_lookup (resolver, "http://one.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "http://proxy.example.com");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "HTTP://uppercase.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "http://proxy.example.com");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "htt://missing-letter.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "default://");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "https://extra-letter.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "default://");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "ftp://five.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "ftp://proxy.example.com");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "http://127.0.0.1/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "direct://");
g_strfreev (proxies);
g_object_unref (resolver);
}
static void
test_socks (void)
{
GProxyResolver *resolver;
gchar *ignore_hosts[2] = { "127.0.0.1", NULL };
gchar **proxies;
GError *error = NULL;
resolver = g_simple_proxy_resolver_new ("socks://proxy.example.com", ignore_hosts);
proxies = g_proxy_resolver_lookup (resolver, "http://one.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 3);
g_assert_cmpstr (proxies[0], ==, "socks5://proxy.example.com");
g_assert_cmpstr (proxies[1], ==, "socks4a://proxy.example.com");
g_assert_cmpstr (proxies[2], ==, "socks4://proxy.example.com");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "http://127.0.0.1/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "direct://");
g_strfreev (proxies);
g_object_unref (resolver);
resolver = g_simple_proxy_resolver_new ("default-proxy://", ignore_hosts);
g_simple_proxy_resolver_set_uri_proxy (G_SIMPLE_PROXY_RESOLVER (resolver),
"http", "socks://proxy.example.com");
proxies = g_proxy_resolver_lookup (resolver, "http://one.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 3);
g_assert_cmpstr (proxies[0], ==, "socks5://proxy.example.com");
g_assert_cmpstr (proxies[1], ==, "socks4a://proxy.example.com");
g_assert_cmpstr (proxies[2], ==, "socks4://proxy.example.com");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "ftp://two.example.com/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "default-proxy://");
g_strfreev (proxies);
proxies = g_proxy_resolver_lookup (resolver, "http://127.0.0.1/",
NULL, &error);
g_assert_no_error (error);
g_assert_cmpint (g_strv_length (proxies), ==, 1);
g_assert_cmpstr (proxies[0], ==, "direct://");
g_strfreev (proxies);
g_object_unref (resolver);
}
static const char *ignore_hosts[] = {
".bbb.xx",
"*.ccc.xx",
"ddd.xx",
"*.eee.xx:8000",
"127.0.0.0/24",
"10.0.0.1:8000",
"::1",
"fe80::/10",
NULL
};
static const struct {
const char *uri;
const char *proxy;
} ignore_tests[] = {
{ "http://aaa.xx/", "http://localhost:8080" },
{ "http://aaa.xx:8000/", "http://localhost:8080" },
{ "http://www.aaa.xx/", "http://localhost:8080" },
{ "http://www.aaa.xx:8000/", "http://localhost:8080" },
{ "https://aaa.xx/", "http://localhost:8080" },
{ "http://bbb.xx/", "direct://" },
{ "http://www.bbb.xx/", "direct://" },
{ "http://bbb.xx:8000/", "direct://" },
{ "http://www.bbb.xx:8000/", "direct://" },
{ "https://bbb.xx/", "direct://" },
{ "http://nobbb.xx/", "http://localhost:8080" },
{ "http://www.nobbb.xx/", "http://localhost:8080" },
{ "http://nobbb.xx:8000/", "http://localhost:8080" },
{ "http://www.nobbb.xx:8000/", "http://localhost:8080" },
{ "https://nobbb.xx/", "http://localhost:8080" },
{ "http://ccc.xx/", "direct://" },
{ "http://www.ccc.xx/", "direct://" },
{ "http://ccc.xx:8000/", "direct://" },
{ "http://www.ccc.xx:8000/", "direct://" },
{ "https://ccc.xx/", "direct://" },
{ "http://ddd.xx/", "direct://" },
{ "http://ddd.xx:8000/", "direct://" },
{ "http://www.ddd.xx/", "direct://" },
{ "http://www.ddd.xx:8000/", "direct://" },
{ "https://ddd.xx/", "direct://" },
{ "http://eee.xx/", "http://localhost:8080" },
{ "http://eee.xx:8000/", "direct://" },
{ "http://www.eee.xx/", "http://localhost:8080" },
{ "http://www.eee.xx:8000/", "direct://" },
{ "https://eee.xx/", "http://localhost:8080" },
{ "http://1.2.3.4/", "http://localhost:8080" },
{ "http://127.0.0.1/", "direct://" },
{ "http://127.0.0.2/", "direct://" },
{ "http://127.0.0.255/", "direct://" },
{ "http://127.0.1.0/", "http://localhost:8080" },
{ "http://10.0.0.1/", "http://localhost:8080" },
{ "http://10.0.0.1:8000/", "direct://" },
{ "http://[::1]/", "direct://" },
{ "http://[::1]:80/", "direct://" },
{ "http://[::1:1]/", "http://localhost:8080" },
{ "http://[::1:1]:80/", "http://localhost:8080" },
{ "http://[fe80::1]/", "direct://" },
{ "http://[fe80::1]:80/", "direct://" },
{ "http://[fec0::1]/", "http://localhost:8080" },
{ "http://[fec0::1]:80/", "http://localhost:8080" }
};
static const int n_ignore_tests = G_N_ELEMENTS (ignore_tests);
static void
test_ignore (void)
{
GProxyResolver *resolver;
GError *error = NULL;
char **proxies;
int i;
resolver = g_simple_proxy_resolver_new ("http://localhost:8080",
(char **)ignore_hosts);
for (i = 0; i < n_ignore_tests; i++)
{
proxies = g_proxy_resolver_lookup (resolver, ignore_tests[i].uri,
NULL, &error);
g_assert_no_error (error);
g_assert_cmpstr (proxies[0], ==, ignore_tests[i].proxy);
g_strfreev (proxies);
}
g_object_unref (resolver);
}
int
main (int argc,
char *argv[])
{
g_test_init (&argc, &argv, NULL);
g_test_add_func ("/static-proxy/uri", test_uris);
g_test_add_func ("/static-proxy/socks", test_socks);
g_test_add_func ("/static-proxy/ignore", test_ignore);
return g_test_run();
}
|
/*
* 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.
*/
/* tslint:disable:no-unused-variable */
/* tslint:disable:no-unused-expression */
/* tslint:disable:no-var-requires */
/* tslint:disable:max-classes-per-file */
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { BrowserModule } from '@angular/platform-browser';
import { Component, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ViewTransactionComponent } from './view-transaction.component';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ClientService } from '../../services/client.service';
import {
BusinessNetworkDefinition,
Serializer,
Factory,
Resource,
ModelFile,
Introspector
} from 'composer-common';
import { BusinessNetworkConnection } from 'composer-client';
import * as chai from 'chai';
import * as sinon from 'sinon';
let should = chai.should();
@Component({
selector: 'codemirror',
template: ''
})
class MockCodeMirrorComponent {
@Input() config: any;
}
describe('ViewTransactionComponent', () => {
let component: ViewTransactionComponent;
let fixture: ComponentFixture<ViewTransactionComponent>;
let mockNgbActiveModal;
let mockClientService;
let mockTransaction;
let mockBusinessNetwork;
let mockBusinessNetworkConnection;
let mockSerializer;
let mockIntrospector;
let mockFactory;
let mockEvent1;
let mockEvent2;
let sandbox;
beforeEach(async(() => {
sandbox = sinon.sandbox.create();
mockNgbActiveModal = sinon.createStubInstance(NgbActiveModal);
mockClientService = sinon.createStubInstance(ClientService);
mockBusinessNetwork = sinon.createStubInstance(BusinessNetworkDefinition);
mockBusinessNetworkConnection = sinon.createStubInstance(BusinessNetworkConnection);
mockSerializer = sinon.createStubInstance(Serializer);
mockIntrospector = sinon.createStubInstance(Introspector);
mockFactory = sinon.createStubInstance(Factory);
mockClientService.getBusinessNetworkConnection.returns(mockBusinessNetworkConnection);
mockClientService.getBusinessNetwork.returns(mockBusinessNetwork);
mockBusinessNetwork.getSerializer.returns(mockSerializer);
mockBusinessNetwork.getFactory.returns(mockFactory);
mockBusinessNetwork.getIntrospector.returns(mockIntrospector);
mockSerializer.toJSON.returns({
$class: 'mock.class',
timestamp: 'now',
transactionId: 'transaction'
});
mockNgbActiveModal.close = sandbox.stub();
TestBed.configureTestingModule({
imports: [
FormsModule,
BrowserModule
],
declarations: [
ViewTransactionComponent,
MockCodeMirrorComponent
],
providers: [
{provide: ClientService, useValue: mockClientService},
{provide: NgbActiveModal, useValue: mockNgbActiveModal}
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ViewTransactionComponent);
component = fixture.componentInstance;
mockEvent1 = sinon.createStubInstance(Resource);
mockEvent1.getIdentifier.returns('event1');
mockEvent2 = sinon.createStubInstance(Resource);
mockEvent2.getIdentifier.returns('event2');
mockTransaction = sinon.createStubInstance(Resource);
mockTransaction.getIdentifier.returns('transaction');
mockSerializer.toJSON.onFirstCall().returns({
$class: 'mock.class',
timestamp: 'now',
transactionId: 'transaction'
});
mockSerializer.toJSON.onSecondCall().returns({
$class: 'mock.event',
timestamp: 'now',
eventId: 'event1'
});
mockSerializer.toJSON.onThirdCall().returns({
$class: 'mock.event',
timestamp: 'now',
eventId: 'event2'
});
});
afterEach(() => {
sandbox.restore();
});
describe('#CodeMirror', () => {
it('should call the correct functions', () => {
let cm = {
foldCode: sandbox.stub(),
getCursor: sandbox.stub()
};
component['codeConfig'].extraKeys['Ctrl-Q'](cm);
cm.foldCode.should.be.called;
cm.getCursor.should.be.called;
});
});
describe('#ngOnInit', () => {
it('should create arrays of Resources, JSON and strings', () => {
component['transaction'] = mockTransaction;
component['events'] = [mockEvent1, mockEvent2];
component.ngOnInit();
mockBusinessNetwork.getSerializer.should.be.called;
mockSerializer.toJSON.should.be.calledWith(mockTransaction);
component.transactionString.should.equal(JSON.stringify({
$class: 'mock.class',
timestamp: 'now',
transactionId: 'transaction'
}, null, ' '));
component.events.should.deep.equal([mockEvent1, mockEvent2]);
mockSerializer.toJSON.should.be.calledWith(mockEvent1);
mockSerializer.toJSON.should.be.calledWith(mockEvent2);
component.eventObjects.should.deep.equal([
{$class: 'mock.event', timestamp: 'now', eventId: 'event1'},
{$class: 'mock.event', timestamp: 'now', eventId: 'event2'}
]);
component.eventStrings.should.deep.equal([
JSON.stringify({$class: 'mock.event', timestamp: 'now', eventId: 'event1'}, null, ' '),
JSON.stringify({$class: 'mock.event', timestamp: 'now', eventId: 'event2'}, null, ' ')
]);
});
it('should handle no events being passed to the modal', () => {
component['transaction'] = mockTransaction;
component.ngOnInit();
mockBusinessNetwork.getSerializer.should.be.called;
mockSerializer.toJSON.should.be.calledWith(mockTransaction);
component.transactionString.should.equal(JSON.stringify({
$class: 'mock.class',
timestamp: 'now',
transactionId: 'transaction'
}, null, ' '));
component.events.should.deep.equal([]);
component.eventObjects.should.deep.equal([]);
component.eventStrings.should.deep.equal([]);
});
});
describe('#selectEvent', () => {
it('should select an event by adding it to the list', () => {
let ev = sinon.createStubInstance(Resource);
component.selectEvent(ev, 0);
component.displayEvents[0].should.deep.equal({event: ev, index: 0});
});
it('should delete the event index in the list if it exists', () => {
let ev = sinon.createStubInstance(Resource);
component.displayEvents = [ev];
component.selectEvent(ev, 0);
component.displayEvents.should.deep.equal([]);
});
});
describe('#showEvents', () => {
it('should change the panel on show', () => {
component.isEvent = false;
component.showEvents();
component.isEvent.should.be.true;
});
});
describe('#showTransaction', () => {
it('should change the panel on show', () => {
component.isEvent = true;
component.showTransaction();
component.isEvent.should.be.false;
});
});
describe('#showEvent', () => {
it('should return true', () => {
component.displayEvents = {0: 'event'};
component.showEvent(0).should.be.true;
});
it('should return false', () => {
component.displayEvents = {};
component.showEvent(0).should.be.false;
});
});
});
|
TARDBP mutation associated with semantic variant primary progressive aphasia, case report and review of the literature ABSTRACT Semantic variant primary progressive aphasia (svPPA) is a clinical syndrome included in the frontotemporal dementia (FTD) spectrum. Unlike other forms of FTD, it is sporadic in the majority of cases and not commonly associated with motor neuron disease (MND). We describe a case of svPPA associated with MND in the same family, due to a mutation of the transactive response DNA binding protein (TARDBP) gene, and review the literature. |
<reponame>wonderful666/marx-10.1.0
#include <linux/ktime.h>
#include <linux/timekeeping.h>
#include <net/tcp.h>
#include <linux/sysctl.h>
#include <hwnet/ipv4/wifi_delayst.h>
#include <trace/events/skb.h>
#include <linux/cryptohash.h>
#include <linux/inet.h>
#include <hwnet/chr/wbc_hw_hook.h>
u8 delayst_switch = 1;
/*for sysctl command,statistic configuration*/
char tcp_delay_filter[DELAY_FILTER_NAME_MAX] = {0};
/*store statistics results*/
DELAY_STAT_T Delay_S = {{{0},{0},{0},{0},{0}},{0},{0}};
DELAY_STAT_T RcvDelay_S = {{{0},{0},{0},{0},{0}},{0},{0}};
DP_SETTINGS_T Settings = {
.dp_mode = mode_stat,
.print_interval = 1000,
.android_uid = UID_MATCH_ALL,
.dp_switch = flag_auto,
};
struct static_key wifi_delay_statistic_key __read_mostly = STATIC_KEY_INIT_FALSE;
/*operatios for delayst_skb_cb for skb->cb*/
skbdirect_enum skbprobe_get_direct(struct sk_buff *pskb)
{
return DELAYST_SKB_CB(pskb)->pdirect;
}
void skbprobe_set_direct(struct sk_buff *pskb, skbdirect_enum direct)
{
DELAYST_SKB_CB(pskb)->pdirect = direct;
}
skbtype_enum skbprobe_get_proto(struct sk_buff *pskb)
{
return DELAYST_SKB_CB(pskb)->pproto;
}
void skbprobe_set_proto(struct sk_buff *pskb, skbtype_enum proto)
{
DELAYST_SKB_CB(pskb)->pproto = proto;
}
ktime_t skbprobe_get_skbtime(struct sk_buff *pskb,int time_index)
{
return (DELAYST_SKB_CB(pskb)->ptime[time_index]);
}
__u32 skbprobe_get_skbuid(struct sk_buff *pskb)
{
return (DELAYST_SKB_CB(pskb)->android_uid);
}
void skbprobe_copy_delayskbcb(DELAYSKB_CB_T *delayskbcb,struct sk_buff *pskb)
{
if (IS_DIRECT(pskb, TP_SKB_DIRECT_SND)) {
delayskbcb->android_uid = skbprobe_get_skbuid(pskb);
delayskbcb->ptime[TP_SKB_SEND] = skbprobe_get_skbtime(pskb,TP_SKB_SEND);
delayskbcb->ptime[TP_SKB_IP] = skbprobe_get_skbtime(pskb,TP_SKB_IP);
delayskbcb->ptime[TP_SKB_HMAC_XMIT] = skbprobe_get_skbtime(pskb,TP_SKB_HMAC_XMIT);
delayskbcb->ptime[TP_SKB_HMAC_TX] = skbprobe_get_skbtime(pskb,TP_SKB_HMAC_TX);
delayskbcb->ptime[TP_SKB_DMAC] = skbprobe_get_skbtime(pskb,TP_SKB_DMAC);
} else {
delayskbcb->android_uid = skbprobe_get_skbuid(pskb);
delayskbcb->ptime[TP_SKB_DMAC] = skbprobe_get_skbtime(pskb,TP_SKB_DMAC);
delayskbcb->ptime[TP_SKB_HMAC_UPLOAD] = skbprobe_get_skbtime(pskb,TP_SKB_HMAC_UPLOAD);
delayskbcb->ptime[TP_SKB_IP] = skbprobe_get_skbtime(pskb,TP_SKB_IP);
delayskbcb->ptime[TP_SKB_RECV] = skbprobe_get_skbtime(pskb,TP_SKB_RECV);
}
}
/*0: not match ,1:match*/
int is_uid_match(struct sk_buff *skb)
{
if (0 == (DELAYST_SKB_CB(skb)->android_uid) ) {
return 0;
}
if ((UID_MATCH_ALL == Settings.android_uid) ||
((DELAYST_SKB_CB(skb)->android_uid) == Settings.android_uid)) {
return 1;
} else {
return 0;
}
}
void skbprobe_record_first(struct sk_buff *skb, u32 type)
{
if (type > (TP_SKB_MAX_ENTRY - 1)) {
return;
}
memset(DELAYST_SKB_CB(skb)->ptime, 0, sizeof(ktime_t)*TP_SKB_MAX_ENTRY);
DELAYST_SKB_CB(skb)->ptime[type] = ktime_get_real();
DELAYST_SKB_CB(skb)->pdirect = ((type == 0) ? (TP_SKB_DIRECT_SND) : (TP_SKB_DIRECT_RCV));
DELAYST_SKB_CB(skb)->android_uid = UID_MATCH_ALL;
}
void skbprobe_record_time(struct sk_buff *skb, int index)
{
if (index < 0 || index >= TP_SKB_MAX_ENTRY) {
return;
}
DELAYST_SKB_CB(skb)->ptime[index] = ktime_get_real();
}
void skbprobe_record_proto(struct sk_buff *skb, __u8 n)
{
skbprobe_set_proto(skb,n);
}
u32 skbprobe_get_latency(struct sk_buff *skb, int t1, int t2)
{
if (t1 < 0 || t2 < 0 || t1 >= TP_SKB_MAX_ENTRY || t2 >= TP_SKB_MAX_ENTRY) {
return 0;
}
return (ktime_to_us(skbprobe_get_skbtime(skb,t2)) - ktime_to_us(skbprobe_get_skbtime(skb,t1)));
}
u32 skbprobe_get_latency_from_delayst(DELAYSKB_CB_T *delayskb, int t1, int t2)
{
if (t1 < 0 || t2 < 0 || t1 >= TP_SKB_MAX_ENTRY || t2 >= TP_SKB_MAX_ENTRY) {
return 0;
}
return (ktime_to_us(delayskb->ptime[t2]) - ktime_to_us(delayskb->ptime[t1]));
}
int delay_record_get_interval_index(uint32_t uDelay)
{
const int threshold_values[4] ={50,200, 1000, 10000};
int j = 0;
for (j=0; j<4; ++j) {
if (uDelay < threshold_values[j]) {
break;
}
}
return j;
}
void delay_record_send(DELAY_STAT_T *delay, struct sk_buff *skb)
{
int i=0;
uint32_t uDelay = 0;
for (i=0; i<4; ++i) {
uDelay = skbprobe_get_latency(skb,i,i+1);
delay->T_TotalDelay[i+1] += uDelay;
delay->T_TotalPkts[i+1] += 1;
delay->T_gap[i+1][delay_record_get_interval_index(uDelay)] ++;
}
}
void delay_record_receive(DELAY_STAT_T *delay, struct sk_buff *skb)
{
int i=0;
uint32_t uDelay = 0;
for (i=3; i>0; --i) {
uDelay = skbprobe_get_latency(skb,i,i-1);
delay->T_TotalDelay[i-1] += uDelay;
delay->T_TotalPkts[i-1] += 1;
delay->T_gap[i-1][delay_record_get_interval_index(uDelay)] ++;
}
}
/*combine funtion for network layer*/
void delay_record_ip_combine(struct sk_buff *skb, skbdirect_enum direct)
{
struct iphdr *iph= NULL;
int index =TP_SKB_HMAC_UPLOAD;
delay_flow_ctl(skb);
iph = ip_hdr(skb);
if (NULL == iph) {
return;
}
if (iph->saddr == in_aton("127.0.0.1") || iph->daddr == in_aton("127.0.0.1")) {
memset(DELAYST_SKB_CB(skb)->ptime, 0, sizeof(ktime_t)*TP_SKB_MAX_ENTRY);
return;
}
if (direct == TP_SKB_DIRECT_SND) {
index = TP_SKB_SEND;
}
if (IS_NEED_RECORD_DELAY(skb,index)) {
skbprobe_record_time(skb, TP_SKB_IP);
}
}
/*determine whether we should record the packet or not in receive direction,filter function*/
void delay_record_rcv_combine(struct sk_buff *skb,struct sock *sk,skbtype_enum type)
{
DELAYST_SKB_CB(skb)->android_uid = sk->sk_uid.val;
if (IS_NEED_RECORD_DELAY(skb, TP_SKB_IP) && is_uid_match(skb)) {
skbprobe_record_time(skb, TP_SKB_RECV);
skbprobe_record_proto(skb,type);
delay_record_gap(skb);
}
}
/*determine whether we should record the packet or not in send direction,filter function*/
void delay_record_snd_combine(struct sk_buff *skb)
{
if (IS_NEED_RECORD_DELAY(skb,TP_SKB_HMAC_TX) && is_uid_match(skb)) {
skbprobe_record_time(skb, TP_SKB_DMAC);
delay_record_gap(skb);
}
}
void delay_record_gap(struct sk_buff *skb)
{
if (IS_DIRECT(skb, TP_SKB_DIRECT_SND)) {
delay_print_time_exception(skb,TP_SKB_SEND,TP_SKB_DMAC);
delay_record_send(&Delay_S, skb);
} else {
delay_print_time_exception(skb,TP_SKB_DMAC,TP_SKB_RECV);
delay_record_receive(&RcvDelay_S, skb);
}
if (Settings.dp_mode == mode_stat) {
if (0 != delayst_switch) {
delay_record_print_combine(skb);
}
} else {
trace_skb_latency(skb);
}
}
/*record first timestamp*/
void delay_record_first_combine(struct sock *sk, struct sk_buff *skb , skbdirect_enum direct , skbtype_enum type)
{
skbprobe_record_first(skb, TP_SKB_SEND);
skbprobe_record_proto(skb, type);
DELAYST_SKB_CB(skb)->android_uid = sk->sk_uid.val;
}
/*print delay time*/
void delay_record_print_combine(struct sk_buff *skb)
{
if (!delayst_switch) {
return;
}
if (IS_DIRECT(skb, TP_SKB_DIRECT_RCV)) {
if (PACKET_IS_ENOUGH_FOR_PRINT(RcvDelay_S, TP_SKB_RECV)) {
printk("SumPkts record : %u ,"
"Rcv Delay [<50us, <200us, <1ms, <10ms, >=10ms]"
"driver:[%u, %u, %u, %u, %u ]"
"ip:[%u, %u, %u, %u, %u ]"
"transport:[%u, %u, %u, %u, %u ]"
"Average: driver %u, ip %u, transport %u",
RcvDelay_S.T_TotalPkts[TP_SKB_RECV],
GET_UPLOAD_ALL, GET_RCV_IP_ALL,GET_RECV_ALL,
GET_AVG_UPLOAD, GET_RCV_AVG_IP, GET_AVG_RECV);
memset(&RcvDelay_S,0,sizeof(DELAY_STAT_T));
}
} else {
if (PACKET_IS_ENOUGH_FOR_PRINT(Delay_S, TP_SKB_DMAC)) {
printk("SumPkts record in driver: %u ,"
"Send Delay [<50us, <200us, <1ms, <10ms, >=10ms]"
"transport:[%u, %u, %u, %u, %u ]"
"ip:[%u, %u, %u, %u, %u ]"
"hmac:[%u, %u, %u, %u, %u ]"
"driver:[%u, %u, %u, %u, %u ]"
"Average: transport %u, ip %u,hmac %u,driver %u",
Delay_S.T_TotalPkts[TP_SKB_DMAC],
GET_SND_IP_ALL, GET_XMIT_ALL, GET_TX_ALL,GET_DMAC_ALL,
GET_SND_AVG_IP, GET_AVG_XMIT,GET_AVG_TX,GET_AVG_DMAC);
memset(&Delay_S,0,sizeof(DELAY_STAT_T));
}
}
}
/*for flow control ,based on pps*/
void delay_flow_ctl(struct sk_buff *skb)
{
static u32 total_pkt = 0;
static u8 delay_cnt = 0;
static s64 t_begin = 0;
s64 kt = 0;
if (!IS_DELAY_SWITCH_AUTO) {
return;
}
kt = ktime_to_us(ktime_get_real());
if (0 == t_begin) {
t_begin = kt;
}
total_pkt += 1;
if ((kt - t_begin) > 1000000) { /*statistics time is over 1s */
if ((total_pkt > DELAY_FLOW_THRESHOLD && delayst_switch) ||
(total_pkt < DELAY_FLOW_THRESHOLD && (!delayst_switch))) { /*overflow/lowflow */
delay_cnt++;
if (delay_cnt >= 3) { /*overflow/lowflow for at least 3 times */
delayst_switch = !delayst_switch;
delay_cnt = 0;
}
} else { /*not overflow/lowflow,count again*/
delay_cnt = 0;
}
total_pkt = 0;
t_begin =kt;
}
return ;
}
/* for time delay exception */
void delay_print_time_exception(struct sk_buff *skb, int t1, int t2)
{
static u8 time_delay_exceed_count_tx = 0;
static u8 time_delay_exceed_count_rx = 0;
u64 uDelay = 0;
static DELAYSKB_CB_T tx_buff;
static DELAYSKB_CB_T rx_buff;
struct delay_chr_report delay_excp_chr_report = {0};
uDelay = skbprobe_get_latency(skb,t1,t2);
if (IS_DIRECT(skb, TP_SKB_DIRECT_SND)) {
if ((uDelay > 7*DELAY_NORMAL_TIME) && (uDelay < 100*DELAY_NORMAL_TIME)) { /*bigger than 7 times normal delay*/
time_delay_exceed_count_tx++;
if (time_delay_exceed_count_tx >=10) {
skbprobe_copy_delayskbcb(&tx_buff,skb);
}
} else {
if (time_delay_exceed_count_tx >=10) {
delay_excp_chr_report.data_direct = TP_SKB_DIRECT_SND;
delay_excp_chr_report.exception_cnt = time_delay_exceed_count_tx;
delay_excp_chr_report.driver_delay = skbprobe_get_latency_from_delayst(&tx_buff, TP_SKB_HMAC_TX, TP_SKB_DMAC);
delay_excp_chr_report.hmac_delay = skbprobe_get_latency_from_delayst(&tx_buff, TP_SKB_HMAC_XMIT, TP_SKB_HMAC_TX);
delay_excp_chr_report.ip_delay = skbprobe_get_latency_from_delayst(&tx_buff, TP_SKB_IP, TP_SKB_HMAC_XMIT);
delay_excp_chr_report.transport_delay = skbprobe_get_latency_from_delayst(&tx_buff, TP_SKB_SEND, TP_SKB_IP);
delay_excp_chr_report.android_uid = tx_buff.android_uid;
wifi_kernel_delay_report(&delay_excp_chr_report);
printk( "time_delay_exception! TX: exception_count = %d, uid = %u, transport_delay %u, ip_delay %u,hmac_delay %u,driver_delay %u,send_time:%lld,ip_time:%lld",
time_delay_exceed_count_tx, tx_buff.android_uid, delay_excp_chr_report.transport_delay, delay_excp_chr_report.ip_delay, delay_excp_chr_report.hmac_delay,
delay_excp_chr_report.driver_delay,ktime_to_us(tx_buff.ptime[TP_SKB_SEND]),ktime_to_us(tx_buff.ptime[TP_SKB_IP]));
}
time_delay_exceed_count_tx = 0;
}
} else {
if ((uDelay > 7*DELAY_NORMAL_TIME) && (uDelay < 100*DELAY_NORMAL_TIME)) {
time_delay_exceed_count_rx++;
if(time_delay_exceed_count_rx >=10) {
skbprobe_copy_delayskbcb(&rx_buff,skb);
}
} else {
if (time_delay_exceed_count_rx >=10) {
delay_excp_chr_report.data_direct = TP_SKB_DIRECT_RCV;
delay_excp_chr_report.exception_cnt = time_delay_exceed_count_rx;
delay_excp_chr_report.driver_delay = skbprobe_get_latency_from_delayst(&rx_buff, TP_SKB_DMAC, TP_SKB_HMAC_UPLOAD);
delay_excp_chr_report.ip_delay = skbprobe_get_latency_from_delayst(&rx_buff, TP_SKB_HMAC_UPLOAD, TP_SKB_IP);
delay_excp_chr_report.transport_delay = skbprobe_get_latency_from_delayst(&rx_buff, TP_SKB_IP, TP_SKB_RECV);
delay_excp_chr_report.android_uid = rx_buff.android_uid;
wifi_kernel_delay_report(&delay_excp_chr_report);
printk("time_delay_exception! RX: exception_count = %d, uid = %u, driver_delay %u, ip_delay %u,transport_delay %u,DMAC_time:%lld,UPLOAD_time:%lld",
time_delay_exceed_count_rx , rx_buff.android_uid,delay_excp_chr_report.driver_delay,delay_excp_chr_report.ip_delay,delay_excp_chr_report.transport_delay,
ktime_to_us(rx_buff.ptime[TP_SKB_DMAC]),ktime_to_us(rx_buff.ptime[TP_SKB_HMAC_UPLOAD]));
}
time_delay_exceed_count_rx = 0;
}
}
return;
}
int delay_set_wifi_command(const char *val)
{
char *clone = NULL, *sub_cmd = NULL;
int err = 0;
unsigned int uid = 0, interval = 0;
const char flag_names[][20] = {"flag_off", "flag_on", "flag_auto"};
const char mode_names[][20] = {"mode_stat", "mode_trace"};
if (!val)
return -EFAULT; /* Bad address */
clone = kstrdup(val, GFP_USER);
if (!clone) {
return -EFAULT;
}
switch (clone[0])
{
case 'f':
if (strcmp(clone,"flag_on") == 0) {
Settings.dp_switch = flag_on;
static_key_enable(&wifi_delay_statistic_key);
delayst_switch = 1;
} else if (strcmp(clone,"flag_off") == 0) {
Settings.dp_switch = flag_off;
static_key_disable(&wifi_delay_statistic_key);
delayst_switch = 0;
} else if (strcmp(clone,"flag_auto") == 0) {
Settings.dp_switch = flag_auto;
delayst_switch = 1;
}
break;
case 'm':
if (strcmp(clone,"mode_stat") == 0) {
Settings.dp_mode = mode_stat;
} else if(strcmp(clone,"mode_trace") == 0) {
Settings.dp_mode = mode_trace;
}
break;
case 'u':
sub_cmd = strchr((const char *)clone, '_');
if (NULL == sub_cmd) {
return -EFAULT;
}
sub_cmd++;
err = kstrtouint((const char *)sub_cmd, 10, &uid);
if (!err) {
Settings.android_uid = uid;
CLEAN_DELAY_RECORD;
}
break;
case 'p':
sub_cmd = strchr((const char *)clone, '_');
if (NULL == sub_cmd) {
return -EFAULT;
}
sub_cmd++;
err = kstrtouint((const char *)sub_cmd, 10, &interval);
if (!err) {
Settings.print_interval = interval;
CLEAN_DELAY_RECORD;
}
break;
case 'd':
CLEAN_DELAY_RECORD;
break;
case 'c':
printk("delay_command configure:delay_switch = %s,dealy_mode = %s,print_interval = %u,android_uid = %u",
flag_names[Settings.dp_switch],mode_names[Settings.dp_mode],Settings.print_interval,Settings.android_uid);
break;
default:
break;
}
if (clone)
kfree(clone);
return 0;
}
int proc_wifi_delay_command(struct ctl_table *ctl, int write, void __user *buffer,
size_t *lenp, loff_t *ppos)
{
char val[DELAY_FILTER_NAME_MAX];
struct ctl_table tbl = {
.data = val,
.maxlen = DELAY_FILTER_NAME_MAX,
};
int err = 0;
if (write) {
err = proc_dostring(&tbl, write, buffer, lenp, ppos);
if (!err) {
err = delay_set_wifi_command(val);
}
}
return err;
}
|
A method for the analysis of catecholamines by selected ion monitoring and 14C isotope dilution in adrenal medullary cell culture. Extracts have been made from culture medium of rat medullar adrenal cells developed in tissue culture in this laboratory. After pentafluorobenzylimine-trimethylsilyl ether formation the catecholamine derivatives were characterized by gas-liquid chromatography chemical ionization mass spectrometry. In order to assess the catecholamine production capabilities of the cells in culture, a mass spectrometric method with isotope dilution has been devised. Chemical ionization selected ion monitoring allows specific detection at the nanogram level in a higher mass range (400-600 amu) than in the electron impact mode. The isotopic dilution method with 14C catecholamines gives rise to accurate measurements and linear response in the picomole range. The use of the + ion for monitoring m/z values minimizes errors in selected ion monitoring analysis. The results obtained are computerized and treated by the data system for fine background subtraction when high sensitivity and accuracy are required. |
<filename>src/shared/home/my-votes.tsx<gh_stars>0
import PlusOutlined from "@ant-design/icons/PlusOutlined";
import RedoOutlined from "@ant-design/icons/RedoOutlined";
import Alert from "antd/lib/alert";
import { t } from "onefx/lib/iso-i18n";
import Helmet from "onefx/lib/react-helmet";
import { styled } from "onefx/lib/styletron-react";
import React, { Component } from "react";
import { connect } from "react-redux";
import { CommonMargin } from "../common/common-margin";
import { IopayRequired } from "../common/iopay-required";
import { colors } from "../common/styles/style-color";
import { fonts } from "../common/styles/style-font";
import { VotingButton } from "../home/vote-button-modal";
import { VoteNowContainer } from "../staking/vote-now-steps/vote-now-container";
import { BucketsLoader } from "./account-meta";
import { MyVotesTable } from "./my-votes-table";
type State = {
showVoteNowModal: boolean;
};
type Props = {};
// path: /my-votes
export function MyVotes(): JSX.Element {
return (
<div>
<Helmet title={`${t("my_stake.title")} - ${t("meta.description")}`} />
<StakingContractContainer />
<CommonMargin />
</div>
);
}
export class StakingContractContainer extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
showVoteNowModal: false,
};
}
refreshPage = () => {
window.location.reload();
};
render(): JSX.Element {
return (
<div>
<SmartContractCalled />
<VotingButton
launch={() => this.setState({ showVoteNowModal: true })}
disabled={false}
extra={{ size: "large" }}
>
<span>
<PlusOutlined />
{t("my_stake.new_vote")}
</span>
</VotingButton>
<RefreshButtonStyle onClick={() => this.refreshPage()}>
<RedoOutlined style={{ marginRight: 4 }} />
{t("my_stake.refresh_list")}
</RefreshButtonStyle>
<CommonMargin />
<MyVotesTableWrapper />
<VoteNowContainer
displayOthers={false}
forceDisplayModal={this.state.showVoteNowModal}
requestDismiss={() => this.setState({ showVoteNowModal: false })}
/>
</div>
);
}
}
@IopayRequired
// @ts-ignore
class MyVotesTableWrapper extends Component {
render(): JSX.Element {
return (
<>
<BucketsLoader />
<MyVotesTable />
</>
);
}
}
const SmartContractCalled = connect(
(state: { smartContract: { smartContractCalled: boolean } }) => {
return {
smartContractCalled:
state.smartContract && state.smartContract.smartContractCalled,
};
}
)(function Inner({
smartContractCalled,
}: {
smartContractCalled: boolean;
}): JSX.Element {
return (
<>
{smartContractCalled && (
<div>
<Alert
message={t("action.broadcasted")}
type="success"
showIcon={true}
/>
<CommonMargin />
</div>
)}
</>
);
});
const RefreshButtonStyle = styled("span", () => ({
...fonts.body,
backgroundColor: colors.white,
color: colors.primary,
float: "right",
lineHeight: "55px",
}));
|
Fibre Orientation in Human Fetal Heart and Ventricular Mechanics : A Small Perturbation Analysis. The study of the topological organisation of myocardial cells is a basic requirement for understanding the mechanical design of the normal and pathological heart. Anatomical observations show that cardiac muscle tissue has a highly specialized architecture. We have made new quantitative measurements of fibre orientation through the heart wall by means of polarized light analysis on some thick sections of human fetal heart embedded in a resin and polymerized. A small perturbation method to find an equilibrium solution in a cylindrical left ventricular (LV) geometry with fibres running on toroidal shells of revolution is used to investigate the mechanical behaviour of three human fetal hearts (FH) of 14, 20 and 33 weeks of gestational age. The results of fibre strains and stresses presented for end-systolic state show significant differences when compared to results of the cylindrical geometry with regular helicoidal fibres running on cylindrical surfaces. Moreover, the toroidal shells of revolution explain shear stresses and strains in the transverse plane which also exist in the adult heart. |
BASIS OF STABILIZING THE CUTTING OF WEEDS BY A CULTIVATOR WITH RIGHT- AND LEFT-SIDE SHEETS The materials of the article consider the main problems associated with the overgrowth of weeds in the sown areas of the Republic of Dagestan. The analysis of methods for removing weeds proved the effectiveness of the mechanical method by performing soil cultivation. In order to reduce the energy intensity of the cultivation process, it is proposed to cut weeds at a minimum depth. For this, a new design of the cultivator with right- and left-handed paws was proposed, in which an elastic element is provided to stabilize the cutting depth. Based on the consideration of the process of cutting weeds with a cultivators paw, analytical dependencies were derived that provide a connection between the design and technological parameters of the working body of the cultivator with a minimum depth of cutting of weeds of 3-5 cm. field surface irregularities. To confirm the theoretical judgments, field studies of the cultivator of the proposed design and the serial cultivator KPS-4.0 mounted by the MTZ-82 tractor were carried out. In the course of the studies performed, it was found that the standard deviation of the depth of tillage for a serial cultivator was ±0.9±1.2 cm, and was higher compared to the values of the square deviation of the depth of tillage ±0.5±0, 6 cm experimental cultivator. At the same time, the serial cultivator provides 90% cutting of weeds, while the proposed one cuts 95% of weeds. All of the above allows us to conclude that the proposed cultivator with right- and left-handed paws is effective in tillage. |
/**
* Transforms a common QueryResultStatistic to an OSSE QueryResultStatistic.
*
* @param commonQueryResultStatistic the QueryResultStatistic in the common namespace
* @return the QueryResultStatistic in the osse namespace
*/
public static de.samply.share.model.osse.QueryResultStatistic convertCommonQrsToOsseQrs(
QueryResultStatistic commonQueryResultStatistic) throws JAXBException {
String commonQueryResultStatisticString = marshal(commonQueryResultStatistic,
JAXBContext.newInstance(de.samply.share.model.common.QueryResultStatistic.class));
commonQueryResultStatisticString = commonQueryResultStatisticString
.replace(XMLNS_PATH_COMMON, XMLNS_PATH_OSSE);
de.samply.share.model.osse.QueryResultStatistic osseQueryResultStatistic = unmarshal(
commonQueryResultStatisticString,
JAXBContext.newInstance(de.samply.share.model.osse.QueryResultStatistic.class),
de.samply.share.model.osse.QueryResultStatistic.class);
return osseQueryResultStatistic;
} |
Protestors set fires outside the gates of Egypt's presidential palace on Friday as Cairo endured a second straight week of demonstrations against Mohammed Morsi.
Protestors set fires outside the gates of Egypt's presidential palace on Friday as Cairo endured a second straight week of demonstrations against Mohammed Morsi. Police responded with tear gas and water cannons, creating a chaotic scene of violence and mayhem.
During the day, tens of thousands of mostly peaceful demonstrators filled Tahrir Squarem waving signs and chanting slogans as they called for a quick end to Morsi's reign, but the nighttime has devolved in to an even more chaotic scene as small bands of fighters defy the curfew to hurl petrol bombs and rocks under the cover of the darkness—as it has almost every night since the protests were reignited on January 25.
More than 60 people died in clashes with police over the last week, but even more trouble is expected as the city heads into the weekend. The deadliest protests took place in Port Said, where Friday marked the one-year anniversary of a terrible soccer riot that killed 70 people.
Morsi has imposed a curfew and emergency law in Port Said and two other cities along the Suez Canal, but that has only fueled the anger of those who believe his government is undemocratic and a betrayal of the nation's revolution. Hopefully, the coming days won't see a repeat of last week's bloodshed, but with neither side seeming to give an inch in the ongoing constitutional debate, those hopes are pretty slim. |
The poll, released Thursday, shows that only 30 percent of the public approves of U.S. leadership, down from 48 percent in 2016. At the same time, 43 percent of people expressed a negative opinion of the U.S. leadership, up from 28 percent in 2016.
Tell your members of Congress: Renegotiation of NAFTA must benefit people and our climate, not multinational corporations.
In a matter of days, President Obama will launch his final push to pressure Congress to pass the Trans-Pacific Partnership (TPP). It's a secretive trade deal that has been called "NAFTA on steroids" - and for good reason.
Far Too Short a Victory!
Sen. Elizabeth Warren, along with Sen. Sherrod Brown, have responded to recent White House statements on TPP with a sharply-worded letter calling out President Obama and other backers of the corporate-friendly trade pact.
We need to fight now to ensure the American public, which has purposefully been kept in the dark about the TPP, knows exactly what is in it.
Fast track authority would allow the President to sign the TPP before Congress has voted to approve it, and then railroad the deal through Congress in only 90 days with limited debate and no amendments allowed.
Tell national leaders and trade representatives negotiating the TPP in secret that we won't let them ambush us with a hidden agenda to let corporations censor our internet, and gain more power over our lives. |
WAS THE POLIS A PERSON IN CLASSICAL ATHENS? CIVIC BODIES AND CHORAL POLITICS IN THE THEATER In his History of the Peloponnesian War, Thucydides waits until he has passed the midpoint of Book 1 to introduce an individual speaking character into his narrative. He does not do so until the scene of the Congress at Sparta (1.6788), where it is first the Corinthians and then the Athenians who plead their cases before the Spartan assembly. One of the functions of this scene is to illustrate the internal division of opinion among the Spartans, and Thucydides now brings two distinct, elite Spartans onstage to voice their conflicting perspectives: King Archidamus addresses his countrymen urging caution (1.805), while the ephor Sthenelaidas makes suitably laconic remarks pressing for war (1.86). Before this turning point, Thucydides had carried out his analysis of the war's causes exclusively with reference to foreign rulers and Greek polis-populations (the Athenians, the Spartans, etc.)and not to any individual actors or leaders of those poleis, such as Archidamus and Sthenelaidas of Sparta. |
Hundreds of thousands of residents in the Mekong Delta of Vietnam were told to evacuate Monday as deadly Tropical Storm Tembin tracks westward from the Philippines.
Officials say several hundreds of thousands fled their homes, a majority of which are made of tin sheets and wooden panels. In Vung Tau city, thousands of fishing boats were forced to halt their several-month-long trips to return to the shore.
Tembin caused more than 160 deaths and left 171 missing after it lashed the southern Philippines, triggering flash floods and landslides.
Most of the deaths from Tropical Storm Tembin were in the hard-hit provinces of Lanao del Norte and Lanao del Sur and on the Zamboanga Peninsula, according to an initial government report on storm casualties.
It's the latest disaster to hit the Philippines, which is battered by about 20 typhoons and storms each year, making the archipelago that lies on the Pacific typhoon belt one of the world's most disaster-prone countries.
(MORE: Southern California's Thomas Fire Now Largest in State History)
A search and rescue operation was underway for more than 30 people swept away by flash floods in the fishing village of Anungan, Mayor Bong Edding of Zamboanga del Norte province's Sibuco town said by phone. Five bodies have been recovered so far in the village.
The rest of the deaths were reported in Lanao del Norte, where floodwaters from a mountain also swept away several riverside houses and villagers, and Lanao del Sur, police and officials said.
Lanao del Norte officials reported the highest death toll at 64 with 139 missing followed by Zamboanga del Norte province, where officials reported at least 29 storm deaths with 19 others missing. The storm left 21 dead and one missing in the lakeside province of Lanao del Sur, according to the Department of Interior and Local Government.
More than 97,000 people remain in 261 evacuation centers across the south, while nearly 85,000 more people are displaced and staying elsewhere as of Monday.
An inter-island ferry sank off northeastern Quezon province last week after being lashed by fierce winds and big waves, leaving at least five people dead. More than 250 passengers and crewmen were rescued.
Tembin, known locally as Vinta, strengthened and picked up speed late Saturday, packing maximum sustained winds of 105 kilometers (65 miles) per hour and gusts of up to 145 kph (90 mph). It struck the southern section of western Palawan province late Saturday and is forecast to blow away from the southern Philippines on Sunday toward the South China Sea. |
Gender alters the high-density lipoprotein cholesterol response to cardiac rehabilitation. PURPOSE A reduced level of high-density lipoprotein cholesterol (HDL-C) is a powerful independent risk factor for the development and progression of coronary heart disease. This study assessed the effects of cardiac rehabilitation exercise training on HDL-C and other lipid subfractions, giving close attention to the role of gender and baseline values. METHODS The study population consisted of 340 patients with coronary heart disease who enrolled in outpatient cardiac rehabilitation and completed 36 sessions of exercise over a 12-week period. With the National Cholesterol Education Panel ATP III guidelines used to create categories of HDL-C, patients were stratified at baseline into four subgroups: males with high HDL-C, males with low HDL-C, women with high HDL-C, and women with low HDL-C. RESULTS Overall, women experienced a significantly greater improvement in HDL-C after exercise training than men (14% vs 7.1%; P <.0001). Among the patients with a high HDL-C at baseline, the women increased HDL-C by 8.4%, whereas there was no change (0.9%) in the men (P <.001 between groups). Additionally, the women with low HDL-C experienced a significantly greater improvement than the men (15.3% vs 11.5%, P <.03). CONCLUSIONS The study results demonstrate that women experience a greater improvement in HDL-C with cardiac rehabilitation than men despite similar changes in fitness and body composition. Women, regardless of baseline HDL-C, demonstrated improvements in HDL-C, whereas only men with low HDL-C experienced an increase in HDL-C. These results describe a differing impact of cardiac rehabilitation on changes in HDL-C based on gender. Clinicians should consider the impact of gender when assessing an individual's risk factor goals and therapeutic options. |
#include <vector>
#include <stan/model/indexing/index_list.hpp>
#include <stan/model/indexing/index.hpp>
#include <gtest/gtest.h>
using stan::model::cons_index_list;
using stan::model::nil_index_list;
using stan::model::index_multi;
using stan::model::index_uni;
TEST(MathIndexingIndexList, cons_index_list) {
nil_index_list empty; // ()
index_uni idx_u(7);
cons_index_list<index_uni, nil_index_list> cil(idx_u, empty);
EXPECT_EQ(index_uni(7).n_, cil.head_.n_);
std::vector<int> ns;
ns.push_back(3);
ns.push_back(17);
index_multi idx_m(ns);
cons_index_list<index_multi, cons_index_list<index_uni, nil_index_list> >
cil2(idx_m, cil);
EXPECT_EQ(2, cil2.head_.ns_.size());
EXPECT_EQ(17, cil2.head_.ns_[1]);
EXPECT_EQ(7, cil2.tail_.head_.n_);
}
|
def fill_form(self, first_name, last_name):
first_name_box = self.browser.find_element_by_css_selector("input#id_first_name")
last_name_box = self.browser.find_element_by_css_selector("input#id_last_name")
first_name_box.send_keys(first_name)
last_name_box.send_keys(last_name) |
def sanitize(string):
if not isinstance(string, str):
return string
string = cybox.utils.unwrap_cdata(string)
if any(c in string for c in XML_RESERVED_CHARS):
return cybox.utils.wrap_cdata(string)
else:
return string |
Kilimanjaro Safaris
Story
The current story is a short photo safari aboard a safari vehicle through the Harambe Wildlife Reserve in Harambe, East Africa. It is 800 square miles (2,100 km²) of natural terrain, including Ituri forest, wetlands of the Safi River valley, and the open bush country of the Serengeti Savanna. African animals on view include real live elephants, giraffes, antelopes, gazelles, crocodiles, monkeys, hippopotamuses, lions, cheetahs, hyenas, african wild dogs, warthogs, ostriches, rhinoceroses, ducks, storks, pelicans, flamingos, wildebeests, okapis and zebras. The game driver points out animals and provides entertainment. The zebras were removed four months after their arrival due to "acclimation" issues. Some reports claim that the zebras were fighting each other, biting at vehicles or each other, standing in the road, or just causing trouble. They were quickly replaced with addax. As of September 2019, there are still no zebras on the wildlife reserve.
History
Long before the safari or even Walt Disney World opened, Walt Disney wanted to use real African animals for the river attraction Jungle Cruise at Disneyland. However, for several reasons, Audio-Animatronics replicas were placed instead.
The ride originally included a scripted portion where the safari truck - callsign "Simba-1" - would be contacted by a habitat warden and a scientist to hunt down poachers that had captured a mother elephant and her child - Big Red and Little Red, respectively. The poachers would have been captured at gunpoint by another cast member, a warden. This element of the attraction was eventually eliminated and replaced with scaring off the poachers after a pursuit.
During Cast Previews of Disney's Animal Kingdom, there was a "Dark Ending" in which the safari vehicle encountered the slaughtered corpse of Big Red. She was seen bloody and on the ground with her tusks sawed off, symbolizing the poachers got to her and the tour group was too late to save the mother elephant. Even though it was only an animatronic, this scene proved too shocking for families and children. Many complaints were filed, so before the official grand opening of the ride, Disney removed the dead corpse, thus changing the attraction that of a happier ending.
Kilimanjaro Safaris typically operates until sundown. However, during the holiday season of 1998, the safaris were continued at night and dubbed Kilimanjaro Night Safaris. Though many animals were asleep, or unable to be seen at night, the attraction had a completely different script and storyline. This "new" attraction featured additional animal sounds, reflectors hidden in the foliage to resemble animals' eyes, and an actual African dance troup, who performed around a bonfire in the area normally occupied by the attraction's elephants. Kilimanjaro Night Safaris only ran during that initial holiday season. After this time, it was deemed that the additional costs, plus the fact that animal visibility was poor (eliciting many guest complaints), made Night Safaris unfeasible to continue regularly.
In 2004, much of the savanna's drainage system had to be replaced. The attraction remained open during the rehab, with green tarps covering the construction sites to keep the animals out.
In 2007-9, the trucks were extended with an extra row of seating, allowing for more capacity. Also, the safari script/story, along with the Wilson/Jobson story has significantly changed. There is less of a story about "Little Red", and more about the animals in the reserve and the need to find a lost elephant at the end. This led to a somewhat confused plot in which guests are searching for a lost "mother elephant" and eventually find her baby which, according to the story, had already been safe the whole time.
In July 2010 it was announced that guests will soon be able to go on "guided treks" around the savanna. This will include areas that are not part of the regular ride experience.
On February 10, 2012 it was announced that the "Little Red" portion of the ride would be replaced with a zebra exhibit. It opened in the fall of 2012.
In 2016, Night Safaris were reintroduced as a part of the expansion of Disney's Animal Kingdom. The nighttime changes included a "sunset," animal sounds, and the introduction of hyenas to the reserve. The ride path was shortened for the night safaris in order to avoid areas where no animals would be visible. |
The falling leaves are going to cost the middle class person in town more money. We might as well just call it another tax.
Bag the leaves yourself or pay someone to do it or if you have someone cutting your grass its going to cost you more. I have been a resident of Stamford for more than 70 years and a taxpayer over 50 years and it only gets worse. Our sewer usage used to be in our tax bill so our politicians had a new way of not raising our taxes but just gave us a sewer usage bill.
My kids want me and my wife to move but it is so hard to do. It’s OK to build a new city in the South End of Stamford but what has happened with the taxes that our being raised by all those apartments? Is Mr. BLT paying his share. It looks nice and great for the millennials to move in and pay less then New York rents. Please Mr. Mayor, help us longtime seniors that own in Stamford; let us stay here and tax the proper people. |
package com.jsoniter.suite;
import com.jsoniter.JsonIterator;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Categories.class)
@Suite.SuiteClasses({AllTestCases.class})
public class StreamingTests {
@BeforeClass
public static void setup() {
JsonIterator.enableStreamingSupport();
}
}
|
/**
* Set: Premium (Enhanced Cloud City)
* Type: Starship
* Subtype: Starfighter
* Title: Dengar In Punishing One
*/
public class Card109_010 extends AbstractStarfighter {
public Card109_010() {
super(Side.DARK, 1, 5, 2, null, 5, 3, 5, "Dengar In Punishing One", Uniqueness.UNIQUE);
setLore("Corellian starfighter. Dengar replaced its passenger capacity and TIE cannons with enhanced targeting systems. Allows Dengar to track and engage multiple enemies at once.");
setGameText("Permanent pilot is •Dengar, who provides ability of 2 and adds 2 to power. When in battle, adds 1 to total battle destiny for each opponent's starship present. Cancels opponent's immunity to attrition here.");
addPersonas(Persona.PUNISHING_ONE);
addIcons(Icon.PREMIUM, Icon.INDEPENDENT, Icon.PILOT, Icon.NAV_COMPUTER);
addModelType(ModelType.CORELLIAN_JM_5000);
}
@Override
protected List<? extends AbstractPermanentAboard> getGameTextPermanentsAboard() {
return Collections.singletonList(
new AbstractPermanentPilot(Persona.DENGAR, 2) {
@Override
public List<Modifier> getGameTextModifiers(PhysicalCard self) {
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new PowerModifier(self, 2));
return modifiers;
}
});
}
@Override
protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) {
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new TotalBattleDestinyModifier(self, new InBattleCondition(self), new PresentEvaluator(self,
Filters.and(Filters.opponents(self), Filters.starship)), self.getOwner()));
modifiers.add(new CancelImmunityToAttritionModifier(self, Filters.and(Filters.opponents(self), Filters.atSameLocation(self))));
return modifiers;
}
} |
Postnatal development of corticosteroid receptor immunoreactivity in the rat cerebellum and brain stem. The postnatal development of corticosteroid receptor immunoreactivity in the rat cerebellum and related brainstem nuclei was studied using a type I receptor antiserum, MINREC4, and a type II receptor monoclonal antibody, BUGR2. Type I receptor immunoreactive (ir) Purkinje cells were first observed at postnatal day 5 (P5), and increased to adult levels by P20. Type I-ir cells, presumably migrating granule cells, were observed in the developing molecular layer of the cerebellum at P5. By P30, the density of type I-ir cells in the definitive molecular and granular layers was still less than adult levels. In contrast, type II-ir Purkinje cells were first observed at P15 and increased to adult levels by P20. No type II-ir cells were observed in the proliferative and migratory zones of the molecular layer. By P30, the density of type II-ir cells in the molecular and granular layers was far less than adult levels. In the deep cerebellar nuclei and most brain stem nuclei type I-ir was observed at P5 and developed to adult levels by P30. Type II-ir was observed in the deep cerebellar nuclei, red and medial vestibular nuclei by P15. The pontine and inferior olivary nuclei showed type II-ir cells by P10. Type II-ir in these regions developed to adult levels by P30. The earlier development of type I-ir suggests that the type I receptor may mediate the actions of corticosteroids in the cerebellum and related brain stem nuclei during early postnatal life.(ABSTRACT TRUNCATED AT 250 WORDS) |
Subsets and Splits