content
stringlengths
7
2.61M
Aromatic adsorption on metals via first-principles density functional theory We review first-principles calculations relevant to the adsorption of aromatic molecules on metal surfaces. Benzene has been intensively studied on a variety of substrates, providing an opportunity to comment upon trends from one metal to another. Meanwhile, calculations elucidating the adsorption of polycyclic aromatic molecules are more sparse, but nevertheless yield important insights into the role of non-covalent interactions. Heterocyclic and substituted aromatic compounds introduce the complicating possibility of electronic and steric effects, whose relative importance can thus far only be gauged on a case-by-case basis. Finally, the coadsorption and/or reaction of aromatic molecules is discussed, highlighting an area where the predictive power of theory is likely to prove decisive in the future. Introduction Aromatic molecules constitute a large and important class of organic compounds, whose unique properties and ubiquitous nature render them central to much of modern chemistry. Unsurprisingly, therefore, the surface science of such molecules has long been of interest, both on semiconductor surfaces (where the emphasis is upon adsorbate-induced modification of substrate electro-optical properties) and on metal surfaces (where substrate-induced modification of adsorbate chemical properties is more to the point). Substantial experimental literature exists in both fields, and the interested reader is referred to appropriate reviews for more information (Zaera 1995;Wolkow 1999;Filler & Bent 2003;Held 2003;Barlow & Raval 2003;Witte & Wll 2004). Since around the turn of the millennium, however, experimental investigations of aromatic adsorption have been supplemented by state-of-the-art calculations, carried out within the framework of first-principles density functional theory (DFT). As regards surface DFT calculations, the phrase 'state-of-the-art' is here taken to imply use of at least the following: (i) a slab-based geometry, with a sufficiently thick slab for convergence, (ii) full relaxation of both the adsorbate *sjj24@hermes.cam.ac.uk and enough layers of the slab to ensure convergence, (iii) a generalized gradient approximation (GGA) for the exchange-correlation functional, and (iv) either a projector-augmented wave or an ultrasoft pseudopotential description of the electron-ion interaction. These calculations have shed light upon the nature of the adsorbate-substrate bond, aided in the interpretation of experimental studies, and pointed the way towards a systematic understanding of aromatic reactivity. Equally, it must also be recognized that while DFT seemingly succeeds in providing reliable structural, electronic and reaction parameters for these species, it singularly fails accurately to reproduce other key features, such as the adsorption energy, in anything approaching a consistent manner. The purpose of this review is to examine what has thus far been learnt and to identify those areas where theory is currently lacking; it is concerned solely with adsorption on metals, for reasons of brevity. The scope of the review includes the relatively extensive literature on the theory of benzene adsorption on simple, ferromagnetic, platinum group and coinage metals. Several polycyclic and heterocyclic aromatic adsorbates have also been studied theoretically, and these are included together with a range of substituted aromatic adsorbates. A small number of calculations concerning the coadsorption of benzene with non-aromatic surface species are also discussed, as are theoretical studies of hydrogenation/dehydrogenation reactions and their products. Theoretical overview In developing a theoretical model for the adsorption of aromatic molecules on metal surfaces, two crucial issues must be addressed. The first is the extent to which one's model can be trusted to represent the aromaticity of the adsorbate; the second relates to the adequacy of one's description of electronic correlation. Clearly, the first issue arises only when considering aromatic adsorbates, while the other is a general matter to be borne in mind whenever dealing with such relatively large molecules. Before embarking upon the review proper, therefore, it will be advisable to critically assess the performance of first-principles DFT on these two criteria. (a) Description of adsorbate aromaticity Aromatic molecules (or aromatic groups within a larger molecule) are characterized by a fully conjugated cyclic structure having notable stability with respect to ring opening, notable lack of reactivity with respect to substitution or addition and notable diamagnetic ring current effects in nuclear magnetic resonance. In the simplest terms, a monocyclic molecule (or part of a molecule) may be identified as aromatic according to whether or not it satisfies the so-called Hckel rule, which requires that it have 4n + 2 electrons within its conjugated system. This rule reflects the energy distribution of the ring's molecular orbitals, ensuring that occupation of bonding orbitals is maximized while minimizing the occupation of antibonding orbitals. A fully conjugated five-membered ring possesses three bonding and two antibonding orbitals, a six-membered ring possesses three bonding and three antibonding orbitals and a seven-membered ring possesses three bonding and four antibonding orbitals; in each case, precisely six electrons would be required to completely fill all the bonding orbitals without occupying any of the antibonding orbitals. In the familiar case of benzene (C 6 H 6 ), each carbon atom in the six-membered ring provides a single electron, so the Hckel rule is satisfied and the molecule is aromatic. For the neutral cyclopentadienyl (C 5 H 5 ) and cycloheptatrienyl (C 7 H 7 ) radicals, in contrast, the Hckel rule is not satisfied and the ring is not aromatic; the neutral cyclopentadienyl radical has one electron too few to fully occupy all of its bonding orbitals, while the neutral cycloheptatrienyl radical has one electron too many to avoid partially occupying one of its antibonding orbitals. On this basis, however, it should be no surprise that the cyclopentadienyl anion (C 5 H − 5 ) is well known to be aromatic (Korolev & Nefedov 1993). This simple picture of aromaticity is highly instructive, but falls short of providing a complete description of all relevant contributions to the chemical properties of actual molecules. The organic literature is replete with discussions of phenomena requiring a more subtle approach, often associated with heterocyclic or polycyclic systems, electron-donating or electron-withdrawing substituents, etc. To fully capture such effects within a theoretical model, it is necessary at least to invoke a molecular orbital scheme, of which DFT is a highly successful example (Parr & Yang 1989;Koch & Holthausen 2000). Put simply, the DFT approach invokes the observation that all ground state properties of a system are fully determined by the total ground state electron density, and thereby recasts the difficult problem of determining the N -electron wave function in terms of the simpler problem of determining N oneelectron wave functions. Each one-electron wave function is evaluated iteratively within a mean-field approach, where the electrostatic and exchange-correlation energies are obtained as functionals of the total electron density. Traditional quantum chemical approaches based upon the Hartree-Fock model achieve a similar separation into one-electron wave functions, but tend not to describe metals with sufficient accuracy to allow reliable adsorption calculations on such susbtrates. 1 One major drawback of the DFT approach is that, while its ability to describe ground state properties is theoretically well founded, its ability to describe electronically excited states is not. It is, in fact, well known that DFT tends to severely underestimate the gap between occupied and unoccupied states in non-metallic systems (whether insulating solids or isolated molecules). Thus, considerable care must be taken with the interpretation of DFT-derived electronic energy levels. Fortunately, however, sufficient collective experience now exists to allow one to say, with some confidence, that the relative energetics among all the occupied levels will typically be reproduced fairly well, as will the relative energetics among all the unnoccupied levels; to a first approximation, one can consider the unoccupied states to have been erroneously shifted relative to the occupied states by a more-or-less uniform offset. Furthermore, experience also shows that the eigenfunctions associated with these energy levels will usually be highly reliable in comparison with those obtained using other quantum chemical techniques. Of maximum importance in the binding of benzene to metal surfaces, for instance, is the description of its two degenerate highest occupied molecular orbitals (HOMOs) and its two degenerate lowest unoccupied molecular orbitals (LUMOs), and these the DFT approach supplies in good order. In short, DFT ought to be considered capable of providing a high-quality description of aromatic systems, so long as the relative energetic positions of the occupied and unoccupied electronic states are treated with due caution. As a general point, however, it should also be recognized that the use of a local density approximation (LDA) for the exchange-correlation functional will likely produce poor results for molecules, and a GGA should be considered much more appropriate. (b) Description of correlation interactions Contributions to the binding of molecules on metal surfaces can be either chemical or physical in nature. Chemical binding typically implies either an ionic interaction, through wholesale transfer of charge between substrate and adsorbate, or a covalent interaction, where orbitals deriving from the adsorbate and the substrate form new bonding and antibonding linear combinations. Physical binding, on the other hand, can arise through interaction of the permanent surface dipole with any intrinsic molecular dipole that may exist, through the interaction of the permanent surface dipole with a statically induced molecular dipole or through interaction between instantaneous dipoles mutually induced in the adsorbate and the substrate. The latter contribution is, in effect, the surface manifestation of the van der Waals (VdW) interaction. 2 In general, VdW interactions are typically considered to be inaccessible within the framework of standard DFT. The problem is that they arise via dipolar excitations of the electronic system away from its ground state, and since DFT guarantees us only a window onto ground state properties, we should not expect reliable answers from this direction. In fact, however, the VdW interaction can fruitfully be regarded as the correlation interaction existing between two regions of high electron density, separated by an intervening region of low electron density. Because the correlation contribution to the energy of the electron gas is included within DFT at the mean-field level, the extent to which DFT does or does not describe the VdW interaction is therefore more accurately a question of whether the mean-field approximation is capable of describing the electronic correlation in a highly inhomogeneous situation. It is not inconceivable, therefore, that a sufficiently complex exchange-correlation functional might succeed in better representing the VdW interaction. Equally, it may be that no such functional can be derived within a mean-field approach. For the present, the best summary of the situation is that standard DFT is known to produce a too-rapid falloff in the interaction energy between two distinct entities as their separation is increased. In the limit of very small separation, the correlation energy captured within DFT might well include a significant fraction of the VdW interaction, but as the separation increases one enters a regime where the VdW interaction is genuinely absent from standard DFT. What all of this means for the adsorption of aromatic molecules is that the accuracy of DFT adsorption energies is very much in question. These are typically quite large molecules (by the standards of surface DFT calculations) that often bind in geometries apt to maximize their VdW interaction with the surface. For the reasons just discussed, some portion of this VdW interaction should be captured by the exchange-correlation functional, but quite a bit may not be. We should therefore expect a fairly significant underestimate of adsorption energy owing to the missing fraction of the VdW interaction. On the other hand, experience with small non-aromatic molecules generally suggests that DFT tends to overestimate covalent binding energies. If the same turns out to be true for aromatic adsorbates, this might offset somewhat the deficiency in the VdW interaction. There seem, on the whole, to be good grounds for a belief that GGA calculations provide a rather sound picture of the covalent chemisorption bond, albeit one that should ideally be supplemented by an estimate of the physisorptive contribution of the VdW interaction; LDA calculations, in contrast, provide adsorption energies that may sometimes lie coincidentally closer to experiment, but almost certainly do so fortuitously by misrepresenting the strength of the covalent chemisorptive component, rather than by more accurately representing the physisorption effect. We shall comment further on this issue in specific cases reviewed below. Adsorbed benzene The starting point for any review of aromatic adsorption on metal surfaces must, inevitably, be the literature on benzene itself. The simplest and most symmetrical of the aromatic molecules, benzene, was also the first to be tackled in first-principles adsorption studies within the slab-based approach. The earliest such study emerged from the group of Hafner, and dealt with adsorption on the Al{111} surface (). The lack of d electrons in the substrate material will have allowed considerable computational savings compared with the more interesting transition metal elements, and the avoidance of ferromagnetic materials for this first study was doubtless also economic. Nevertheless, significantly more challenging calculations on the Ni{100}, Ni{110} and Ni{111} surfaces followed from the same group during the course of the very next year (Mittendorfer & Hafner 2001a), together with a contribution on Ni{111} from the present author and co-workers at around the same time. Ongoing investigations from several groups have, by now, extended the set of surfaces studied to include not only simple metals (Al) and ferromagnetic metals (Fe, Co and Ni), but also platinum-group metals (Ru, Rh, Pd, Ir and Pt) and the coinage metals (Cu, Ag and Au). (a) On simple metals Adsorption of benzene on Al{111} was studied theoretically by the group of Hafner, at a coverage of 0.14 ML in a ( √ 7 √ 7)R19.1 surface unit cell (). Several different adsorption sites were considered, but the energetic differences between them were found to be within about 0.01 eV (beyond the reliability of DFT to distinguish). The adsorption energy was calculated as 0.35 eV per molecule, and the vertical distance between the C atoms and the uppermost Al atoms ranged between 3.73 and 3.84, dependent upon adsorption site and azimuthal orientation. In all cases, the molecule was flat-lying, with minimal distortion from its gas-phase geometry. The theoretical results were fully consistent with angle-resolved ultraviolet photoemission spectroscopy (ARUPS), high-resolution electron energy loss spectrscopy and temperature-programmed desorption (TPD) measurements reported in the same work (). The rather weak bonding of benzene to this simple sp metal was accounted for by mutual polarization of the adsorbate and substrate, with no substantial charge transfer from one to the other; a calculated reduction in work function of 0.39 eV was attributed to the same effect (). With such weak bonding, however, it must be questionable to what degree DFT fully captures the important physical properties of the system, especially the VdW interaction between the substrate and the adsorbate. (b) On ferromagnetic metals In contrast to the case of simple metals, adsorption of benzene on transition metals invariably involves a significantly stronger interaction and greater perturbation of both adsorbate and substrate. The first relevant slab-based DFT studies were those of Mittendorfer & Hafner (2001a), who considered adsorption on Ni{111}, Ni{100} and Ni{110}, and of Yamagishi et al., whose work concentrated on Ni{111}. On the Ni{111} surface, benzene is known to form an ordered ( √ 7 √ 7)R19.1 overlayer at saturation coverage, believed, based on photoelectron diffraction (PhD) (), low-energy electron diffraction (LEED) () and ARUPS (), to involve 0.14 ML flat-lying molecules centred over the hcp hollow site, with its C−C bonds oriented along the in-plane 110 directions. At lower coverages, PhD experiments () suggest a clear preference for the molecules to centre instead on the bridge site, with two C−C bonds oriented along the in-plane 211 directions. Both theoretical studies, however, indicated a definite preference for the 211 -oriented bridge site in the high coverage regime, and neither group reported calculations at lower coverage (Mittendorfer & Hafner 2001a;). It remains unclear whether the DFT calculations fail to obtain the correct adsorption site, due to their inadequate inclusion of intermolecular VdW interactions, or whether the experimental site assignments are themselves weak; certainly the interpretations placed on the PhD and LEED data in the high coverage regime are not straightforward (;), and the site sensitivity of the ARUPS experiment () may be insufficient to regard it as a conclusive indicator in isolation. Reported bridge-site adsorption energies of 1.01 eV per molecule (Mittendorfer & Hafner 2001a) or 0.91 eV per molecule are significantly greater than previously calculated for benzene on Al{111}, suggesting a much stronger adsorbate-substrate interaction than on the simple metal. The best hcp-site models yield adsorption energies only around 0.1 eV smaller (as do the best fcc-site models) suggesting that they too involve substantial binding interaction. Indeed, the calculations reveal that the C−H bonds bend away from the surface, making angles with the plane of 19 /28. Furthermore, the aromatic ring expands somewhat, with C−C bonds increasing in length by around 2-4% on average, in a pattern consistent with the symmetry of the adsorption site (Mittendorfer & Hafner 2001a;). Topological analysis of the electron density, within the formalism developed by Bader, confirms that this expansion is correlated with a partial decrease in the effective C−C bond order. The slab-based calculations concur that C atoms of the aromatic ring lie on average around 1.92 higher than the uppermost Ni atoms (Mittendorfer & Hafner 2001a;) in much better agreement with PhD and LEED analyses (;) than earlier cluster-based studies (;Jing & Whitten 1991) that had yielded estimates significantly in excess of 2. Bonding of the benzene molecule to the Ni{111} surface was described in depth, both by Mittendorfer & Hafner (2001a) and by Yamagishi et al.. Both groups essentially concluded that bonding is primarily due to covalent combination of orbitals from the molecule (predominantly the two degenerate HOMOs and the two degenerate LUMOs) with d orbitals from the metal. The resulting mixed orbitals are clearly visible in the calculated density of states (Mittendorfer & Hafner 2001a), in the electron density change upon adsorption (Mittendorfer & Hafner 2001a;) and in the net spin density ) (see figure 2). Overall, the dominance of backdonation of electrons into the LUMO, as opposed to donation from the HOMO, is reflected in the net gain of electrons by benzene, amounting to approximately 0.5 e −. Notably, the magnetic moments of Ni atoms immediately involved in bonding to the molecule are susbtantially reduced (more than halved, relative to the clean surface value) while those not directly involved are hardly affected (Mittendorfer & Hafner 2001a;); the molecule itself gains a slight magnetic moment opposed to the majority spin of the substrate, indicative of weak interaction between the LUMO and the minority-spin sp electrons (;;). On the Ni{100} surface, benzene is known from experiment to form a c(4 4) overlayer (;), studied theoretically by Mittendorfer & Hafner (2001a). In this case, their DFT calculations showed a very clear energetic preference for flat-lying adsorption centred over the hollow site, although the azimuthal orientation of the molecule was less certain: an arrangement in which two C−C bonds lie along one of the 011 directions (with an adsorption energy of 2.13 eV per molecule; see figure 3a) was found to be just 0.04 eV per molecule more stable than one in which two such bonds lie along one of the 001 directions. Clearly, benzene is adsorbed much more strongly to Ni{100} than to Ni{111}, but surprisingly its geometry is no more distorted, nor does it lie any closer to the surface (Mittendorfer & Hafner 2001a). Indeed, apart from the binding energy and the obvious difference in substrate symmetry, the adsorption of benzene on the two flat surfaces of Ni appears to be remarkably similar. Moving away from flat surfaces, however, the story becomes more complex, as exemplified by the calculations of Mittendorfer & Hafner (2001a) for c(4 2) benzene adsorption on Ni{110} (i.e. the highest-symmetry stepped facet for an fcc metal (;Jenkins & Pratt 2007)). Here, the preferred adsorption site was found to bridge across the trough, from one ridge to the next, with a substantial geometric asymmetry (figure 3b): the aromatic ring remains almost planar, but is canted by 5 with respect to the surface plane about an axis lying along the 110 trough direction (Mittendorfer & Hafner 2001a). Similarly, canted adsorption has been noted in calculations by Delle Site & Sebastiani for the adsorption of benzene on Ni{221}, although that stepped surface is of lower symmetry in the first place and features much wider {111} terraces against which the adsorbate lies almost parallel. On Ni{110}, the benzene molecule is itself wider than the {111}-like microfacets, and no such simplifying observation is possible. Nevertheless, Mittendorfer & Hafner (2001a) argue that bonding on the {110} facet occurs through combination of metal d states with the molecular states, just as was the case for the {111} and {100} surfaces; that the calculated adsorption energy of 1.78 eV per molecule is intermediate in magnitude also argues for an interaction of similar origin. Supplementary to the relatively comprehensive studies on Ni described above, a few calculations have also been reported for benzene adsorption on the other ferromagnetic metals, namely Co and Fe. We first note the work of Pussi et al. on the Co{0001} surface. The {0001} facet of an hcp crystal is its only flat face, and is structurally very similar to the {111} facet of an fcc crystal (Jenkins & Pratt 2007). We should not, therefore, be surprised that the adsorption of benzene on Co{0001} shows certain similarities to its adsorption on Ni{111}, most notably that it forms a ( √ 7 √ 7)R19.1 overlayer at saturation coverage and that quantitative LEED analysis () indicates a preference for adsorption in the 1120 -oriented hcp site 3 (the 1120 directions being closepacked in-plane directions analogous to the 110 directions in the fcc-{111} plane (Jenkins & Pratt 2007)). On the other hand, the LEED analysis also indicates that the C atoms of the aromatic ring lie some 2.20 above the uppermost Co atoms, which is considerably higher than on Ni{111} (around 1.92 by experiment and theory (;;Mittendorfer & Hafner 2001a;)) so the analogy should clearly not be over-stressed. In their DFT calculations, Pussi et al. expressly neglected to consider the possibility of adsorption in a truly 1100 -oriented bridge model, which is unfortunate, as this is the closest possible analogue to the 211 -oriented bridge model favoured by DFT on Ni{111} (Mittendorfer & Hafner 2001a;). They do report calculations for seven other plausible site/orientation combinations, however, finding that the 1120 -oriented fcc and hcp models are jointly the most favourable of those considered. On the basis of their LEED analysis, they then discard the fcc site and concentrate only on the 1120 -oriented hcp model. Interestingly, the calculated height of the benzene molecule above the surface in this model is just 1.96, which is much closer to that found on Ni{111}, and in quite poor agreement with the LEED analysis reported in the same work; otherwise, the structural results are in quite good accord, including the now familiar upward bend of the C−H bonds (). On Fe{100}, which is a kinked bcc surface (;Jenkins & Pratt 2007), Sun et al. (2007a,b) report a preference for adsorption of benzene in the hollow site, oriented with two of its C−C bonds aligned along one of the 001 directions (i.e. exhibiting the same symmetry as on the flat fcc Ni{100} surface (Mittendorfer & Hafner 2001a)), although alternative azimuthal orientations were not considered in this instance. It is interesting that the calculated adsorption energy of 1.07 eV per molecule on Fe{100} is much lower than the value of 2.13 eV obtained by Mittendorfer & Hafner (2001a) in the case of Ni{100}. Induced spinpolarization of the adsorbate molecule was found to be highly sensitive to the adsorption site, and included distinct majority-and minority-spin components (a,b). Higher coverage 0.25 ML tilted geometries have also been explored by Sun et al. (2008b) within a (2 2) unit cell, aiming to explain changes in spin-polarization at the onset of multilayer growth. (c) On platinum-group metals Considerable attention has also been devoted to the adsorption of benzene on the platinum-group metals, not least because of their role in catalytic hydrogenation or dehydrogenation of aromatic compounds. Among the earliest first-principles calculations for such an adsorption system were those reported as part of a combined LEED/DFT study of deuterated benzene on Ru{0001} by Held et al.. In that work, a ( √ 7 √ 7)R19.1 overlayer was observed experimentally, and an equivalent perodicity adopted in the theoretical investigation. Analysis of the LEED data indicated adsorption at the hcp site, with the molecule oriented to have its C−C bonds aligned along 1100 directions (i.e. differing from the orientation preferred in hcp sites on Ni{111} and Co{0001}). DFT calculations were performed for only this single adsorption model, producing results in excellent agreement with the LEED structural analysis. For instance, the height of the C atoms above the uppermost Ru atoms was calculated by DFT to be 2.10, to be compared with 2.04 from LEED. Most significantly, this work was the first to provide experimental evidence for the strong outward deflection of the C−D bonds; in LEED, three C−D bonds formed angles of 9 with the surface plane, and three others made an angle of 22, whereas DFT predicted corresponding angles of 14 and 24 ; lateral positions of the D atoms were, however, difficult to determine with accuracy from the LEED data (). Notwithstanding zero-point energy effects, it is reasonable to assume that similar results would hold for non-deuterated benzene; the deuterated form was used in these experiments to exploit the stronger scattering of electrons by deuterium relative to hydrogen. The calculated adsorption energy of 1.31 eV per molecule is rather higher than the values calculated for adsorption on Ni{111} (variously 0.91 eV per molecule or 1.01 eV per molecule (Mittendorfer & Hafner 2001a)), though still considerably less than that for adsorption on Ni{100} or Ni{110} (2.13 and 1.78 eV per molecule, respectively (Mittendorfer & Hafner 2001a)). Adsorption of benzene on the {111} surfaces of Pt, Pd and Rh has been comprehensively addressed in a series of studies by Saeys et al. (2002Saeys et al. (, 2003, by Morin et al. (2003bMorin et al. (, 2004aMorin et al. (,b, 2006 and by Orita & Itoh (2004a). All of these studies assumed a (3 3) overlayer, corresponding to a lower coverage than the ( √ 7 √ 7)R19.1 calculations described above and reveal a consistent preference for adsorption in the 211 -oriented bridge geometry relative to the 'next best' 110 -oriented hcp model. The actual adsorption energies suffer from a fair degree of variation between different studies, however, so the work by Morin et al. (2004a), in which the three different substrates are studied together, is the best place to look for trends: these authors report adsorption energies of 0.90 and 0.67 eV per molecule for the competitive bridge and hcp structures on Pt{111} (cf. 1.21 and 0.78 eV per molecule in the work of Saeys et al., energies of 1.19 and 1.03 eV per molecule for the same structures on Pd{111} (cf. 1.43 and 1.17 eV per molecule in the work of Orita & Itoh (2004a)) and energies of 1.53 and 1.51 eV per molecule on Rh{111}. Thus, the absolute adsorption heat increases on changing substrate from Pt to Pd to Rh, while the relative difference between the two most-favoured models decreases to the point of negligibility. By far, the highest adsorption energy reported for benzene on any transition metal substrate, however, is the value of 2.88 eV calculated recently by Yamagishi et al. for adsorption on Ir{100}. Here, the molecule adopts a flat-lying geometry, centred over the hollow site in an assumed c(4 4) arrangement, with two of its C−C bonds oriented along one of the 001 directions. The orientational preference is thus opposite to that found by Mittendorfer & Hafner (2001a) on the Ni{100} surface, where two of the C−C bonds lay along one of the 011 directions, although in both cases the calculated energy differential is less than 0.05 eV per molecule. The adsorption energy, it should be noted, has been adjusted to include the energy needed to lift the (1 5) reconstruction of the clean Ir{100} surface and would otherwise be somewhat greater. Although much higher than for the corresponding {111} surface the adsorption energy of 2.03 eV per molecule calculated by Orita & Itoh (2004a) for benzene on Pd{100} is hardly comparable with that on Ir{100}. In comparison to the flat {111} and {100} surfaces of platinum-group metals, the stepped {110} surface facet has gained much less attention from theorists. We are aware of only one investigation in this area, reported by Favot et al. and relating to the adsorption of benzene on Pd{110}. Their paper does not mention the value obtained for the adsorption energy, and it is worth noting that gradient corrections are not included in the exchange-correlation functional, but nevertheless the calculated geometry is entirely reasonable in comparison with results for adsorption on Ni{110} (Mittendorfer & Hafner 2001a). (d) On coinage metals Adsorption on the coinage metals typically involves a major contribution from the substrate sp electrons, the d-band being relatively inert due to its position well below the Fermi level. We might therefore expect benzene adsorption on these substrates to be somewhat intermediate between the cases of simple and transition metals discussed at length above. On the Au{100} surface, however, Chen et al. report a surprisingly high adsorption energy of 1.92 eV per molecule in a hollow site, very nearly independent of orientation; other sites are found to be considerably less stable. The calculated height of the C atoms above the uppermost Au atoms is reported as 2.38 for the marginally most stable hollow site model (with two C−C bonds aligned along one of the 011 directions) and 2.22 for the other (with two C−C bonds aligned along one of the 001 directions); angles of deflection for the C−H bonds are 13 and 16 from the surface plane for these two models, respectively (). Significant electron transfer, from adsorbate to substrate, of around 0.7 e − per molecule is also indicative of a rather strong bonding interaction (). On Cu{100}, the same group reports similarly large adsorption energies in the range 1.95-2.28 eV per molecule for flat-lying benzene in the hollow site at various coverages; the calculated height of the C atoms above the Cu atoms is in the range 2.00-2.06, while the C−H bonds are deflected outwards to make an angle of around 15 with the surface plane (). Furthermore, an extremely large electron transfer from substrate to adsorbate, of around 3.5 e − per molecule, is reported, which must surely be unphysical. Indeed, earlier DFT calulations by Lorente et al. had produced a much more reasonable adsorption energy for benzene on Cu{100}, of just 0.68 eV per molecule, with the adsorbate located in the hollow site and oriented to have two C−C bonds parallel to one of the 011 directions. The geometry calculated by Lorente et al. also differs considerably from that provided by Chen et al., in that the C atoms lie rather further from the uppermost Cu atoms, at a height of 2.23, and the outward deflection of the C−H bonds amounts to only 8 from the surface plane. Finally, it is noteworthy that the calculated magnitude and direction of electron transfer in the work of Lorente et al. is entirely in line with expectations. It therefore seems that the calculations of Chen et al. (2005Chen et al. (, 2006 for benzene adsorption on the Au{100} and Cu{100} surfaces may suffer from some significant systematic error, possibly related to the use of the LDA functional rather than one of the more reliable GGA functionals (i.e. they overestimate the covalent contribution to adsorbate-substrate binding). Even weaker binding has been calculated for benzene on Cu{111}, Ag{111} and Au{111}, where Bilic et al. report maximum adsorption energies of 0.03, 0.05 and 0.08 eV per molecule, respectively, assuming a (3 3) overlayer. As those authors point out, adsorption in these systems is likely to be dominated by physisorptive VdW effects not captured within the DFT formalism, so the details of calculated atomic and electronic structure are of limited relevance except in demonstrating a lack of chemisorptive bonding and a relatively featureless lateral potential energy surface. Similarly weak adsorption (0.05 eV per molecule) has also been reported by Schravendijk et al. for benzene on Au{111}, while slightly higher adsorption energies of 0.24 and 0.40 eV per molecule have been calculated for benzene on Cu{110} by Bilic et al. and Atodiresei et al. (2008a,c), respectively. A much higher benzene adsorption energy of 1.13 eV per molecule has also been claimed by Rogers et al. for the Cu{110} case, but it is notable that this unexpectedly high value is again associated with the use of an LDA functional; while it lies close to the experimental value, it seems likely that it does so because the lacking VdW interaction is fortuitously compensated by exaggerated covalent bonding. Polycyclic aromatic adsorbates When two benzene rings are fused along an edge, with the elimination of four hydrogen atoms, each ring in the resulting molecule continues to satisfy the Hckel rule and is thus aromatic. Indeed, fusing any number of benzene rings in similar fashion will result in an aromatic compound, and so a whole class of polycyclic aromatic molecules may be envisaged. 4 The lower orders of this sequence include linear arrangements of the fused rings (e.g. naphthalene, anthracene, tetracene and pentacene) as well as nonlinear arrangements (e.g. phenanthrene, pyrene and chrysene). A limited number of first-principles studies have addressed the adsorption of these larger molecules on metal surfaces, which we now summarize. Utilizing a (4 3) unit cell, Morin et al. (2004b) calculate an adsorption energy of 1.37 eV per molecule for naphthalene on Pt{111} in the preferred geometry (where each ring is positioned similarly to the 211 -oriented bridge model favoured by benzene). Santarossa et al. determined a very similar adsorption energy of 1.31 eV per molecule for naphthalene on Pt{111} within their slab calculations of (6 6) overlayers. Additional calculations for adsorption on Pt{111}, Pd{111} and Rh{111} were performed within a cluster-based approach, and although exhibiting some finite size effects nevertheless give an interesting insight into chemical trends; adsorption energies of 1.51, 1.29 and 2.86 eV per molecule were calculated for the three substrates, respectively (). In line with the findings of Morin et al. (2004a) for benzene, the work of Santarossa et al. reveals a substantially higher adsorption energy for naphthalene on Rh{111} when compared with either Pt{111} or Pd{111}. (b) Anthracene In addition to benzene and naphthalene, Morin et al. (2004b) also studied the adsorption of anthracene (three linearly fused benzene rings, C 14 H 10 ) on Pt{111}, finding an adsorption heat of 1.79 eV per molecule within a (5 3) unit cell; in this instance, a geometry with each ring positioned by analogy with benzene and naphthalene (i.e. in a 211 -oriented bridge arrangement) was assumed, rather than determined. It is evident that the DFT adsorption energies of benzene, naphthalene and anthracene calculated by Morin et al. (2004b) (i.e. 0.90, 1.37 and 1.79 eV) vary fairly linearly with the number of C atoms present. Deviations from precise linearity, however, arise owing to a misfit between the ring spacing of the polycycle 4 It is important to point out that while some polycyclic aromatic compounds contain a total of 4n + 2 electrons across the entire molecule (e.g. naphthalene, C 10 H 8 ) this is not the absolute requirement that it would be for monocycles; in general, polycyclic aromatic compounds are those for which each of the constituent monocycles is aromatic in at least one resonance structure of the polycyclic molecule, and consequently some such aromatic compounds will have a total number of electrons differing from 4n + 2 (e.g. pyrene, C 16 H 10 ). and the lattice spacing of the substrate and should be expected to become increasingly apparent as the size of the molecule increases. Indeed, using a simple model for the degree of misfit, and incorporating terms representing the distortion of both molecule and surface, Morin et al. (2004b) estimate covalent chemisorption energies of 1.3 and 0.7 eV per molecule for tetracene and pentacene (consisting, respectively, of four and five linearly fused benzene rings). Full DFT calculations to confirm these predictions are still awaited. Interestingly, calorimetric experiments by Campbell and co-workers (;) indicate that the DFT calculations of Morin et al. (2004b) underestimate the adsorption energies of benzene and napthalene on Pt{111} by approximately 0.14 eV per C atom (figure 4). Assuming that this degree of error holds true for larger molecules (which seems reasonable, given that it most likely arises owing to missing VdW interactions within the DFT formalism), one can suggest supplementing the energies calculated and predicted by Morin et al. (2004b) with 0.84, 1.40, 1.96, 2.52 and 3.08 eV for molecules containing 6, 10, 14, 18 and 22 C atoms. Thus, the 'empirically corrected' adsorption energies would become: 1.74 eV for benzene, 2.77 eV for naphthalene, 3.75 eV for anthracene, 3.82 eV for tetracene and 3.78 eV for pentacene. Intriguingly, such a sequence suggests that adsorption heats become more or less constant for the C 14, C 18 and C 22 compounds, as the increasing contribution of the VdW interaction is offset by the greater misfit and distortion associated with the chemisorption bond. The work of Dou et al. reveals a preference for a flat-lying adsorption geometry on Cu{100} in which the fused benzene rings are located above hollow sites, oriented such that two C−C bonds from each lie along one of the 011 directions, similar to the geometry determined for benzene itself by Lorente et al. on the same substrate. The calculated adsorption energy in this model is 2.44 eV per molecule (), again broadly consistent with the value of 0.68 eV calculated previously for a single benzene ring (). A very slight outward bend is apparent in the two terminal rings, amounting to a maximum vertical separation of 0.20 between the lowest and highest lying C atoms; the height of the molecule above the surface is in the region of 2.20 (). On Ru{1010}, Lu et al. report two competitive adsorption geometries for flat-lying tetracene, aligned with its long axis either parallel or perpendicular to an in-plane 1120 direction (adsorption energies of 4.23 and 4.19 eV per molecule respectively; see figure 5). In the 1120 -oriented case, the molecule lies along and slightly to one side of a surface ridge, with its centre of mass located above a three-fold hollow site and exhibiting a slightly concave internal geometry (i.e. the ends of the molecule bow a little away from the surface); in the 0001 -oriented case, the centre of mass is located above a ridge bridge site, with the molecule spanning across three ridges in all and exhibiting a slightly convex internal geometry (i.e. the ends of the molecule bow a little towards the surface). Scanning tunnelling microscopy (STM) images presented in the same paper provide good evidence for substantial (approximately equal) occupancy of both conformations on the surface ). (d) Pentacene Finally, for this section, we turn to the adsorption of pentacene (five linearly fused benzene rings, C 22 H 14 ), which has been studied by means of DFT on Al{100} by Simeoni et al., on Au{100} by Lee & Yu Ferretti et al. and on Fe{100} by Sun et al. (2008a). On the simple and coinage metals, binding is expected to be relatively weak, as indeed borne out by calculated chemisorption energies of 0.32 eV per molecule for Al{100} () and 0.28 eV per molecule for Au{100} (Lee & Yu 2005;) when employing a GGA functional. Unsurprisingly, the use of LDA functionals yields very much higher chemisorption energies of 2.42 eV per molecule for Al{100} () and 3.21 eV per molecule for Au{100} (Lee & Yu 2005;), which both groups involved recognize as unphysically high. Doubtless the GGA values are themselves too low, owing to missing VdW interactions (for a point of comparison, experiment indicates an adsorption energy of 1.14 eV per molecule for pentacene on Au{111} ()) but at least they are likely to reproduce geometries and the electronic features of chemisorption with reasonable accuracy. Ferretti et al., for example, present a detailed and convincing comparison between their calculated GGA electronic structure and that obtained via ARUPS experiments. The various LDA calculations, on the other hand, almost certainly represent spuriously strong covalent chemisorption, featuring highly distorted adsorbate molecules and/or anomalously short adsorbate-substrate distances (;Lee & Yu 2005;;). Unsurprisingly, the calculated adsorption energy for pentacene on Fe{100} is genuinely high, reported by Sun et al. (2008a) as 3.99 eV per molecule within the GGA (cf. 1.07 eV and 2.46 eV per molecule for benzene and anthracene, calculated by the same group). Heterocyclic aromatic adsorbates Thus far, we have considered the adsorption of benzene and of molecules consisting of fused benzene rings. In all these cases, covalent binding to the metal surface involves the whole molecule and is, to that extent, an essentially delocalized affair. In general, all of these species seem to adopt a flat-lying or nearly flatlying geometry, in order to maximize not only the delocalized adsorbate-substrate covalent interaction, but also the VdW interaction with the surface. In contrast, the class of heterocyclic aromatic compounds involves rings containing at least one non-carbon atom. Here, the symmetry of the ring is broken, and the possibility exists that one or more of the ring atoms may interact significantly more or less strongly with the substrate than do the others. Consequently, the geometry of the molecule is likely to be tilted to some degree, even on a perfectly flat surface. Among the simplest of the heterocyclic aromatic molecules are six-membered rings containing one or more non-hydrogenated nitrogen atoms (e.g. pyridine and pyrimidine), five-membered rings containing a hydrogenated nitrogen atom (e.g. pyrrole) and five-membered rings containing a non-hydrogenated oxygen or sulphur atom (e.g. furan and thiophene). Polycyclic heteroaromatics include examples where only a single ring is heterocyclic (e.g. quinoline, indole) and others where several are (e.g. purine). As regards the adsorption of these species on metal surfaces, only thiophene has attracted sustained attention from theorists, supplemented by isolated studies on pyridine and pyrrole. The adsorption of furan and pyrimidine on metals appears to have been ignored in the DFT literature to date. (a) Pyridine and pyrrole The pyridine (C 5 H 5 N) and pyrrole (C 4 H 4 NH) molecules together highlight an important aspect of heterocyclic aromatic chemistry, namely the issue of basicity. In the case of the six-membered pyridine ring, the non-hydrogenated N atom employs two electrons in forming bonds with neighbouring C atoms, contributes one electron to the system and retains its two remaining electrons as a lone pair; the localization of non--bonding electrons on the N atom renders the molecule basic. Conversely, in the case of the five-membered pyrrole ring, the hydrogenated N atom employs three electrons in forming bonds with neighbouring C and H atoms and contributes its two remaining electrons to the system; the complete delocalization of these last two electrons renders the molecule non-basic. The adsorption of pyridine on Cu{110} and Ag{110} has been studied by Atodiresei et al. (2008b), who report that flat-lying geometries are strongly disfavoured in comparison with upright geometries bonding via the N lone pair (i.e. the HOMO). On both substrates, they find a preference for the molecular plane to lie parallel to the 001 surface direction with DFT adsorption energies of 0.76 eV for Cu{110} and 0.45 eV for Ag{110}. In these two instances, therefore, the basicity of pyridine dominates its binding to the surface, preventing any significant interaction through the aromatic ring itself. We note, in passing, that these authors make plausible estimates of the missing VdW contributions to the adsorption energies of 0.21 and 0.15 eV per molecule in the most stable geometries on Cu{110} and Ag{110}, respectively, based upon a semi-empirical correction scheme proposed by Grimme. Abdallah et al. report calculations for pyridine adsorption on Mo{110}, a flat bcc surface (;Jenkins & Pratt 2007), in which the strongest binding is found for a flat-lying adsorbate geometry with the N atom and the two 'meta' C atoms located in near-atop sites (adsorption energy 1.54 eV per molecule). Upright models were found to bind far less strongly (with a maximum reported adsorption energy of just 0.66 eV per molecule), although the authors suggest that such a state may become populated at high coverage (). For the non-basic pyrrole molecule, Abdallah & Nelson report a clear preference for flat-lying geometries on Mo{110}, centred approximately over the hollow site, with binding energies in the vicinity of 1.30 eV (varying with azimuthal orientation). The molecule displays a marked outward deflection of the C−H and N−H bonds, reminiscent of benzene on transition metal surfaces. (b) Thiophene In contrast to the, respectively, basic and non-basic natures of pyridine and pyrrole, thiophene (C 4 H 4 S) may be considered to exhibit both basic and non-basic characteristics simultaneously. Within the five-membered thiophene ring, the non-hydrogenated S atom employs two electrons in forming bonds with neighbouring C atoms, contributes two electrons to the system and retains two more electrons as a lone pair; the donation of two electrons from the S atom into the delocalized system is indicative of a non-basic molecule, but the retention of a localized lone pair on the S atom implies a residual basic character. Early calculations by Blyth et al. for the adsorption of thiophene on Al{111} indicated very weak binding in a flat-lying geometry; the calculated adsorption energy of 0.54 eV per molecule is only slightly higher than that obtained for benzene on the same substrate (), and the authors found little evidence of substantial electron transfer between substrate and adsorbate. On the Ni{100} surface, by way of contrast, Mittendorfer & Hafner (2001b) calculated a very high adsorption energy of 2.57 eV per molecule, associated with a structure in which the aromatic ring is heavily disrupted. Indeed, their optimum geometry sees one of the two C-S bonds broken, enabling each of these atoms to more comfortably occupy neighbouring bridge sites; the molecule has become, in effect, a highly curved but non-closed C 4 -S chain, with no remaining evidence of aromaticity (Mittendorfer & Hafner 2001b). A second, somewhat less stable but fully intact adsorption geometry is also reported, in which the molecule is flat-lying and centred over the hollow site with its S atom in a near-atop location; the calculated adsorption energy in this case is 2.23 eV, and the molecule retains its aromaticity, albeit with quite strong geometric distortion (Mittendorfer & Hafner 2001b). The split-ring state has been suggested by the same authors as a possible intermediate in the desulphurization of thiophene, and moderate reaction barriers for such a route have indeed been calculated (Mittendorfer & Hafner 2003). It appears that all of these calculations were performed without spin polarization, but qualitatively similar results were subsequently obtained in spin-polarized calculations for thiophene adsorption structures on Ni{100} by Orita & Itoh (2004b) (adsorption energy 2.88 eV in the split-ring structure, 2.46 eV in the intact molecular structure, both at lower coverage than the earlier work). On the Pd{100} surface, only the flat-lying intact molecular adsorption mode was found to be stable, with a calculated adsorption energy of 2.20 eV per molecule (Orita & Itoh 2004b), while on the Cu{100} surface the same authors report very low adsorption energies for thiophene, with several flat-lying geometries yielding values in the range 0.30-0.50 eV per molecule (Orita & Itoh 2004b). The adsorption and dissociation of thiophene on Ni{110} has been studied theoretically by Morin et al. (2003a), who determine the most stable adsorption geometry to be one in which the molecule is flat-lying and bridges from one surface ridge to the next (adsorption energy 2.02 eV per molecule, from spin-polarized calculations). Two alternative geometries, in which the molecule exhibits different azimuthal orientations, are also reported to have relatively high adsorption energies (1.49 and 1.68 eV per molecule), and furthermore would dissociate trivially (activation barriers below 0.20 eV) into an acyclic thiolate, and thence ultimately to a S adatom and a hydrocarbon. The authors argue, therefore, that adsorbing molecules landing on the surface in one of these reactive geometries will dissociate more readily than diffusing into the stable molecular state (a). Recently, Sony et al. have investigated the adsorption of thiophene on Cu{110}, making use of an exchange-correlation functional specially formulated with the aim of accounting for VdW interactions (). Indeed, the calculated adsorption energy of 0.50 eV per molecule is claimed to arise solely from the VdW interaction (), consistent with an equilibrium adsorbate-substrate distance of nearly 3. Further examination of the merits of this interesting development lie beyond the scope of the present review. Substituted aromatic adsorbates The effect of substituent groups on the adsorption of aromatic molecules might be expected to be twofold, arising owing to either electronic or steric considerations. Hydroxy (-OH) or methoxy (-OCH 3 ) groups, for example, are generally regarded as electron-donating, while carboxylic (-COOH) groups are electron-withdrawing, and it is interesting to consider whether these attributes are recognizable in the influence they exert on aromatic adsorption. On the other hand, the sheer spatial extent of these different groups will inevitably itself have some bearing on the degree to which an aromatic ring can lie flat on the surface without placing significant internal strain on the molecule. Whether the electronic or the steric effects dominate is, of course, a key question for theory to address. (a) Phenol and anisole The hydroxy group is among the simplest of electron-donating moieties that might be considered as substituents to an aromatic ring. Consequently, phenol (C 6 H 5 OH) has been the most frequent example of substituted aromatic adsorption tackled within the first-principles DFT approach. The first to do so were Delle Site et al., who examined several different adsorption sites and orientations for flat-lying phenol on Ni{111}. The most remarkable aspect of their results is the lack of any strong substituent effect; the molecule favours adsorption at a bridge site with two C−C bonds oriented along 211 directions and only a relatively small sensitivity to which C atom binds the -OH group. From a structural perspective, the aromatic ring distorts in fashion very similar to benzene, with a slight increase in the average C−C bond lengths and an outward bend of the C−H bonds. The C−O bond is also deflected away from the surface, indicating a repulsive interaction that accounts for an adsorption energy (0.91 eV) a little more than 0.1 eV less than that calculated by the same authors for benzene (Delle ). Various geometries for phenol adsorbed with a vertical ring plane, binding to the surface via its O atom, have been calculated on Ni{111}, Ni{110} and Ni{221}, but all have adsorption energies much smaller than those for the flat-lying geometry (). Orita and Itoh (2004a), meanwhile, studied theoretically the adsorption of phenol on Pd{111} and Pd{100}. On the Pd{111} surface, they report an adsorption energy of 1.39 eV per molecule for phenol, compared with 1.43 eV per molecule for benzene, while on the Pd{100} surface the adsorption energy of phenol is reported as 1.94 eV per molecule, compared with 2.04 eV per molecule for benzene (Orita & Itoh 2004a). As on Ni{111}, it seems likely that the steric effect of the -OH group is primarily responsible for reducing the overall strength of adsorbate-substrate binding. The methoxy group represents another relatively simple electron-donating moiety, whose substitution for a hydrogen atom might be expected to influence the reactivity of an aromatic ring. The adsorption of anisole (C 6 H 5 OCH 3 ) has therefore been studied theoretically on Pt{111} by Tan et al., with a view to investigating electronic versus steric effects. When adsorbed with the aromatic ring in a flat-lying geometry, the phenyl-O bond was deflected away from the surface by around 12, while the O-methyl bond remained nearly parallel to the surface. A very similar geometry has since also been reported from cluster studies of anisole on Pt{111} (). The adsorption energy was calculated by Tan et al. to be 0.76 eV per molecule, somewhat less than the values in the range 0.9-1.2 eV per molecule calculated for benzene on the same substrate by other groups (;a). Crucially, the electron density redistribution upon adsorption was found to resemble closely that expected for a regular benzene ring and to bear very little resemblance to the HOMO and LUMO of gas-phase anisole ( figure 6). This was interpreted as evidence that molecular distortion, driven by steric effects, interferes with the inductive electronic influence of the -OCH 3 group (). In both the phenol and anisole cases, effects due to the electron-donating character of the -OH or -OCH 3 groups are essentially negligible, in part because distortion of the molecule essentially decouples the orbitals of the substituent from those of the aromatic ring, and in part because electron donation and withdrawal owing to interaction with the surface is dominant over any intramolecular phenomena. Steric considerations, on the other hand, not only account for much of the molecular distortion, but also explain the generally weaker binding of the molecule to the surface compared with benzene. (b) Miscellaneous molecules Ghiringhelli & Delle Site have performed calculations for the adsorption of phenylalanine (C 6 H 5 CH 2 CHNH 2 COOH) on various metallic substrates. On coinage metal surfaces (Cu{111}, Ag{111} and Au{111}), they find a preference for adsorption geometries in which the molecule binds via its N atom, with the aromatic ring elevated well away from the surface; it is possible that DFT underestimation of VdW interaction may be an important consideration here. On transition metal surfaces (Ni{111}, Pd{111} and Pt{111}), they report strong bonding of the molecule to the surface via both the N atom and the aromatic ring. Indeed, the molecule exhibits considerable internal strain in order to achieve this favourable configuration. The adsorption of two even more complex aromatic molecules has been studied on Rh{111} by Barbosa & Sautet, the first containing a benzyne (C 6 H 4 ) ring and the second a pyridyne (C 5 H 3 N) ring, each with methyl and pyroglutamic substituents attached in place of the two missing H atoms. In both cases, the preference is for binding via the aromatic ring, stabilized further by bonding through the pyroglutamic side group; the authors argue this latter effect ensures that only one side of the ring can attach to the surface, with profound consequences for enantioselective catalysis (Barbosa & Sautet 2003). Coadsorption and reaction A small number of theoretical studies have considered coadsorption systems involving benzene. Unsurprisingly, the focus of such work has typically been the elucidation of interactions between the coadsorbed species, considered from both the energetic and the electronic points of view. In addition, some efforts have been made towards a theoretical understanding of simple reactions involving aromatic molecules, for the most part focusing upon the transition states, intermediates or reaction products of benzene hydrogenation and dehydrogenation. This final substantive section summarizes these investigations. (a) Benzene coadsorption with O or CO Although it is relatively rare for benzene to form ordered overlayers on metal surfaces, it is notable that coadsorption with other species can sometimes induce ordering to occur. A classic example is to be found in the coadsorption of benzene with either O atoms or CO molecules on Ni{111}, which in either case leads to a (2 √ 3 2 √ 3) overlayer. The DFT calculations of Yamagishi et al. reveal that the preference of the non-aromatic adsorbate to reside in a hollow site forces the benzene molecule to likewise occupy such a site, despite the calculated preference for bridge-site adsorption in the single-component system (the fcc site is marginally preferred when the coadsorbate is O, the hcp is preferred when it is CO). Furthermore, the driving force towards formation of an intimately coadsorbed overlayer (as opposed to phase separation) was found to differ in the two cases. When coadsorbed with O, the dominant effect opposing segregation is strong repulsion between the adatoms at high local coverage, with repulsion between benzene molecules providing a small additional contribution, and attractive interactions between benzene and the adatoms being almost negligible. When coadsorbed with CO, on the other hand, the repulsion between benzene molecules plays an equal role with the attraction between benzene and carbon monoxide, and the repulsion between the non-aromatic molecules is of only minor importance (). Morin et al. (2004a) meanwhile tackled the (3 3) structure formed by coadsorption of benzene with CO on Rh{111}, also concluding that the marked preference of the non-aromatic adsorbate to occupy a hollow site rather than a bridge site drives the benzene molecule to occupy such a site itself. (b) Dehydrogenation of benzene Removal of a single H atom from benzene results in the phenyl radical (C 6 H 5 ), and removal of a second H atom from an adjacent C atom yields singlet ortho-benzyne (C 6 H 4 ). In general, both species are plausible products of benzene dehydrogenation on metal surfaces, and a particularly interesting instance is to be found on Ir{100}. On that substrate, benzene adsorbs at low temperature in a disordered flat-flying fashion, but upon heating to 465 K a c(2 4) LEED pattern develops coincident with evolution of hydrogen (). Stoichiometric considerations strongly imply that the remaining surface species is benzyne rather than phenyl, and indeed quantitative analysis of the LEED-IV spectra indicates the ortho form of the molecule, bonding through the dehydrogenated C atoms and inclined with its ring plane at approximately 47 to the surface. Subsequent first-principles calculations by Yamagishi et al. (2002Yamagishi et al. (, 2003 yielded an adsorption geometry (figure 7) in remarkable agreement with the experimental observation (e.g. tilt angle 48 ) and analysis of the electronic structure demonstrated that adsorbate-substrate binding was due in part to bonds involving the dehydrogenated C atoms, and in part due to bonding through the orbitals of the aromatic ring. When coadsorbed in a c(4 4) arrangement with C, calculations show that the presence of adatoms in neighbouring hollow sites forces benzyne to adopt a fully upright geometry, in which the orbitals of the aromatic ring make a negligible contribution to the binding (). On Cu{100}, by way of contrast, calculations by Bocquet et al. indicate that both phenyl and benzyne prefer a fully upright geometry in the absence of any coadsorbates. Furthermore, comparison of simulated inelastic tunnelling spectroscopy (IETS) with the corresponding experimental spectra was presented as evidence favouring the existence of phenyl rather than benzyne after STM-induced dehydrogenation of benzene (). The same group has recently reported calculated transition states for C−H scission in benzene on Cu{111}, Cu{100} and Cu{110}, finding that the stepped surface presents the lowest reaction barrier (1.70 eV on Cu{110}), while the two flat surfaces yield rather higher barriers (1.85 eV on Cu{100}; 2.20 eV on Cu{111}) ((Lesnard et al., 2008. Further dehydrogenation of phenyl to yield benzyne is reported to involve a barrier of just 1.58 eV on Cu{100}, but is not believed to be readily surmounted in the non-thermal reaction conditions imposed by STM tip voltage pulses ((Lesnard et al., 2008. (c) Hydrogenation of benzene The stepwise hydrogenation of benzene to 1,4-cyclohexadiene (C 6 H 8 ) has been studied theoretically by Mittendorfer & Hafner and Hafner, who report an activation barrier of 0.73 eV for addition of the first H atom and 0.40 eV for addition of the second; the first reaction is asserted to be the rate-determining step in the full hydrogenation to cyclohexane (C 6 H 12 ), but no further barriers are reported to support this claim (Mittendorfer & Hafner 2002;Hafner 2008). On the Pd{111} and Pt{111} surfaces, Morin et al. report energies for a comprehensive set of intermediates en route from benzene to cyclohexane, albeit without calculating any reaction barriers. Nevertheless, invoking the Brnsted-Evans-Polanyi picture, whereby activation barriers are linearly related to reaction enthalpy, these authors argue that the highly endothermic first hydrogenation step is rate limiting on Pd{111}, whereas the same step is only moderately endothermic and probably not rate limiting on Pt{111} (); earlier cluster calculations had indeed already identified the fifth hydrogenation step as rate limiting on this latter surface ((Saeys et al., 2005. Conclusions Adsorption of benzene has been quite thoroughly, though not yet exhaustively, studied on a variety of different metal substrates. In general, the molecule adopts a flat-lying, or very nearly flat-lying, geometry, binding to the surface through donation of electrons from one or both of its two degenerate HOMOs and back-donation into one or both of its two degenerate LUMOs. Among transition metal substrates, adsorption energies appear to be substantially stronger on the fcc-{100} facet (typically greater than 2.0 eV) than on the fcc-{111} facet (typically less than 1.5 eV); non-fcc substrates have been considered only sporadically. On the coinage metals, in contrast, binding energy owing to covalent donation/back-donation is much weaker (at least when calculated using GGA functionals) and VdW interactions likely play a dominant role. Efforts to include such non-covalent binding within DFT-based calculations show some promise, but are far from routinely applied. The adsorption of polycyclic aromatic molecules has also been subject to a certain amount of theoretical attention, in particular focusing upon naphthalene, anthracene, tetracene and pentacene. In general, the covalent contribution to the binding may be expected to increase with the addition of each successive ring to the molecule, but lack of registry with the substrate inevitably compromises this effect. Meanwhile, the role of VdW interactions becomes progressively more important for larger and larger molecules, so the suitability of standard DFT becomes ever more questionable as the number of rings increases. Again, appropriate methods for inclusion of VdW effects will be crucial for further progress in this direction. In the case of heterocyclic aromatic adsorbates, efforts have predominantly been aimed towards pyridine, pyrrole and thiophene. In the former two cases, both flat-lying and vertical geometries have been reported on different substrates, while for thiophene a flat-lying geometry seems to be predominant. Relatively few different substrates have been investigated to date, however, so it would be dangerous to extrapolate trends from such limited data. The adsorption of substituted aromatic molecules raises the question of whether electronic or steric effects are capable of substantially modifying behaviour away from that of benzene. In the case of phenol and anisole, the electron-donating substituent groups (hydroxy and methoxy, respectively) appear to have remarkably little effect on the nature of adsorption. Indeed, there is some evidence that distortion of the molecule upon adsorption to some degree decouples the substituent group from the ring (that is, from the point of view of the electronic structure). Only a small steric effect remains, which slightly reduces the adsorption energy. In other cases, with more complex substituents, the molecule can bond simultaneously through the aromatic ring and through some other part of the molecule. Here, the effect is likely to be highly dependent upon the particular molecule considered, so again it becomes difficult to draw general conclusions. Finally, we note that coadsorption of benzene with other species and surface reactions of benzene have also been subjected to theoretical study over recent years. In the case of coadsorption, the interest lies in understanding how the aromatic and non-aromatic species interact, and the evidence suggests that both attractive and repulsive interactions have a role to play in dictating the coadsorption geometry. As for reactions, the dehydrogenation of benzene to form phenyl or benzyne has been considered on a handful of occasions, as has the hydrogenation towards cyclohexane. Needless to say, both are important topics that warrant much more sustained effort into the future. The author is grateful to The Royal Society for a University Research Fellowship.
Precise phase retrieval under harsh conditions by constructing new connected interferograms To date, no phase-shifting method can accurately retrieve the phase map from a small set of noisy interferograms with low phase-shifts. In this Letter, we develop a novel approach to resolve this limitation under such harsh conditions. The proposed new method is based on constructing a set of connected interferograms by means of simple subtraction and addition operations, in which all the subset of interferograms have the same phase-shift interval of /2. According to this characteristic, this set of connected interferograms can be processed with conventional phase retrieval methods as PCA or AIA obtaining accurate results. The reduction in the RMS errors after using our method reaches as high as 93.7% and 89.3% respectively comparing with conventional PCA and AIA methods under harsh conditions. Both simulation and experiment results demonstrate that the new proposed method provides an effective way, with high precision and robustness against noise, for phase retrieval. into simultaneous dual-wavelength phase-shifted interferometry. However, all of these presented PCA methods still require large number of phase shifted interferograms to maintain sufficient accuracy of phase retrieval. All the above-mentioned phase demodulation algorithms would produce inaccurate results when using few phase-shifted interferograms with high noise level and small phase shifts. To solve these issues collectively, we propose a new method that would resolve these problems by constructing a new set of connected interferograms using simple subtraction and addition operations. The phase shifts of the new connected interferograms have special characteristics, which allow to retrieve the phase by conventional phase retrieval methods directly from these new connected interferograms. Methods In PSI, the intensity distribution of one arbitrary pixel within the nth interferogram can be expressed as where n and k represent the sequence number of phase-shifted interferogram and the respective pixel position and N is the number of interferograms. Additionally, a k and b k represent the background and the modulation amplitude terms, and k and n are the objective phase and the phase shift of the nth interferogram. Finally, the total number of pixels composing an interferogram is K. In our method, extra sets of interferograms could be constructed by subtraction and addition operations shown in Eqs. -. A subtraction operation is first performed between interferograms to obtain intensity difference images by, h is the sequence number of the intensity difference images, and h ∈ , with H the total number of the intensity difference images. It is easy to deduce that H = N(N − 1)/2. Then, an addition operation between interferograms is performed to obtain the intensity adding interferograms as where i, j ∈ with i < j, and g ∈ , the sequence number of the intensity adding images, where G is the total number of the intensity adding images. Again, it is easy to deduce that G = N(N − 1)/2. Note that H = G. Combining the intensity difference with the intensity adding interferograms, we can construct a new connected interferograms set as T where Z is a matrix of size K. These extra sets of connected interferograms could be post-processed to obtain the modulating phase, as demonstrated below. Normalization is a key step of the proposed method. Moreover, in the process of normalization, Fourier transform method 23 is one of essential and important steps. Normalization is performed from all the above connected interferograms. Methods of normalization have been reported in refs 24-26. The resultant normalized connected interferograms are denoted as where Norm() represents the normalizing operator. For Eq., the result of the normalized interferograms can be estimated as k n Similarly, S, − S, A and − A can be estimated as From Eqs. -, it is easy to deduce that the normalized constructed images is also a set of phase shifted interferograms, with phase shifts of ( i + j )/2 − /2, ( i + j )/2, ( i + j )/2 + /2 and ( i + j )/2 +. Given by the subtracting and adding operations between the interferograms, we have more interferograms with more different Scientific RepoRts | 6:24416 | DOI: 10.1038/srep24416 phase shifts. Using this characteristic, we can retrieve the objective phase easily and accurately from these new constructed images using phase retrieval methods, such as the PCA and AIA methods. Our proposed method is based on three steps for phase retrieval. First of all, we use Eqs. - to construct the new connected interferograms set Z. Secondly, normalize these new connected interferograms to get the normalized interferograms Z*. Finally, by means of phase retrieval methods, such as PCA and AIA approaches, the phase map is obtained from these normalized interferograms. Results To prove the effectiveness of the proposed method, we have tested it with simulated fringe patterns. In this simulation, only 8 interferograms are used to retrieve the phase. The phase shifts between fringe patterns are nonlinear and are respectively 0 rad, 0.10 rad, 0.17 rad, 0.20 rad, 0.24 rad, 0.32 rad, 0.35 rad and 0.4 rad. In addition, we have added some additive Gaussian noise to the interferograms with noise-to-signal ratio (NSR) of 30%. In Fig. 1(a), we show one of the simulated fringe patterns, in which the background and the modulation amplitude are respectively equal to The size of the fringe pattern is of 300 300 pixels, and the phase corresponds to (x, y) = 4 − 〈 4〉, where < > is the average operator, and − 1.5 ≤ x, y ≤ 1.5. Figure 1(b) shows the theoretical wrapped phase map, and Fig. 1(c,d) present the obtained wrapped phase map by PCA and AIA methods from the new connected interferograms. Here, we term PCAN and AIAN to represent the new methods of phase demodulation by PCA and AIA methods from the new constructed connected interferograms respectively. According to our proposed method outlined above, 112 new connected interferograms with different phase-shifts were constructed. To quantify the recovered phase error, we have computed the root mean square (RMS) error of the difference between the theoretical phase and the extracted one, which corresponds to 0.202 rad by PCAN method and 0.221 rad by AIAN method as shown in Table 1. The RMS errors by PCAN and AIAN methods are relatively close and small, indicating decent feasibility of our method in this difficult situation. Besides, we study the effect of complicated pattern on the measurement accuracy. As shown in Fig. 2(a), simulated fringe patterns with the size of 300 300 pixels are generated according to Eq., in which the background and the modulation amplitude are the same as mentioned above. The measured phase distributions is set as the where "Peaks" is the peaks function in Matlab. The noise is also set as the additive Gaussian distribution with the NSR of 30%. The results indicate that the proposed method is suitable for complicated pattern. Besides, according to Eqs. - and Fig. 3, the phase shifts of the new connected interferograms are distributed like a ladder and the phase shift interval between each subset image is /2. Moreover, another simulation was performed to study the effect of noise influence on the precision of retrieved phase. Table 1 provides the results that show the NSR of the interferograms ranging from 15% to 30%, with RMS errors from 0.155 rad to 0.202 rad by PCAN method, and from 0.160 rad to 0.221 rad by AIAN method. In Table 1, PCAN8 and AIAN8 represent phase retrieved by PCAN and AIAN methods from 8 original interferograms. It is therefore suggested that, by using PCAN and AIAN algorithms for different NSRs, these retrieved RMS errors would present very limited fluctuation indicating high robustness against noise. From the results above, it is easy to indicate that our method present three advantages as can be used with: small number of interferograms; small phase shift interval between interferograms; high level of noise. Since few original interferograms are used to construct extra sets of connected interferograms, our method generates more information for phase retrieval, hence presenting high robustness against noise. Besides, although the phase shifts of original interferogram is small, each subset images have the same small phase shift interval, and phase shift interval between each subset images is /2, therefore, conventional phase retrieval methods can and, no other method can accurately retrieve the phase. To verify the above simulated results, the proposed method was also employed to perform phase extraction from experimental phase-shifted interferograms. In our experiment, 60 phase shifted interferograms were captured with size of 300 300 pixels. One example of the phase-shifted interferograms is provided in Fig. 4(a), and the phase shifts of the captured interferograms are shown in Fig. 4(b). We first obtained the wrapped phase map by the conventional four-step method using four phase shifted interferograms with respective phase shifts of approximately 0, /2, and 3 /2 rad, which was used as the reference phase, and this phase map is shown in Fig. 5(a). Later, alternative methods e.g. AIA and PCA were employed to obtain the same form of wrapped phase maps from all the 60 interferograms, as shown in Fig. 5(b,c). The performance of our proposed method is also shown superior, especially for the case of using few interferograms with small phase-shifts. For comparison, we selected only 8 interferograms from the first of 60, and successfully obtained a new set of phase maps using the PCAN and AIAN methods versus PCA and AIA methods, as provided in Fig. 6(a-d) and written as PCAN8, AIAN8, PCA8 and AIA8. Here, PCAN8 and AIAN8 represent the phase retrieved by PCAN and AIAN methods from 8 original interferograms, and PCA8 and AIA8 represent the phase retrieved by PCA and AIA methods from the 8 interferograms from the first of 60. Unwrapped phase maps using four-step method (as reference), PCA8 method and PCAN8 method are shown in Fig. 7. Comparing to the reference phase map, it is clearly shown that the phase obtained by PCA8 method appears serious distortion, while the phase obtained by PCAN8 method is nearly the same as the reference. Figure 8 shows the phase distribution of the interferogram cross-section, where red line is the reference value, green line and blue line are the phase of cross section by PCA8 method and PCAN8 method respectively. It is confirmed that the phase of cross section obtained by PCA8 method suffers obvious deviation, while that by PCAN8 method is agreed well with the reference, which indicates that precision of PCAN8 method is much higher than that of by PCA8 method under this harsh condition. In addition, the RMS errors of all the methods with respect to reference are provided in Table 2. Clearly, the AIA and PCA methods using 60 (all) interferograms shows very small RMS errors, indicating great precision of their calculated results that could be ultimately achieved by excessive number of interferograms. However, the precision of phase extraction using the same methods but with only 8 interferograms is rather low, giving RMS errors 1.162 rad and 1.887 rad respectively for AIA8 and PCA8. In contrast, the proposed methods of PCAN and AIAN have demonstrated relatively small magnitude of RMS error as 0.118 rad and 0.124 rad respectively, which is far below than that of AIA8 and PCA8 under the same condition with reduction of 93.7% and 89.3%, hence suggesting high robustness of the proposed method precision against limited number of interferograms with small phase shifts. The main reason for such advantage is that the phase shifts between interferograms are small. Therefore, the proposed method could be more preferable over AIA and PCA methods in case of using few interferograms with small phase shifts. Another advantage of our method is the low sensitivity against noise, since it could also give decent performance from noisy interferograms with the uncertain phase shifts as illustrated in Fig. 3. It is therefore suggested that our method could be also applied under noisy condition. Discussion To analyze the influence of using different numbers of interferograms with our proposed method, we have separately performed the phase retrieval with the first 3, 4, 5, 6, 7 and 8 interferograms. In Fig. 9, the obtained wrapped phases map e.g. PCAN3 refers to phase map obtained from 3 phase-shifted interferograms, and so forth. The RMS errors of PCAN3 to PCAN8 are shown in Table 3, in which all of them are close to 0.12 rad that suggests almost the same precision regardless of the number of interferograms used. In practical applications, our method would be preferable since fewer number of phase shifted interferograms (typically around 3~5 frames) could minimize the effects of vibrations, as well as saving the processing time. However, if the interferograms are found noisy in great extent, then using more phase shifted interferograms to retrieve phase would help improve the precision. Obviously, in this case, it is better to use more frames than 5. Besides, we have tested other linear combinations to construct a new connected interferograms set to retrieve phase. Assume that Z 1 = (− S, A, S, − A, I, − I) T andZ 2 = ( − S, A, S, − A) T, here Z 2 is the same as Z mentioned above, the simulation and experiment calculated data is the same as the calculated data of Figs 1 and 4. The calculated results are obtained by PCAN method. For simulation case, using Z 1 to retrieve phase, the RMS error is 0.219 rad, while using Z 2 to retrieve phase, the RMS error is 0.202 rad. For experiment case, using Z 1 to retrieve phase, the RMS is 0.122 rad, while using Z 2 to retrieve phase, the RMS is 0.118 rad. From both the simulation and experimental results, it is clearly to indicate that using Z 2 is slightly better than Z 1. The main reason is that, for Z 2, the phase shifts distribution are better than Z 1 in the range of . In other words, using Z 2 to retrieve phase, the data is more satisfied the condition of using PCA method. Actually speaking, from the view of input information, Z 1 is more than Z 2, but phase shift of A is i and − A is i +, if we added another set of interferograms B and phase shifts of B is i + /2 as well as − B is i + 3/2, and construct a new set Z 3 = ( − S, A, S, − A, I, − I, B, − B) T, in this case, the obtained result is better than Z 2. Finally, we have tested another interferogram with irregular fringe pattern. As shown in Fig. 10, Fig. 10(a) shows the interferogram with irregular fringe pattern, Fig. 10(b) is the reference wrapped phase, and Fig. 10(c) is the obtained wrapped phase map by PCAN method. The RMS error of the PCAN method is 0.13 rad. The result indicates that the RMS error is small and the proposed method is also suitable for complicated pattern. Conclusion In summary, to date, no other method can retrieve phase accurately under these harsh conditions, such as: a small number of phase-shifted interferograms; the interferogram with strong noise; a very small phase shift interval between interferograms. In this paper, we propose a new method that would resolve these difficulties. The proposed method skillfully constructs a set of new connected interferograms by means of simple subtraction and addition operations, in which each subset images has the same small phase shift interval, but phase shift interval between each subset images is /2. Using this characteristic and combining with some conventional phase retrieval methods, such as PCA and AIA methods, phase can be retrieved easily from these new constructed images. According to the simulated and experimental results, it is proved that the phase can still be obtained with high precision under these harsh conditions.
William Alexander McArthur William Alexander McArthur (1857 – 7 June 1923), was a British Liberal politician and businessman. Biography McArthur was born in Sydney, Australia, the eldest son of Alexander McArthur and his wife Maria Bowden, the second daughter of the Rev. William B. Boyce. McArthur's father was a businessman and politician in Australia and England, becoming MP for Leicester. McArthur was educated privately. On 12 August 1890 at the Trinity Wesleyan Church, Abingdon-on-Thames, Berkshire, he married Florence Creemer (died 24 October 1940), the third daughter of John Creemer Clarke of Wayste Court, Abingdon, and the couple had one son and two daughters. He worked as a merchant like his father, and became a partner in the firm of W. and A. McArthur, Colonial Merchants. He was a Director of the Bank of Australasia. He was Mas Commr. for New South Wales at the Colonial and Indian Exhibition in 1886. McArthur was elected to Parliament for Buckrose at the 1886 general election, with a majority of a single vote, but was unseated on a scrutiny being held and the seat was awarded to the Conservative candidate, Christopher Sykes. He entered Parliament for St Austell in an 1887 by-election, a seat he held until 1908. McArthur served in the Liberal administrations of William Ewart Gladstone and the Earl of Rosebery as a Junior Lord of the Treasury from 1892 to 1895. McArthur died on 7 June 1923 at a private hospital in Sydney, aged 66, and was interred 8 June at South Head Cemetery.
#pragma once #include <stdint.h> enum class CullingMask : uint32_t { NONE = 0, ALL = 4294967295, GEOMETRY = 1, CASCADE_SHADOWMAP = 2, SPOT_SHADOWMAP = 4, CUBE_SHADOWMAP = 8 };
<gh_stars>1-10 import os import pandas as pd def read_datastore(settings, year=None, warm_start=False): """ Access to the land use .H5 data store """ # If `year` is the start year of the whole simulation, or `warm_start` is # True, then land use forecasting has been skipped. This is useful for # generating "warm start" skims for the base year. In this case, the # ActivitySim inputs must be created from the base year land use *inputs* # since no land use outputs have been created yet. # # Otherwise, `year` indicates the forecast year, i.e. the simulation year # land use *outputs* to load. region = settings['region'] region_id = settings['region_to_region_id'][region] usim_local_data_folder = settings['usim_local_data_folder'] if (year == settings['start_year']) or (warm_start): table_prefix_yr = '' # input data store tables have no year prefix usim_datastore = settings['usim_formattable_input_file_name'].format( region_id=region_id) # Otherwise we read from the land use outputs else: usim_datastore = settings['usim_formattable_output_file_name'].format( year=year) table_prefix_yr = str(year) usim_datastore_fpath = os.path.join(usim_local_data_folder, usim_datastore) if not os.path.exists(usim_datastore_fpath): raise ValueError('No land use data found at {0}!'.format( usim_datastore_fpath)) store = pd.HDFStore(usim_datastore_fpath) return store, table_prefix_yr
SickKids: The History of the Hospital for Sick Children by David Wright (review) sion. This book breaks new ground in thinking about how hospital history was shaped by local politics, economics, and social structures. Moreover, Doyle makes a strong case for the idea that pre-NHS health services were more coordinated than has been argued in the past. Doyles work is timely given ongoing concerns about the sustainability of health funding in many parts of the world. Scholars, practitioners, and members of the public would benefit from understanding more about how past generations wrestled with the challenge of improving health and health care systems.
<filename>worldedit-core/src/main/java/com/sk89q/worldedit/function/pattern/RepeatingExtentPattern.java /* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.function.pattern; import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.MutableBlockVector3; import com.sk89q.worldedit.world.block.BaseBlock; import static com.google.common.base.Preconditions.checkNotNull; /** * Returns the blocks from {@link Extent}, repeating when out of bounds. */ public class RepeatingExtentPattern extends AbstractExtentPattern { private final BlockVector3 size; private final MutableBlockVector3 mutable; private BlockVector3 origin; private BlockVector3 offset; /** * Create a new instance. * * @param extent the extent * @param offset the offset */ public RepeatingExtentPattern(Extent extent, BlockVector3 origin, BlockVector3 offset) { super(extent); setOrigin(origin); setOffset(offset); size = extent.getMaximumPoint().subtract(extent.getMinimumPoint()).add(1, 1, 1); this.mutable = new MutableBlockVector3(); } /** * Get the offset. * * @return the offset */ public BlockVector3 getOffset() { return offset; } /** * Set the offset. * * @param offset the offset */ public void setOffset(BlockVector3 offset) { checkNotNull(offset); this.offset = offset; } /** * Get the origin. * * @return the origin */ public BlockVector3 getOrigin() { return origin; } /** * Set the origin. * * @param origin the origin */ public void setOrigin(BlockVector3 origin) { checkNotNull(origin); this.origin = origin; } @Override public BaseBlock apply(BlockVector3 position) { int x = Math.abs(position.getX() + offset.getX()) % size.getBlockX() + origin.getX(); int y = Math.abs(position.getY() + offset.getY()) % size.getBlockY() + origin.getY(); int z = Math.abs(position.getZ() + offset.getZ()) % size.getBlockZ() + origin.getZ(); return getExtent().getFullBlock(mutable.setComponents(x, y, z)); } }
Effectiveness of oral antibiotics for definitive therapy of non-Staphylococcal Gram-positive bacterial bloodstream infections Background: Data on the effectiveness of definitive oral (PO) antibiotics for BSIs in preparation for discharge from hospital are lacking, particularly for Gram-positive bacterial BSIs (GP-BSI). The objective of this study was to determine rates of treatment failure based on bioavailability of PO antimicrobial agents used for GP-BSI. Methods: This was a single-center, retrospective cohort study of adult inpatients admitted to an academic medical center over a three-year period. Patients with a non-staphylococcal GP-BSI who received intravenous antibiotics and were then switched to PO antibiotics for at least a third of their treatment course were included. The cohort was stratified into high (⩾90%) and low (<90%) bioavailability groups. The primary endpoint was the proportion of patients experiencing clinical failure in each group. Secondary endpoints included clinical failure stratified by antibiotic group, bactericidal versus bacteriostatic PO agents, and organism. Results: A total of 103 patients met criteria for inclusion, which failed to reach the a priori power calculation. Of the patients included, 26 received high bioavailability agents and 77 received low bioavailability agents. Infections originated largely from a pulmonary source (30%) and were caused primarily by streptococcal species (75%). Treatment failure rates were 19.2% in the high bioavailability group and 23.4% in the low bioavailability group (p = 0.66). Clinical failure stratified by subgroups also did not yield statistically significant differences. Conclusions: Clinical failure rates were similar among patients definitively treated with high or low bioavailability agents for GP-BSI, though the study was underpowered to detect such a difference. Introduction Bloodstream infections (BSIs) are associated with significant morbidity and mortality, and are the 11th leading cause of death in the United States (US). 1 In an epidemiological study of nosocomial BSIs in the US, 65% of episodes were caused by Gram-positive bacterial organisms. 2 Treatment of Gram-positive bacterial BSIs typically involves a course of intravenous (IV) therapy, requiring administration via IV lines, prolonged hospitalization, increased treatment costs, and increased risk of line-related infections. 3,4 There is a paucity of evidence-based data on the effectiveness of definitive antimicrobial regimens, specifically oral (PO) options, for Gram-positive bacterial BSIs in preparation for discharge from hospital. The 2007 Infectious Diseases Society for America (IDSA) guideline for community acquired pneumonia (CAP) suggests that a switch to PO therapy is reasonable, even in patients with bacteremia, once clinical stability is achieved 5 ; however, this recommendation is based on a small study in which only 9% of patients had concomitant bacteremia, with no information about which PO antibiotics were used. 6 A similar, randomized study by Oosterheert and colleagues assessing the effectiveness of early PO antibiotic use in severe CAP showed the majority of patients received amoxicillin/clavulanic acid. However, the specific agents used in the 9% of patients with concomitant bacteremia was not specifically mentioned. 7 The practice of transitioning from IV to PO antimicrobial agents with high bioavailability for the completion of treatment of BSI is largely based on expert opinion. Providers often analyze patientspecific factors in clinical context to determine agent selection and appropriate timing of PO antibiotics, due to the lack of conclusive data demonstrating efficacy of one PO agent over another. In an evidence-based review by Hale and colleagues, the authors point to susceptibility data, source control, stable hemodynamics, and the use of highly bioavailable agents as important considerations prior to switching to PO therapy in Grampositive bacterial BSI. 8 More data for the transition from IV to PO antibiotics in Gram-negative bacterial BSIs have been published than in Grampositive bacterial BSI, but with conflicting results. A study by Kutob and colleagues examined treatment failure rates based on bioavailability of PO antimicrobial agents prescribed for definitive therapy of Gram-negative bacterial BSI, and found that the risk of treatment failure increased as bioavailability of the PO regimen declined. 9 In contrast, a study published by Mercuro and colleagues found no difference in clinical success between PO stepdown therapy with beta-lactams or fluoroquinolones for Gram-negative bacterial BSI. 10 The purpose of this study was to examine the rate of clinical treatment failure based on bioavailability of PO agents and to determine risk factors for failure. This study was designed to help guide selection of the most optimal antimicrobial agents in solely Gram-positive bacterial BSIs, due to the gap in literature on this topic. We hypothesized that patients treated with agents with lower bioavailability would be more likely to experience clinical failure than those treated with higher bioavailability agents. Study design and setting This was a single-center, retrospective cohort study of adult inpatients admitted to an academic medical center in Charlotte, NC, between 1 September 2014 and 31 August 2017. Patients with a Gram-positive bacterial BSI caused by a prespecified list of organisms who received IV antibiotics and were then switched to PO antibiotics for discharge were included. Patients were identified through a Theradoc® information systems (Premier, Inc., Charlotte, NC, USA) generated report. The electronic medical record was used to gather and collect all necessary data, and approval for the study was obtained through the institutional review board. The data were entered and managed in a secure Research Electronic Data Capture (REDCap TM ) database. 11 Patient selection Adult patients (>18 years old) were included in the study if they had a positive blood culture for Streptococcus spp., Enterococcus spp., Peptostre ptococcus, or Clostridium spp.; if they received appropriate antibiotic therapy; and if at least onethird of their total course of antibiotics received were PO, including both inpatient and upon discharge. Appropriate antibiotic therapy was defined as antibiotics adequately dosed for the patient's creatinine clearance (CrCl) with in vitro activity against the isolate based on the Clinical and Laboratory Standards Institute criteria. CrCl and dose were assessed at the initiation of IV and PO antibiotics, and again at hospital discharge. Patients were excluded if they had bacteremia caused by Staphylococcus aureus, coagulasenegative Staphylococcus, or had a prior episode of bacteremia due to the same organism within the past 90 days. Patients were also excluded if the organism identified was determined by a treating clinician to be a contaminant; if the patient had a polymicrobial infection with an organism not listed previously; if the patient was never admitted for IV treatment; if the patient had a catheter-related BSI, concomitant meningitis, osteomyelitis, or endocarditis; or if they expired during hospitalization. Study objectives The primary outcome of this study was clinical failure in patients receiving high versus low journals.sagepub.com/home/tai 3 bioavailability agents. High bioavailability agents were defined as those with >90% bioavailability and included clindamycin, doxycycline, fluoroquinolones, linezolid, metronidazole, and trimethoprim/sulfamethoxazole. Low bioavailability agents were <90% bioavailable, including the aminopenicillins, penicillins, and cephalosporins. Clinical failure was defined as all-cause mortality within 90 days of diagnosis of BSI, 90-day hospital readmission from date of previous discharge due to infectious process, switch back to IV therapy due to lack of improvement on PO therapy, or recurrent BSI due to the original organism within 90 days of switch to PO therapy. To determine all-cause mortality, both medical records and death certificate databases were searched. Secondary endpoints assessed included clinical failure stratified by antibiotic group, organism, and bactericidal versus bacteriostatic agents. Bacteriostatic agents were defined as clindamycin, doxycycline, and linezolid. Duration of hospitalization, clinical failure in patients who had documented microbiological clearance versus those who did not, and source of infection were also assessed. Statistical analysis Descriptive statistics including means and standard deviations, or counts and percentages, were calculated for all variables. The primary analysis was a chi-squared test comparing the proportion of patients experiencing clinical failure in those receiving high versus low bioavailability agents. To assess potential risk factors of treatment failure, univariate logistic regression models were used to calculate odds ratios and 95% confidence intervals. To compare baseline characteristics and other secondary outcomes between study groups, Student's t test was used for normally distributed data, the Wilcoxon rank sum test was used for ordinal data or continuous data that were not normally distributed, and the chi-square test or Fisher's exact test was used for categorical data. A two-tailed p value of less than 0.05 was considered statistically significant. SAS Enterprise Guide®, version 6.1, was used for all analyses (SAS Institute Inc., Cary, NC, USA). Sample size was based on a chi-square test comparing the proportion of patients experiencing clinical failure in those receiving high versus low bioavailability agents. To detect a proportional difference of 10%, and assuming a 4% rate of clinical failure for patients treated with agents known to have higher bioavailability, 128 patients were required per treatment group for a power of 80% and alpha of 0.05. These failure rates were based on earlier studies in Gram-negative bacteremia as well as clinical expertise. 9 Results Over the 3-year study period, 597 adult patients with non-Staphylococcal Gram-positive bacterial BSIs were identified, with 103 patients being eligible for inclusion ( Figure 1). The median patient age was 59, with 51% being female, and 47% and 43% being White and African American, respectively ( were well balanced, apart from 46% of the high bioavailability group having a history of cancer compared with 20% of the low bioavailability group (p = 0.008). The predominant source of infection was pulmonary (30%) with the predominant organism being a streptococcal species (75%) ( Table 2). Patients were treated for a median of 15 days with 9 days administered orally and 7 days administered in the hospital. Overall, 23 out of the 103 patients experienced clinical failure (Table 3). In the high bioavailability group, 4 of the 26 patients were readmitted due to an infectious process, and 1 patient in the group expired for a total of five failures. In the low bioavailability group, 15 of the 77 were readmitted due to infection, with 1 of the 15 expiring, 5 requiring a switch back to IV therapy due to lack of improvement, and 2 having recurrent bacteremia due to the original organism. An additional three patients in the low bioavailability group died within 90 days of diagnosis for a total of 18 failures. Upon stratifying failure rates based on bioavailability, 19.2% of the high bioavailability group failed, while 23.4% of the low bioavailability group failed (p = 0.66). When assessing for risk factors for failure between bacteriostatic versus bactericidal agents, high versus low bioavailability agents, medication class, and organism, there were no statistically significant associations identified (Table 4). Discussion In this study, no difference in rates of clinical failure between the high (19.2%) and low (23.4%) bioavailability groups were observed. Additionally, there were no statistically significant differences in secondary endpoints. Failure rates in this study were higher than those seen in prior studies for the treatment of Gram-negative bacteremia. Kutob examined 362 cases of Gram-negative bacteremia treated with PO antibiotics and reported failure rates of 2%, 12%, and 14% for high, moderate, and low bioavailability agents respectively (p = 0.02). 9 Similar to Kutob, Mercuro studied PO treatment of Gram-negative bacteremia with beta-lactams compared with fluoroquinolones in 224 patients. This resulted in failure rates of 13% for each group (p = 0.96). 10 Apart from focusing on Gram-negative as opposed to Gram-positive organisms, these studies also had dissimilar stratifications of bioavailability, different definitions of clinical failure, and unique patient populations. In our study, 19% of patients were immunocompromised, with 9% having moderate-to-severe liver disease. In the Kutob study, these were the only two statistically significant risk factors for failure seen outside of bioavailability, and, in their study, only 9% were immunocompromised, with 3% having liver cirrhosis. 9 This could indicate that our patient population had a higher burden of illness and may have been more infection prone. In the study by Mercuro, 5% of patients had cirrhosis, and the number of immunocompromised patients was not stated. 10 Mercuro found diabetes with complications as their largest risk factor for treatment failure, which entailed 23% of their population, a similar proportion to our study. 10 Infections in our study were largely from a pulmonary source and caused by a streptococcal species, whereas prior studies had high rates of urinary sources of infection due to Escherichia coli. 9,10 It is important to note differences in treatment of these organisms, especially when considering use of low bioavailability agents. In general, streptococcal species have much lower minimum inhibitory concentrations for beta-lactam antibiotics when compared with the Enterobacteriaceae, making pharmacodynamic targets more easily achievable, even with use of agents with lower bioavailability. 12 With the majority of patients in this study having a streptococcal pneumonia as their source of BSI, these results could be taken into consideration when recommending treatment options in conjunction with clinical experience, microbiological data, and previous literature. Ramirez found that, in patients with Streptococcus pneumo niae bacteremia from a pulmonary source, there was no difference in clinical outcomes between patients who received PO switch therapy versus those who completed a course of IV only therapy after showing clinical improvement. 6 Although the specific antibiotics used were not mentioned, together these studies provide rationale for treating highly susceptible organisms such as Streptococcus pneumoniae with targeted antimicrobial agents such as beta-lactams. In this study, median length of therapy was approximately 2 weeks in both groups, similar to other studies in Gram-negative bacterial infections, and which recent literature suggests may not be needed in lower inoculum infections with absence of a deep seeded source. 13,14 However, to our knowledge, there are no published studies in Gram-positive bacterial infections to support this extrapolation. Due to the prolonged duration in both groups, it is unknown how a shorter duration of therapy would affect failure rates between groups, or if the similar failure rates were due to the 2-week course. With most patients receiving low bioavailability agents, it is clear that use of these agents was common practice at our institution for treatment of Gram-positive bacterial BSI after initial IV antibiotics. To our knowledge, this is the first study of IV to PO switch therapy for the completion of treatment of Gram-positive bacteremia. Similar studies are available in Gram-negative bacteremia; however, there are conflicting results regarding whether high bioavailability agents are more successful in treating BSI. 9,10,15 This study adds to the literature in an area of uncertainty, but must be interpreted with its limitations. Due to the retrospective nature of this study, the medical record was relied upon and the data extracted were dependent upon documentation accuracy. There was no randomization of the treatment groups and the groups were unevenly split, with 25% receiving high bioavailability agents and 75% receiving low bioavailability agents. We were also unable to confirm adherence to the treatment regimen upon discharge due to the study design and had to rely on discharge medication reconciliations with the assumption of adherence. Although death certificate databases were searched and medical records postdischarge were examined, some clinical failures may have gone undetected if they were admitted to a hospital outside of the center's healthcare system. For the five patients who were confirmed to have expired during the study period, cause of death (e.g. whether or not infection-related) was unable to be determined. Due to the strict exclusion criteria and the unexpectedly small sample size, power was not met, making the validity of these results uncertain. To power our study to detect the 4% difference in clinical failure that was seen, over 300 patients in each group would have been required. As our data set was run through a Theradoc® generated report in conjunction with our rapid diagnostic blood culture testing, our data set was able to go back only as far as September of 2014 when these processes were implemented. Despite these limitations, this study is the first of its kind in Gram-positive bacterial BSI. The patients in this trial did receive a long duration of PO therapy, with a median of 9 out of 15 (60%) days of therapy being PO, and patients were followed for 90 days postdiagnosis. As the primary objective of this trial was to determine the effectiveness of PO antibiotics, this is a major strength of the data. All patients received appropriately dosed and active antibiotics for the duration of their course. Despite no statistically significant differences, relevant risk factors were chosen to determine their effects on treatment outcomes, including bioavailability and pharmacodynamic properties. This study is hypothesis-generating for future, large-scale studies. Conclusion There were no differences in outcomes between the use of high or low bioavailability agents for the treatment of Gram-positive bacterial BSI. There were also no risk factors observed that increased the risk of failure based on the type of agent used or the organism and source that were being treated. Due to its limitations, conclusions cannot be drawn solely from this study; however, it is hypothesis-generating in an area where there is a paucity of data. These results set the stage for future, large-scale studies to validate the results of this study. Moxifloxacin 90 *Ciprofloxacin not included given lack of reliable activity against Gram-positive organisms.
Cold Calling and Web Postings: Do They Improve Students Preparation and Learning? Getting students to prepare well for class is a common challenge faced by instructors all over the world. This study investigates the effects that two frequently used techniques to increase student preparation -- web postings and cold calling -- have on student outcomes. The study is based on two experiments and a qualitative study conducted in a statistics course that Masters in Public Policy (MPP) students take in their second semester at the Kennedy School. When used together, web postings and cold calling seem to increase the amount of time that students devote to reading before class by about an hour. This effect is both statistically and practically significant. However this increase in pre-class reading did not translate into increased learning (measured by average test scores on the midterm exam). Neither of the two techniques seems to be better than the other one at increasing reading time, test scores or other student outcomes. Introduction Getting undergraduate and graduate students to read for class is often difficult (i.e. McKeachie and Svinicki, 2010). Students have significant demands on their time, including other schoolwork, extracurricular activities, and socializing. Examining undergraduate and graduate-level psychology courses, Burchfield and Sappington found that student completion of assigned readings plummeted from approximately 80 percent in 1981 to 20 percent in 1997. As an additional hurdle, statistics reading is often found by students to be dry and hard to follow (i.e. Cobb 1987). In an examination of introductory statistics textbooks for higher education, Harwell et al found that only one of the six texts was recommended for use by a majority of students. Even if students do the readings, there is no guarantee that the experience will make a significant impact on the student's performance in the course. Creating usable knowledge from reading involves a set of complex skills, and these skills are rarely taught to students in an explicit fashion. Research has also documented the difficulty students have in transferring knowledge learned in a particular context to new problems and settings (Bransford et al, 2000). This difficulty can be particularly acute with textbooks, as these resources often present material in ways that are quite different from the style and substance of the rest of the course. There are several ways that instructors can encourage students to increase the quantity and quality of their reading. Two promising techniques, both commonly used at the graduate level, are web postings and cold calling. This paper reports on a study conducted to find out how effective these methods were in improving student outcomes in a masters level statistics course taught at the Kennedy School of Government (Harvard University). The rest of the paper is organized as follows: Section 2 provides a description of the two techniques and explores the mechanisms through which these techniques could potentially impact student outcomes, Section 3 describes the study design, Section 4 presents the results, and Section 5 concludes. Description of Web Postings and Cold Calling This section provides a brief description of the two teaching techniques under study--web postings and cold calling. Although each technique can be used in a variety of ways, particularly in terms of the types and number of questions employed, this background section will focus on a robust format of each technique. Web postings use modern technology --particularly the course management platforms common in most institutions of higher education --to facilitate a long-standing practice of having students answer questions about the assigned reading in advance of coming to class (Chance et al, 2007). Peer instruction (PI), a popular pedagogical method in higher education, utilizes a well-developed and representative model of web postings (Crouch and Mazur, 2001). In PI, web posts are oriented towards higher-order cognition, asking students to carry out tasks including application, analysis, and evaluation. The assignments also ask students what they have found most confusing in the readings. The students post their answers through the course site in advance of class, giving the instructor the opportunity to read the responses before class. This information can then be incorporated in to the planning and execution of the class session. The students' posts, and their related participation in class, are graded to incentivize compliance. Cold calling, although most well known for its use in law and business school classrooms, is also common in many other higher education settings. Cold calling is the process of asking a question and calling, without advanced notice, on a student who has not volunteered to answer that question. Often, instructors devoted to cold calling will begin a class session by volunteering a student to summarize the essential aspects of one or more of the readings. Cold calls are then often used significantly throughout the remainder of the class session, employing questions that range from those that elicit factual details to those requiring complex thinking skills. Often, an instructor will stay with a single student for a long string of questions, and in the most extreme form, will do so until the student comes to a question for which they have no satisfactory answer. Theory of Change: Potential for Impacting Student Learning This sub-section describes the mechanisms through which these techniques could possibly affect student learning. Below is a simplified logic model encompassing the theories of change for both pedagogical techniques The remainder of this section expands on each of the four mechanisms described in Figure 1, and also explores a few mechanisms through which the two techniques could lead to a decrease in student learning. a) Increased learning due to the task itself Web postings are one version of what the learning sciences refer to as "prompts." There is a rich research literature on how a wide variety of prompts increase student learning (e.g., ;Linn & Eylon, 2006;White and Frederiksen, 1998;). Prompts are a type of scaffold: a pedagogical tool designed to assist learners in accomplishing complex tasks more effectively (). Reiser distinguishes two main ways in which scaffolding supports learning: "structuring the task" and "problematizing the subject matter." "Problematizing the subject matter" happens when a scaffold makes some aspect of the student's work more problematic, thereby requiring the student to spend more time and mental energy addressing this important idea or process. These "desirable difficulties" have been shown to improve student's conceptual knowledge. Web posting questions serve this role by requiring students to grapple much more intensely with important concepts in the readings. The answers to these questions also make visible, to both the student and the instructor, the student's current ways of thinking about the material. Research has shown that engaging student preconceptions in this way is critically important to the development of lasting knowledge and skills (Bransford, et al, 2000). The web post question that asks about remaining areas of confusion also provides valuable information to both the student and instructor. Answering the question helps the student pay more attention to the process of learning -what is going well, what is still problematic, and what the student might do to go about addressing these problems. This "thinking about thinking," or metacognition, helps students become better self-directed learners and problem solvers (Bransford et al, 2000). The instructor, in turn, can use this information to help him/her figure out how best to spend class time. Cold calling facilitates students' abilities both to process information quickly and to communicate a response effectively. There are several ways students benefit from this process. First, when people are forced to verbalize their understanding and make connections between ideas, the knowledge involved is strengthened. Second, as with web posts, cold calling helps make thinking visible. In particular, due to the involuntary nature of cold calling, students' misconceptions and preconceptions are more likely to surface than if instructors solicited volunteers. Although this can be uncomfortable, unearthing these misunderstandings is an important step in helping students to learn concepts effectively (Bransford et al, 2000). Last, research has shown that cold calling can lead to greater participation of minority groups; for example, US college classes featuring only voluntary participation tend to be dominated by white males. b) Increased learning due to the task's impact on the amount and timing of reading Extensive research has shown that holding students accountable for assigned reading in some concrete way dramatically increases the average amount students read. Mazur has found web postings to be an effective way to get students to complete the readings, and Carney et al found similar results from using a paper-based version of the method. Although we were unable to uncover any studies of how cold calling impacted student reading completion, it is sensible to expect that students will read more given that they may be asked to answer questions in front of their classmates and that their answers are formally evaluated. In turn, increased reading could likely have a positive impact on student learning, both because reading is generally an effective way to learn material (McKeachie & Svinicki, 2010) and because research shows that a student needs to encounter information multiple times in multiple ways to effectively incorporate it into their existing knowledge. c) Increased learning due to the task's impact on the quality of reading Web posts are an effective method for helping students to "structure the task" of reading a textbook by drawing students' attention to important aspects of the text and by encouraging them to process the concepts in a deeper way. Even though these questions are not intended to cover every major concept of a reading, they give students a clearer idea of the types of information they should focus on acquiring. It is likely that this improved understanding of where to focus their time and attention while reading will increase their conceptual understanding. Under related conditions, Reder and Anderson found that students who read textbook summaries actually acquired more knowledge than those who read the entire text. The questions also incentivize students to digest and process the text more deeply, which research has shown leads to improved knowledge development (Ferguson-Hessler and de Jong, 1990;McKeachie and Svinicki, 2010). Students also tend to retain information more clearly and permanently when they space out their readings rather than cram them before an exam or paper (Reder and Anderson, 1982). The influence of cold calling on the quality of reading is more indirect, as it is not tailored to any particular assignment. The types of questions that are asked in the process of cold calling will serve as a powerful signal to students as to what is valued from the reading (Doyle, 1983;McKeachie and Svinicki, 2010). If the instructor commonly cold calls on students to give a summary of one or more readings, people are more likely to read with this end goal in mind. Similarly, if the bulk of the cold calls focus on higher-order cognition, students should tend focus more on concepts than factual details. Also, as with web postings, students should benefit from cold calling if it leads them to do their readings regularly rather than all at once before an exam. d) Increased learning due to the task's impact on the classroom experience In having some positive impact on the quantity and quality of reading completed by students in advance of class, both web posts and cold calling enhance students' ability to learn from the class session. Students are better able to comprehend what is happening in class and are more aware of the knowledge gaps they need to remedy. Both of these reasons should increase the likelihood that students are willing and able to participate in class, and this active processing of material promotes learning (Bransford, et al, 2000). Another way that web posts improve the classroom experience is in helping the instructor make better use of class time. By reading the posts, the instructor has a fuller understanding of where students are at in terms of conceptual understanding of the material. The instructor can weave specific posts or themes from the posts in to the session and can modify what content is covered and the ways in which it is presented. A particular advantage of cold calling, assuming it is done in a sustained fashion, is that it creates a concrete incentive for students to stay focused throughout an entire class session. Increasing student attention is important, particularly given the findings that students have a difficult time focusing on a lecture for more than ten to twenty minutes. e) Decreased learning concerns There are two main reasons why either of these methods might decrease student learning. The first involves the potential these methods have to negatively impact students' intrinsic motivation for the course. Hobson found that intrinsic motivation was significantly influenced both by the instructor's attitudes and behaviors and by the relevance of the course content. There is a danger that web posts or cold calling, particularly if mainly instituted to increase student reading, can be seen as paternalistic. Some students also find cold calling off-putting due to its adversarial nature of forcing participation. Also, motivation could be further diminished if students find the reading to be dry and difficult to understand. The second reason why learning may decrease is that the increased time spent on reading and / or web posting may lead to a decrease in time spent on other, possibly more valuable, aspects of the course. If students are strongly incentivized to spend more time on reading and related activities such as web posting, that time has to come from somewhere. If at least some of that time is taken from other course activities -such as thoroughly understanding a problem set or studying lecture notes -any gains from the reading and related activities could be diminished or completely erased. In a detailed study of pedagogical innovation in engineering classrooms at MIT and the University of Cambridge, researchers found this ripple effect in time allocation, as a change in one aspect of the course led students to change the time they devoted to many other aspects of the course (Seering and Britter, 2007). Study Design Two experiments were conducted to assess the effectiveness of cold calling and web posting in increasing students' preparation for class and learning. Each experiment took place in a different section of "Quantitative Analysis and Empirical Methods II" (coded API-202), a required course taken by MPP students in their second semester. It is the second course in the statistics sequence and focuses on applied statistical analysis. Both sections were taught by one of the authors (Levy) in the Spring of 2009. The readings in the course came from "Introduction to Econometrics" by Stock and Watson, a standard statistics textbook used across many university campuses. The two experiments followed the same basic structure (Figure 2). Levy announced the experiments in the second class of the semester, after enrollment settled in and students could no longer switch to other sections of the course. In the third class, students in each section were randomly assigned into two different groups. The students were then exposed to their respective treatment conditions in classes #4 -#11, and the midterm exam occurred in class #12. Although the experiment concluded at that point, the assignment to the two groups was reversed so that all students were treated equally in the course (i.e. they were exposed to the same interventions but at different points in the semester). Figure 2 -Structure of Experiments The two experiments differed in terms of the treatment conditions students were assigned to (Table 1). In experiment #1, students in the first group were assigned to the "Web Posting AND Cold Calling" treatment, which meant that they would be required to do web postings before each class and they were put on a list from which they could be cold called. Students in the second group were instead assigned to a control condition in which Levy simply encouraged them to read before class, as he had done in many of his past courses (with some exhortations about the importance of reading before class for their learning). In experiment #2, students in the first group were required to do web posting for each class, whereas students in the second group were subject to cold calling. In addition to the experiments, a qualitative study was conducted aimed at understanding students' views on how they were experiencing the web postings and cold calling. Throughout the semester, Levy met with small groups of students to ask about their perceptions, and at the end of the course students were asked to fill in a brief anonymous survey in which they indicated their predictions as to which treatment would work and why. The qualitative survey was instrumental in understanding the results of the experiments and in helping Levy draw lessons for his pedagogy. Implementation of the Treatments This sub-section describes in some detail how the web postings and cold calling were implemented. We think this specificity will help readers interpret the results and assess the extent to which the findings are generalizable to contexts that are relevant for them. Web postings: Students were required to post answers to three questions on the course website by 4:00 am of the day of class. The three questions were based on the reading assigned for that day's class. Students could see each other's postings, but the questions were crafted such that it would be very evident if one student simply copied from another. For example, in the first question used in class #6 (see Box 1 below), students were asked to come up with a bivariate relationship in which they were interested and then use that bivariate relationship to answer some sub-questions. Since there are countless of bivariate relationships they could come up with, it would be very unlikely that two students would come up with the same answers unless they had seen each other's work. The third question was always the same: "Please tell us what you found difficult or confusing in this reading assignment." This question, recommended by Harvard Physics Professor Eric Mazur, was meant to facilitate metacognitive thinking from students and to give the instructor a sense of common student difficulties. Levy used this information to adjust the length of class time spent on each topic, and at the start of each class, he shared with students the themes that emerged from the posts. Compliance with web postings was fairly high. On average, students submitted 7.07 postings out of the 8 that were assigned. Approximately 80% of students posted 7 or 8 times. Some postings clearly demonstrated careful reading and reflection, whereas others seemed much less thoughtful. An example of the latter, in response to question #3, was: "Homoskedasticity and heteroskedasticity are interesting, but it would be great to spend some more time talking about both concepts in class." Cold Calling: As described in Section 2, implementation of cold calling can vary tremendously from class to class. In the case of this study, for each class session, Levy randomly chose one student from the cold call list of approximately 40 students. He typically asked that student two to three related questions. The questions, based on the assigned reading, tended to be factual/technical in nature. For example, in one class he asked "What are the two conditions for Omitted Variable Bias?" A student who had done the assigned reading should be able to answer this question, whereas a student who did not do the reading would have difficulty saying anything meaningful (unless they were familiar with the material from prior coursework, which was rare). When a student did not know the answer Levy would alternate between silence and probing for about 2-3 minutes, and then would move on. Based on qualitative feedback, some students felt stressful about being cold called whereas others felt that the probability of being cold called was fairly low (since only one out of the approximately 40 students on the cold call list was cold-called per class). We would rate this implementation of cold calling as "low to moderate" intensity, in contrast to the higher intensity typical of the Harvard Business and Law Schools, where instructors often do numerous cold calls per class and can probe with the struggling student for 5 to 10 minutes. Implementation of Random Assignment Random assignment was conducted separately in the two sections of the course. There were 80 students in experiment #1 and 93 students in experiment #2.The instructor and grade obtained in the first statistics course of the sequence were used as strata for random assignment. As it turns out, the grade in the previous statistics Box 1 -Example of Web posting questions (Class #6) Think about a bivariate relationship you are interested in. course was highly predictive of performance in the course in which the experiments were conducted. 1 This stratification increased the statistical power of the study design, which was especially important given the relatively small sample sizes. The goal of random assignment was to ensure that the two groups in each experiment were identical at the outset of the study, so that any subsequent difference in outcomes could be attributed solely to the difference in treatments received. Tables 2a and 2b compare the two groups for each of the experiments. As can be seen, the groups are indeed comparable to each other in key baseline characteristics, including gender, classroom seat location, previous statistics course (API-201) grade 2, the percentage taking the advanced section of the previous statistics course (API-201A), and the grade in problem set #1 (which was due before treatment began). The differences between the groups tend to be small and not statistically significant. In experiment #2, one difference (for whether the student was an MPP1 only, as opposed to a student from another school or doing a joint degree with the Kennedy School) was statistically significant at the 10% significance level. All in all, the results of Tables 2a and 2b are consistent with random assignment being well implemented and generating two comparable groups. The R 2 of a regression of midterm exam score in the course studied here on the strata dummy variables was 0.55 for experiment #1 and 0.57 for experiment #2. 2 This finding is important, but is to be expected given that this variable was used as strata for random assignment. 3 p-value reported to assess whether the difference between the means of the groups was statistically significant. 4 pp means percentage points. Impact Estimation Impacts were estimated separately for each of the experiments using the specification below: where Y is the outcome of interest, TREAT is the binary indicator for whether the student was assigned to group #1, and STRAT is a collection of binary indicators representing the different strata that were used for random assignment. The coefficient on TREAT represents the impact estimate of the group #1 treatment relative to the group #2 treatment. Robust standard errors were calculated. The key outcomes examined were the following: Time reading the textbook (minutes per week): Refers to the number of minutes students spent on course-related activities on week #4 of the semester. Students were asked to report this measure on an assignment they turned in that week. 5 Time spent on the course (minutes per week): Refers to the number of minutes students spent on courserelated activities on week #4 of the semester. It was taken from the same source as the previous measure. Number of times participating in class: A course assistant reported the number of times students participated in each of the classes during the treatment period. Problem set grades: Average grade of the 3 problem sets that were due during the treatment period (on a scale of 0 to 3). Standardized midterm score: Midterm exam score was standardized by subtracting the mean and dividing over the standard deviation of midterm score in each of the two samples. Results Overall, the key results of the two experiments were: Web Postings and Cold Calling had a positive effect on the amount of time students read before class but not on academic performance (as measured by the midterm exam score), When tested against each other, neither of the two methods (Web Posting and Cold Calling) came out on top in terms of improving any of the key outcomes. This section presents results from the two experiments in more detail. 5 While these self-reported measures are subject to measurement error, we tried to minimize the degree to which this error might be systematic by including a note on the assignment indicating "Your answers to the questions in this sheet will help us understand better how you allocate the time you spend on this course. Please answer the questions candidly. Your answers will not affect your grade on this problem set or on any other part of the course. As long as you submit your answers, you will get full credit on this part of the assignment." Experiment #1: Web Postings and Cold Calling vs. Control Group Web Postings and Cold Calling (WP&CC) together increased the time students spent reading the textbook by approximately one hour per week (Table 3a). This effect is statistically significant, and given that the control group only read about 35 minutes per week, represents quite a large change. The effect on reading time translated into an increase in the overall time that students spent on the course outside the classroom as a result of being assigned to the WP&CC group. The magnitude of the effect on total time spent on the course is about 47 minutes, which though not statistically different from the effect on reading time, hints at the possibility that reading time may be crowding out other course-related activities. Since both time spent on reading and time spent on the course was self-reported, one could suspect that the results presented above may overstate the true effect of the WP&CC treatment since students who were assigned to this treatment may be particularly prone to overstate the amount of time they devoted to the course for social desirability bias and similar reasons. While this possibility cannot be discarded, we do not think it is driving the results observed for three reasons. First, as reported in the previous section, the students were explicitly told that their answers about time use would not affect their grades, and were encouraged to answer candidly. Second, the qualitative study repeatedly suggests that students indeed felt incentivized (or, as many said, "forced") to read when they were assigned to the web postings and cold calling group (see Box 2 for some representative quotes.) Third, students protested several times in the semester about having to read and about the amount of reading. This had never happened in the four previous iterations of Levy teaching the course. Given that students assigned to the WP&CC group read more before class, one may expect that they both would participate more in class and do better in the problem sets and exam. This is not confirmed by the data. Although they seem to participate more often in class (0.66 times more), the difference is not statistically significant. Their problem set grades actually decreased by 0.18 points (about 0.43 standard deviations of the control group mean), and while this effect is only significant at the 10% level, it is suggestive that perhaps reading more led students to devote less effort to their problem sets. The qualitative study provides some support for this "crowding out" effect. (See Box #3 for some representative quotes.) Box #2 -Representative quotes suggesting students read more  "I only read when I was in the "web posting + warm calling group -sorry!"  "I would not read if I was not forced to through web postings"  "I would not have done readings except for warm calling and postings  "Warm calling and web posting forced me to read"  "Given time constraints, I would probably not have read anything without the warm call motivation. Unfortunately this is part of life @ the Kennedy School"  "Because the web posting was mandatory, they forced me to read."  "I did not do the reading from the textbook when it was not required"  "If no web postings, sometimes you intend to do the readings and end up not doing them"  "Without required posting, I probably would not have read"  "I was "gently" forced to read the material"  "Frankly my reading seriously dropped off in the second half of the semester when I wasn't required to post on the web. Incentives, incentives, incentives"  "The threat of being called in class motivated me to read" Source: Qualitative survey done at the end of the semester Page 13 of 22 Finally, the treatment also did not translate into an increase in learning, at least as measured by the midterm exam score. The effect on test score was small (0.03 standard deviations) and statistically insignificant at conventional levels. There are several possible substantive explanations for this result. The first, perhaps naturally favored by some economists, is that students are skilled in optimizing their use of time. As such, the WP&CC treatment may have led students to do more of something (in this case reading) that was less beneficial per time spent than some other things that got crowded out (in this case, studying or working on problem sets). Thus, an increase in reading, and even in time spent on the course overall, may not translate to better academic performance. A second explanation is that reading did not add significant value to student understanding, perhaps because the reading was not complementary enough to the class or because the reading was not appropriate for the type of students in the course. Several students voiced this general opinion; a representative quote from one: "Readings did not significantly enhance learning beyond lectures." A third possible explanation is that test scores are hard to affect in general, a finding supported by the research literature (i.e. Prince, 2006), and that these interventions were simply not strong enough (perhaps because of their short duration or because of the way they were implemented) to generate a significant impact. A fourth explanation is that since not all questions in the midterm exam drew directly from the materials in the readings, the midterm exam score was perhaps not measuring the learning that students were supposed to attain from the readings. But we conducted some analyses where the dependent variable was the aggregate score on the questions that were unequivocally related to the readings in the textbook 6, and again found no effect of the treatments on this aggregate score. 7 There are also some methodological alternative explanations to the lack of effect on midterm test scores. The first one is that, given the small sample sizes, the study did not have enough statistical power to detect reasonably 6 To decide which questions fell in this category, we asked Suzanne Cooper, a veteran instructor of the course, to make such determination. This represented an informed judgment call from someone not involved in this study. 7 The point estimate of the coefficient on the treatment variable was -0.08 in Experiment #1 and 0.11 in Experiment #2, and neither of these was statistically significant at conventional levels. Box #3 -Representative quotes suggesting reading crowded out other course activities  "Postings and reading did not enhance the in-class learning, rather they took time away from problem sets"  "If you do the readings hastily (because there is so much to do for this course), it does not make much of a difference"  "While the warm calling did nudge me to be more motivated to do the readings, the intense workload of the course and mandatory biweekly postings completely burnt me out and crushed my motivation to read by the end of the course"  "I did not like the web postings because they distracted from focusing on studying the material. " Source: Qualitative survey done at the end of the semester sized effects. While we cannot discard this explanation, we do not think it is very compelling. For one thing, the statistical power of the design was greatly improved by stratifying the random assignment using the grade on the first course of the sequence. Additionally, the point estimate was 0.03 standard deviations, and even with our relatively large standard error (0.17), we should have been able to detect sizable effects in the order of a third of a standard deviation or more. The second methodological explanation is that the treatments may have had spillovers. To the extent that cold calling and web posting led to half of the students being better prepared for class, perhaps the discussion in the classroom was enriched in a way that benefitted everyone in the course (including the half of the students who were in the control group). If this were indeed the case, our estimates here would understate the effect of WP&CC on learning. We cannot discard this explanation but would argue that the spillovers, if they existed, could also have affected negatively the control groups. For example, if the discussion occurred at a higher level (or faster pace), the control group students perhaps could have been more likely to be lost or confused, and if this were the case our estimates here would be overstating the effects of WP&CC on test scores. In sum, while we cannot discard these two methodological issues as partly explaining our results, we think it is unlikely that they are fully responsible for them. Experiment #2 -Web Postings vs. Cold Calling When tested against each other, neither of the two methods (Web Posting and Cold Calling) was found to be more effective in terms of improving any of the key outcomes (Table 3b). The differences in average outcomes between the web posting and cold calling groups was not statistically significant for time spent reading, time spent in the course, class participation, problem set grades and midterm grade. The difference in the midterm grade was 0.24 standard deviations in favor of the web posting group, which is not trivial, but it was not statistically significant. Furthermore, given no statistically significant effects on the other four outcomes, as well as the lack of impacts on midterm score in Experiment #1, it seems hard to argue that the web postings have an effect over cold calling with regards to midterm scores. Student and HKS Faculty Perceptions of WP & CC Effectiveness The reader could argue that perhaps the results reported above were not all that surprising. We argue here that they were. First, Levy's priors were that the combination of web posting and cold calling in Experiment #1 would have led to higher scores on the midterm exam. After all, he had been using these techniques for two years because he thought they led to increased learning. Second, as described below, samples of faculty and students by and large did not predict accurately the observed pattern of results. We conducted two surveys to examine how predictions of the effectiveness of the treatments related to the study's actual findings. The first survey group was composed of all the students taking part of the study, while the second included approximately 40 Kennedy School Faculty members attending a research seminar in which this study was presented. In the case of the faculty members, they were asked to make the predictions after they had heard the description of the interventions but before they had heard the results. In terms of Experiment #1, the vast majority of both groups correctly predicted the positive effects on reading time (92% of students and 74% of faculty). But only a minority of each group (26% in both) correctly predicted the lack of effects on learning (Table 4a). Students and faculty were not much better predicting the results of experiment #2. The majority of them thought that web posting would increase reading time relative to cold calling (Table 4b), which was not supported by the evidence. Furthermore, only 15% of faculty members and 18% of students predicted that web posting and cold calling would be equivalent in terms of their effect on learning. Conclusions Many instructors struggle with how to get their students to prepare better for class. This study reports on the effects of two frequently used techniques (web postings and cold calling) on student outcomes in a statistics course that MPP students take in their second semester at the Harvard Kennedy School. When used together these two techniques seem to increase the amount of time that students devote to reading before class by about an hour. This effect is both statistically and practically significant. However this increase in reading did not translate into increased learning (measured by average test scores on the midterm exam). Neither of the two techniques seems to be better than the other one at increasing reading time, test scores and other student outcomes. Possible substantive explanations for why web postings and cold calling affect reading time but not test scores include: the reallocation of time induced by the interventions was not optimal for increasing learning, the readings themselves did not add much value to other activities in the course, and the treatments were not intense enough to generate impacts on a variable as hard to affect as test scores. We do not conclude that web postings and cold calling cannot helpful to increase learning in general. Instead, we conclude that they were not helpful in this context as implemented here. Perhaps more importantly, we conclude that instructors using techniques they think are leading to increased learning would perhaps do well to assess whether this is actually true. Both authors, as well as the vast majority of students and other faculty members surveyed, had intuitions that ran counter to the main results of the study, namely that these interventions would have some positive impact on learning. If anything, we hope this study contributes to the notion that gathering evidence about our teaching has the potential of helping us become better in our teaching. Page 17
# Generated by Django 2.0.6 on 2018-08-13 08:07 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stats', '0001_initial'), ] operations = [ migrations.AddField( model_name='sourcehit', name='referer', field=models.CharField(default='', max_length=32), preserve_default=False, ), migrations.AddField( model_name='sourcehit', name='remoteHost', field=models.CharField(default='', max_length=32), preserve_default=False, ), migrations.AddField( model_name='sourcehit', name='requestTime', field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2018, 8, 13, 8, 6, 54, 267358)), preserve_default=False, ), migrations.AddField( model_name='sourcehit', name='userAgent', field=models.CharField(default='', max_length=200), preserve_default=False, ), ]
<reponame>xintipi/vite_vue_3 export default { title: '削除', cancel: 'キャンセル', delete: '削除', message_ja: ' を削除してもよろしいですか?', };
/* * The MIT License * * Copyright 2018 Pivotal Software, Inc.. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package edu.eci.arsw.compscene.model; import java.util.List; /** * * @author dbeltran */ public abstract class Pregunta { private int id; private String enunciado; private String tema; private List<String> opcionesDeRespuesta; private Float tiempo; private Object respJUgador; public Pregunta(int id, String enunciado, String tema, List<String> opcionesDeRespuesta, Float tiempo) { this.id = id; this.enunciado = enunciado; this.tema = tema; this.opcionesDeRespuesta = opcionesDeRespuesta; this.tiempo = tiempo; this.respJUgador=null; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEnunciado() { return enunciado; } public void setEnunciado(String enunciado) { this.enunciado = enunciado; } public String getTema() { return tema; } public void setTema(String tema) { this.tema = tema; } public List<String> getOpcionesDeRespuesta() { return opcionesDeRespuesta; } public void setOpcionesDeRespuesta(List<String> opcionesDeRespuesta) { this.opcionesDeRespuesta = opcionesDeRespuesta; } public Float getTiempo() { return tiempo; } public void setTiempo(Float tiempo) { this.tiempo = tiempo; } public Object getRespuestaJugador(){ return respJUgador; } public void setRespuestaJugador(Object ob){ respJUgador=ob; } public boolean validadorRespuesta(Object respuestaJugador, Object respuestaCorrecta){ return false; } @Override public String toString() { return "Pregunta{" + "id=" + id + ", encunciado=" + enunciado + ", tema=" + tema + '}'; } }
def field_alias(select_field): if select_field.alias is not None: return select_field.alias if isinstance(select_field.expr, tq_ast.ColumnId): return select_field.expr.name return None
export * as intake from "./intakeQuestions"; export * as weekly from "./weeklyQuestions"; export * as vaccination from "./vaccinationQuestions"; export * from "./helpers";
28.8 Multi-Modal Peripheral Nerve Active Probe and Microstimulator with On-Chip Dual-Coil Power/Data Transmission and 64 2nd-Order Opamp-Less ADCs The peripheral nervous system (PNS) enables communication between the central nervous system and various organs, for example by conveying sensory information and relaying motor commands. Electrical stimulation of peripheral nerves has been shown effective in treating major intractable disorders ranging from autoimmune disorder to chronic pain. It acts on specific nerves and avoids significant side effects of most drugs. Closed-loop PNS neurostimulators offer the additional benefits of personalization and optimality of the treatment. Such medical devices infer physiological function from measurable nerve action potentials and deliver custom-tailored electrical stimulation to elicit desired clinical outcomes.
//! The `ledger` module provides functions for parallel verification of the //! Proof of History ledger as well as iterative read, append write, and random //! access read to a persistent file-based ledger. use bincode::{self, deserialize, deserialize_from, serialize_into, serialized_size}; #[cfg(test)] use budget_transaction::BudgetTransaction; #[cfg(test)] use chrono::prelude::Utc; use entry::Entry; #[cfg(test)] use hash::hash; use hash::Hash; use log::Level::Trace; use mint::Mint; use packet::{SharedBlob, BLOB_DATA_SIZE}; use rayon::prelude::*; use result::{Error, Result}; use signature::{Keypair, KeypairUtil}; use solana_sdk::pubkey::Pubkey; use std::fs::{create_dir_all, remove_dir_all, File, OpenOptions}; use std::io::prelude::*; use std::io::{self, BufReader, BufWriter, Seek, SeekFrom}; use std::mem::size_of; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::Path; use transaction::Transaction; use vote_program::Vote; use vote_transaction::VoteTransaction; // // A persistent ledger is 2 files: // ledger_path/ --+ // +-- index <== an array of u64 offsets into data, // | each offset points to the first bytes // | of a u64 that contains the length of // | the entry. To make the code smaller, // | index[0] is set to 0, TODO: this field // | could later be used for other stuff... // +-- data <== concatenated instances of // u64 length // entry data // // When opening a ledger, we have the ability to "audit" it, which means we need // to pick which file to use as "truth", and correct the other file as // necessary, if possible. // // The protocol for writing the ledger is to append to the data file first, the // index file 2nd. If the writing node is interupted while appending to the // ledger, there are some possibilities we need to cover: // // 1. a partial write of data, which might be a partial write of length // or a partial write entry data // 2. a partial or missing write to index for that entry // // There is also the possibility of "unsynchronized" reading of the ledger // during transfer across nodes via rsync (or whatever). In this case, if the // transfer of the data file is done before the transfer of the index file, // it's likely that the index file will be far ahead of the data file in time. // // The quickest and most reliable strategy for recovery is therefore to treat // the data file as nearest to the "truth". // // The logic for "recovery/audit" is to open index and read backwards from the // last u64-aligned entry to get to where index and data agree (i.e. where a // successful deserialization of an entry can be performed), then truncate // both files to this syncrhonization point. // // ledger window #[derive(Debug)] pub struct LedgerWindow { index: BufReader<File>, data: BufReader<File>, } pub const LEDGER_DATA_FILE: &str = "data"; const LEDGER_INDEX_FILE: &str = "index"; // use a CONST because there's a cast, and we don't want "sizeof::<u64> as u64"... const SIZEOF_U64: u64 = size_of::<u64>() as u64; #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] fn err_bincode_to_io(e: Box<bincode::ErrorKind>) -> io::Error { io::Error::new(io::ErrorKind::Other, e.to_string()) } fn read_entry<A: Read>(file: &mut A, len: u64) -> io::Result<Entry> { deserialize_from(file.take(len)).map_err(err_bincode_to_io) } fn entry_at<A: Read + Seek>(file: &mut A, at: u64) -> io::Result<Entry> { let len = u64_at(file, at)?; read_entry(file, len) } fn next_entry<A: Read>(file: &mut A) -> io::Result<Entry> { let len = deserialize_from(file.take(SIZEOF_U64)).map_err(err_bincode_to_io)?; read_entry(file, len) } fn u64_at<A: Read + Seek>(file: &mut A, at: u64) -> io::Result<u64> { file.seek(SeekFrom::Start(at))?; deserialize_from(file.take(SIZEOF_U64)).map_err(err_bincode_to_io) } impl LedgerWindow { // opens a Ledger in directory, provides "infinite" window // pub fn open(ledger_path: &str) -> io::Result<Self> { let ledger_path = Path::new(&ledger_path); let index = File::open(ledger_path.join(LEDGER_INDEX_FILE))?; let index = BufReader::new(index); let data = File::open(ledger_path.join(LEDGER_DATA_FILE))?; let data = BufReader::with_capacity(BLOB_DATA_SIZE, data); Ok(LedgerWindow { index, data }) } pub fn get_entry(&mut self, index: u64) -> io::Result<Entry> { let offset = self.get_entry_offset(index)?; entry_at(&mut self.data, offset) } // Fill 'buf' with num_entries or most number of whole entries that fit into buf.len() // // Return tuple of (number of entries read, total size of entries read) pub fn get_entries_bytes( &mut self, start_index: u64, num_entries: u64, buf: &mut [u8], ) -> io::Result<(u64, u64)> { let start_offset = self.get_entry_offset(start_index)?; let mut total_entries = 0; let mut end_offset = 0; for i in 0..num_entries { let offset = self.get_entry_offset(start_index + i)?; let len = u64_at(&mut self.data, offset)?; let cur_end_offset = offset + len + SIZEOF_U64; if (cur_end_offset - start_offset) > buf.len() as u64 { break; } end_offset = cur_end_offset; total_entries += 1; } if total_entries == 0 { return Ok((0, 0)); } let read_len = end_offset - start_offset; self.data.seek(SeekFrom::Start(start_offset))?; let fread_len = self.data.read(&mut buf[..read_len as usize])? as u64; if fread_len != read_len { return Err(io::Error::new( io::ErrorKind::Other, format!( "entry read_len({}) doesn't match expected ({})", fread_len, read_len ), )); } Ok((total_entries, read_len)) } fn get_entry_offset(&mut self, index: u64) -> io::Result<u64> { u64_at(&mut self.index, index * SIZEOF_U64) } } pub fn verify_ledger(ledger_path: &str) -> io::Result<()> { let ledger_path = Path::new(&ledger_path); let index = File::open(ledger_path.join(LEDGER_INDEX_FILE))?; let index_len = index.metadata()?.len(); if index_len % SIZEOF_U64 != 0 { Err(io::Error::new( io::ErrorKind::Other, format!("index is not a multiple of {} bytes long", SIZEOF_U64), ))?; } let mut index = BufReader::new(index); let data = File::open(ledger_path.join(LEDGER_DATA_FILE))?; let mut data = BufReader::with_capacity(BLOB_DATA_SIZE, data); let mut last_data_offset = 0; let mut index_offset = 0; let mut data_read = 0; let mut last_len = 0; let mut i = 0; while index_offset < index_len { let data_offset = u64_at(&mut index, index_offset)?; if last_data_offset + last_len != data_offset { Err(io::Error::new( io::ErrorKind::Other, format!( "at entry[{}], a gap or an overlap last_offset {} offset {} last_len {}", i, last_data_offset, data_offset, last_len ), ))?; } match entry_at(&mut data, data_offset) { Err(e) => Err(io::Error::new( io::ErrorKind::Other, format!( "entry[{}] deserialize() failed at offset {}, err: {}", index_offset / SIZEOF_U64, data_offset, e.to_string(), ), ))?, Ok(entry) => { last_len = serialized_size(&entry).map_err(err_bincode_to_io)? + SIZEOF_U64 } } last_data_offset = data_offset; data_read += last_len; index_offset += SIZEOF_U64; i += 1; } let data = data.into_inner(); if data_read != data.metadata()?.len() { Err(io::Error::new( io::ErrorKind::Other, "garbage on end of data file", ))?; } Ok(()) } fn recover_ledger(ledger_path: &str) -> io::Result<()> { let ledger_path = Path::new(ledger_path); let mut index = OpenOptions::new() .write(true) .read(true) .open(ledger_path.join(LEDGER_INDEX_FILE))?; let mut data = OpenOptions::new() .write(true) .read(true) .open(ledger_path.join(LEDGER_DATA_FILE))?; // first, truncate to a multiple of SIZEOF_U64 let len = index.metadata()?.len(); if len % SIZEOF_U64 != 0 { trace!("recover: trimming index len to {}", len - len % SIZEOF_U64); index.set_len(len - (len % SIZEOF_U64))?; } // next, pull index offsets off one at a time until the last one points // to a valid entry deserialization offset... loop { let len = index.metadata()?.len(); trace!("recover: index len:{}", len); // should never happen if len < SIZEOF_U64 { trace!("recover: error index len {} too small", len); Err(io::Error::new(io::ErrorKind::Other, "empty ledger index"))?; } let offset = u64_at(&mut index, len - SIZEOF_U64)?; trace!("recover: offset[{}]: {}", (len / SIZEOF_U64) - 1, offset); match entry_at(&mut data, offset) { Ok(entry) => { trace!("recover: entry[{}]: {:?}", (len / SIZEOF_U64) - 1, entry); let entry_len = serialized_size(&entry).map_err(err_bincode_to_io)?; trace!("recover: entry_len: {}", entry_len); // now trim data file to size... data.set_len(offset + SIZEOF_U64 + entry_len)?; trace!( "recover: trimmed data file to {}", offset + SIZEOF_U64 + entry_len ); break; // all good } Err(_err) => { trace!( "recover: no entry recovered at {} {}", offset, _err.to_string() ); index.set_len(len - SIZEOF_U64)?; } } } if log_enabled!(Trace) { let num_entries = index.metadata()?.len() / SIZEOF_U64; trace!("recover: done. {} entries", num_entries); } // flush everything to disk... index.sync_all()?; data.sync_all() } // TODO?? ... we could open the files on demand to support [], but today // LedgerWindow needs "&mut self" // //impl Index<u64> for LedgerWindow { // type Output = io::Result<Entry>; // // fn index(&mut self, index: u64) -> &io::Result<Entry> { // match u64_at(&mut self.index, index * SIZEOF_U64) { // Ok(offset) => &entry_at(&mut self.data, offset), // Err(e) => &Err(e), // } // } //} #[derive(Debug)] pub struct LedgerWriter { index: BufWriter<File>, data: BufWriter<File>, } impl LedgerWriter { // recover and open the ledger for writing pub fn recover(ledger_path: &str) -> io::Result<Self> { recover_ledger(ledger_path)?; LedgerWriter::open(ledger_path, false) } // opens or creates a LedgerWriter in ledger_path directory pub fn open(ledger_path: &str, create: bool) -> io::Result<Self> { let ledger_path = Path::new(&ledger_path); if create { let _ignored = remove_dir_all(ledger_path); create_dir_all(ledger_path)?; } let index = OpenOptions::new() .create(create) .append(true) .open(ledger_path.join(LEDGER_INDEX_FILE))?; if log_enabled!(Trace) { let len = index.metadata()?.len(); trace!("LedgerWriter::new: index fp:{}", len); } let index = BufWriter::new(index); let data = OpenOptions::new() .create(create) .append(true) .open(ledger_path.join(LEDGER_DATA_FILE))?; if log_enabled!(Trace) { let len = data.metadata()?.len(); trace!("LedgerWriter::new: data fp:{}", len); } let data = BufWriter::new(data); Ok(LedgerWriter { index, data }) } fn write_entry_noflush(&mut self, entry: &Entry) -> io::Result<()> { let len = serialized_size(&entry).map_err(err_bincode_to_io)?; serialize_into(&mut self.data, &len).map_err(err_bincode_to_io)?; if log_enabled!(Trace) { let offset = self.data.seek(SeekFrom::Current(0))?; trace!("write_entry: after len data fp:{}", offset); } serialize_into(&mut self.data, &entry).map_err(err_bincode_to_io)?; if log_enabled!(Trace) { let offset = self.data.seek(SeekFrom::Current(0))?; trace!("write_entry: after entry data fp:{}", offset); } let offset = self.data.seek(SeekFrom::Current(0))? - len - SIZEOF_U64; trace!("write_entry: offset:{} len:{}", offset, len); serialize_into(&mut self.index, &offset).map_err(err_bincode_to_io)?; if log_enabled!(Trace) { let offset = self.index.seek(SeekFrom::Current(0))?; trace!("write_entry: end index fp:{}", offset); } Ok(()) } pub fn write_entry(&mut self, entry: &Entry) -> io::Result<()> { self.write_entry_noflush(&entry)?; self.index.flush()?; self.data.flush()?; Ok(()) } pub fn write_entries<'a, I>(&mut self, entries: I) -> io::Result<()> where I: IntoIterator<Item = &'a Entry>, { for entry in entries { self.write_entry_noflush(&entry)?; } self.index.flush()?; self.data.flush()?; Ok(()) } } #[derive(Debug)] pub struct LedgerReader { data: BufReader<File>, } impl Iterator for LedgerReader { type Item = io::Result<Entry>; fn next(&mut self) -> Option<io::Result<Entry>> { match next_entry(&mut self.data) { Ok(entry) => Some(Ok(entry)), Err(_) => None, } } } /// Return an iterator for all the entries in the given file. pub fn read_ledger( ledger_path: &str, recover: bool, ) -> io::Result<impl Iterator<Item = io::Result<Entry>>> { if recover { recover_ledger(ledger_path)?; } let ledger_path = Path::new(&ledger_path); let data = File::open(ledger_path.join(LEDGER_DATA_FILE))?; let data = BufReader::new(data); Ok(LedgerReader { data }) } // a Block is a slice of Entries pub trait Block { /// Verifies the hashes and counts of a slice of transactions are all consistent. fn verify(&self, start_hash: &Hash) -> bool; fn to_blobs(&self) -> Vec<SharedBlob>; fn to_blobs_with_id(&self, id: Pubkey, start_id: u64, addr: &SocketAddr) -> Vec<SharedBlob>; fn votes(&self) -> Vec<(Pubkey, Vote, Hash)>; } impl Block for [Entry] { fn verify(&self, start_hash: &Hash) -> bool { let genesis = [Entry::new_tick(start_hash, 0, start_hash)]; let entry_pairs = genesis.par_iter().chain(self).zip(self); entry_pairs.all(|(x0, x1)| { let r = x1.verify(&x0.id); if !r { warn!( "entry invalid!: x0: {:?}, x1: {:?} num txs: {}", x0.id, x1.id, x1.transactions.len() ); } r }) } fn to_blobs_with_id(&self, id: Pubkey, start_idx: u64, addr: &SocketAddr) -> Vec<SharedBlob> { self.iter() .enumerate() .map(|(i, entry)| entry.to_blob(Some(start_idx + i as u64), Some(id), Some(&addr))) .collect() } fn to_blobs(&self) -> Vec<SharedBlob> { let default_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0); self.to_blobs_with_id(Pubkey::default(), 0, &default_addr) } fn votes(&self) -> Vec<(Pubkey, Vote, Hash)> { self.iter() .flat_map(|entry| { entry .transactions .iter() .flat_map(VoteTransaction::get_votes) }).collect() } } // TODO: move this to the right file, entry.rs? pub fn reconstruct_entries_from_blobs(blobs: Vec<SharedBlob>) -> Result<Vec<Entry>> { let mut entries: Vec<Entry> = Vec::with_capacity(blobs.len()); for blob in blobs { let entry = { let blob = blob.read().unwrap(); let blob_size = blob.size()?; deserialize(&blob.data()[..blob_size]) }; match entry { Ok(entry) => entries.push(entry), Err(err) => { trace!("reconstruct_entry_from_blobs: {:?}", err); return Err(Error::Serialize(err)); } } } Ok(entries) } /// Creates the next entries for given transactions, outputs /// updates start_hash to id of last Entry, sets num_hashes to 0 pub fn next_entries_mut( start_hash: &mut Hash, num_hashes: &mut u64, transactions: Vec<Transaction>, ) -> Vec<Entry> { // TODO: ?? find a number that works better than |? // V if transactions.is_empty() || transactions.len() == 1 { vec![Entry::new_mut(start_hash, num_hashes, transactions)] } else { let mut chunk_start = 0; let mut entries = Vec::new(); while chunk_start < transactions.len() { let mut chunk_end = transactions.len(); let mut upper = chunk_end; let mut lower = chunk_start; let mut next = chunk_end; // be optimistic that all will fit // binary search for how many transactions will fit in an Entry (i.e. a BLOB) loop { debug!( "chunk_end {}, upper {} lower {} next {} transactions.len() {}", chunk_end, upper, lower, next, transactions.len() ); if Entry::serialized_size(&transactions[chunk_start..chunk_end]) <= BLOB_DATA_SIZE as u64 { next = (upper + chunk_end) / 2; lower = chunk_end; debug!( "chunk_end {} fits, maybe too well? trying {}", chunk_end, next ); } else { next = (lower + chunk_end) / 2; upper = chunk_end; debug!("chunk_end {} doesn't fit! trying {}", chunk_end, next); } // same as last time if next == chunk_end { debug!("converged on chunk_end {}", chunk_end); break; } chunk_end = next; } entries.push(Entry::new_mut( start_hash, num_hashes, transactions[chunk_start..chunk_end].to_vec(), )); chunk_start = chunk_end; } entries } } /// Creates the next Entries for given transactions pub fn next_entries( start_hash: &Hash, num_hashes: u64, transactions: Vec<Transaction>, ) -> Vec<Entry> { let mut id = *start_hash; let mut num_hashes = num_hashes; next_entries_mut(&mut id, &mut num_hashes, transactions) } pub fn get_tmp_ledger_path(name: &str) -> String { use std::env; let out_dir = env::var("OUT_DIR").unwrap_or_else(|_| "target".to_string()); let keypair = Keypair::new(); let path = format!("{}/tmp/ledger-{}-{}", out_dir, name, keypair.pubkey()); // whack any possible collision let _ignored = remove_dir_all(&path); path } pub fn create_tmp_ledger_with_mint(name: &str, mint: &Mint) -> String { let path = get_tmp_ledger_path(name); let mut writer = LedgerWriter::open(&path, true).unwrap(); writer.write_entries(&mint.create_entries()).unwrap(); path } pub fn create_tmp_genesis( name: &str, num: u64, bootstrap_leader_id: Pubkey, bootstrap_leader_tokens: u64, ) -> (Mint, String) { let mint = Mint::new_with_leader(num, bootstrap_leader_id, bootstrap_leader_tokens); let path = create_tmp_ledger_with_mint(name, &mint); (mint, path) } pub fn create_ticks(num_ticks: usize, mut hash: Hash) -> Vec<Entry> { let mut ticks = Vec::with_capacity(num_ticks as usize); for _ in 0..num_ticks { let new_tick = Entry::new(&hash, 1, vec![]); hash = new_tick.id; ticks.push(new_tick); } ticks } pub fn create_tmp_sample_ledger( name: &str, num_tokens: u64, num_ending_ticks: usize, bootstrap_leader_id: Pubkey, bootstrap_leader_tokens: u64, ) -> (Mint, String, Vec<Entry>) { let mint = Mint::new_with_leader(num_tokens, bootstrap_leader_id, bootstrap_leader_tokens); let path = get_tmp_ledger_path(name); // Create the entries let mut genesis = mint.create_entries(); let ticks = create_ticks(num_ending_ticks, mint.last_id()); genesis.extend(ticks); let mut writer = LedgerWriter::open(&path, true).unwrap(); writer.write_entries(&genesis.clone()).unwrap(); (mint, path, genesis) } #[cfg(test)] pub fn make_tiny_test_entries(num: usize) -> Vec<Entry> { let zero = Hash::default(); let one = hash(&zero.as_ref()); let keypair = Keypair::new(); let mut id = one; let mut num_hashes = 0; (0..num) .map(|_| { Entry::new_mut( &mut id, &mut num_hashes, vec![Transaction::budget_new_timestamp( &keypair, keypair.pubkey(), keypair.pubkey(), Utc::now(), one, )], ) }).collect() } #[cfg(test)] mod tests { use super::*; use bincode::serialized_size; use budget_transaction::BudgetTransaction; use entry::{next_entry, Entry}; use hash::hash; use packet::{to_blobs, BLOB_DATA_SIZE, PACKET_DATA_SIZE}; use signature::{Keypair, KeypairUtil}; use std; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use transaction::Transaction; use vote_program::Vote; #[test] fn test_verify_slice() { use logger; logger::setup(); let zero = Hash::default(); let one = hash(&zero.as_ref()); assert!(vec![][..].verify(&zero)); // base case assert!(vec![Entry::new_tick(&zero, 0, &zero)][..].verify(&zero)); // singleton case 1 assert!(!vec![Entry::new_tick(&zero, 0, &zero)][..].verify(&one)); // singleton case 2, bad assert!(vec![next_entry(&zero, 0, vec![]); 2][..].verify(&zero)); // inductive step let mut bad_ticks = vec![next_entry(&zero, 0, vec![]); 2]; bad_ticks[1].id = one; assert!(!bad_ticks.verify(&zero)); // inductive step, bad } fn make_test_entries() -> Vec<Entry> { let zero = Hash::default(); let one = hash(&zero.as_ref()); let keypair = Keypair::new(); let vote_account = Keypair::new(); let tx0 = Transaction::vote_new(&vote_account, Vote { tick_height: 1 }, one, 1); let tx1 = Transaction::budget_new_timestamp( &keypair, keypair.pubkey(), keypair.pubkey(), Utc::now(), one, ); // // TODO: this magic number and the mix of transaction types // is designed to fill up a Blob more or less exactly, // to get near enough the the threshold that // deserialization falls over if it uses the wrong size() // parameter to index into blob.data() // // magic numbers -----------------+ // | // V let mut transactions = vec![tx0; 362]; transactions.extend(vec![tx1; 100]); next_entries(&zero, 0, transactions) } #[test] fn test_entries_to_blobs() { use logger; logger::setup(); let entries = make_test_entries(); let blob_q = entries.to_blobs(); assert_eq!(reconstruct_entries_from_blobs(blob_q).unwrap(), entries); } #[test] fn test_bad_blobs_attack() { use logger; logger::setup(); let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 8000); let blobs_q = to_blobs(vec![(0, addr)]).unwrap(); // <-- attack! assert!(reconstruct_entries_from_blobs(blobs_q).is_err()); } #[test] fn test_next_entries() { use logger; logger::setup(); let id = Hash::default(); let next_id = hash(&id.as_ref()); let keypair = Keypair::new(); let vote_account = Keypair::new(); let tx_small = Transaction::vote_new(&vote_account, Vote { tick_height: 1 }, next_id, 2); let tx_large = Transaction::budget_new(&keypair, keypair.pubkey(), 1, next_id); let tx_small_size = serialized_size(&tx_small).unwrap() as usize; let tx_large_size = serialized_size(&tx_large).unwrap() as usize; let entry_size = serialized_size(&Entry { prev_id: Hash::default(), num_hashes: 0, id: Hash::default(), transactions: vec![], }).unwrap() as usize; assert!(tx_small_size < tx_large_size); assert!(tx_large_size < PACKET_DATA_SIZE); let threshold = (BLOB_DATA_SIZE - entry_size) / tx_small_size; // verify no split let transactions = vec![tx_small.clone(); threshold]; let entries0 = next_entries(&id, 0, transactions.clone()); assert_eq!(entries0.len(), 1); assert!(entries0.verify(&id)); // verify the split with uniform transactions let transactions = vec![tx_small.clone(); threshold * 2]; let entries0 = next_entries(&id, 0, transactions.clone()); assert_eq!(entries0.len(), 2); assert!(entries0.verify(&id)); // verify the split with small transactions followed by large // transactions let mut transactions = vec![tx_small.clone(); BLOB_DATA_SIZE / tx_small_size]; let large_transactions = vec![tx_large.clone(); BLOB_DATA_SIZE / tx_large_size]; transactions.extend(large_transactions); let entries0 = next_entries(&id, 0, transactions.clone()); assert!(entries0.len() >= 2); assert!(entries0.verify(&id)); } #[test] fn test_ledger_reader_writer() { use logger; logger::setup(); let ledger_path = get_tmp_ledger_path("test_ledger_reader_writer"); let entries = make_tiny_test_entries(10); { let mut writer = LedgerWriter::open(&ledger_path, true).unwrap(); writer.write_entries(&entries.clone()).unwrap(); // drops writer, flushes buffers } verify_ledger(&ledger_path).unwrap(); let mut read_entries = vec![]; for x in read_ledger(&ledger_path, true).unwrap() { let entry = x.unwrap(); trace!("entry... {:?}", entry); read_entries.push(entry); } assert_eq!(read_entries, entries); let mut window = LedgerWindow::open(&ledger_path).unwrap(); for (i, entry) in entries.iter().enumerate() { let read_entry = window.get_entry(i as u64).unwrap(); assert_eq!(*entry, read_entry); } assert!(window.get_entry(100).is_err()); std::fs::remove_file(Path::new(&ledger_path).join(LEDGER_DATA_FILE)).unwrap(); // empty data file should fall over assert!(LedgerWindow::open(&ledger_path).is_err()); assert!(read_ledger(&ledger_path, false).is_err()); std::fs::remove_dir_all(ledger_path).unwrap(); } fn truncated_last_entry(ledger_path: &str, entries: Vec<Entry>) { let len = { let mut writer = LedgerWriter::open(&ledger_path, true).unwrap(); writer.write_entries(&entries).unwrap(); writer.data.seek(SeekFrom::Current(0)).unwrap() }; verify_ledger(&ledger_path).unwrap(); let data = OpenOptions::new() .write(true) .open(Path::new(&ledger_path).join(LEDGER_DATA_FILE)) .unwrap(); data.set_len(len - 4).unwrap(); } fn garbage_on_data(ledger_path: &str, entries: Vec<Entry>) { let mut writer = LedgerWriter::open(&ledger_path, true).unwrap(); writer.write_entries(&entries).unwrap(); writer.data.write_all(b"hi there!").unwrap(); } fn read_ledger_check(ledger_path: &str, entries: Vec<Entry>, len: usize) { let read_entries = read_ledger(&ledger_path, true).unwrap(); let mut i = 0; for entry in read_entries { assert_eq!(entry.unwrap(), entries[i]); i += 1; } assert_eq!(i, len); } fn ledger_window_check(ledger_path: &str, entries: Vec<Entry>, len: usize) { let mut window = LedgerWindow::open(&ledger_path).unwrap(); for i in 0..len { let entry = window.get_entry(i as u64); assert_eq!(entry.unwrap(), entries[i]); } } #[test] fn test_recover_ledger() { use logger; logger::setup(); let entries = make_tiny_test_entries(10); let ledger_path = get_tmp_ledger_path("test_recover_ledger"); // truncate data file, tests recover inside read_ledger_check() truncated_last_entry(&ledger_path, entries.clone()); read_ledger_check(&ledger_path, entries.clone(), entries.len() - 1); // truncate data file, tests recover inside LedgerWindow::new() truncated_last_entry(&ledger_path, entries.clone()); ledger_window_check(&ledger_path, entries.clone(), entries.len() - 1); // restore last entry, tests recover_ledger() inside LedgerWriter::new() truncated_last_entry(&ledger_path, entries.clone()); // verify should fail at first assert!(verify_ledger(&ledger_path).is_err()); { let mut writer = LedgerWriter::recover(&ledger_path).unwrap(); writer.write_entry(&entries[entries.len() - 1]).unwrap(); } // and be fine after recover() verify_ledger(&ledger_path).unwrap(); read_ledger_check(&ledger_path, entries.clone(), entries.len()); ledger_window_check(&ledger_path, entries.clone(), entries.len()); // make it look like data is newer in time, check reader... garbage_on_data(&ledger_path, entries.clone()); read_ledger_check(&ledger_path, entries.clone(), entries.len()); // make it look like data is newer in time, check window... garbage_on_data(&ledger_path, entries.clone()); ledger_window_check(&ledger_path, entries.clone(), entries.len()); // make it look like data is newer in time, check writer... garbage_on_data(&ledger_path, entries[..entries.len() - 1].to_vec()); assert!(verify_ledger(&ledger_path).is_err()); { let mut writer = LedgerWriter::recover(&ledger_path).unwrap(); writer.write_entry(&entries[entries.len() - 1]).unwrap(); } verify_ledger(&ledger_path).unwrap(); read_ledger_check(&ledger_path, entries.clone(), entries.len()); ledger_window_check(&ledger_path, entries.clone(), entries.len()); let _ignored = remove_dir_all(&ledger_path); } #[test] fn test_verify_ledger() { use logger; logger::setup(); let entries = make_tiny_test_entries(10); let ledger_path = get_tmp_ledger_path("test_verify_ledger"); { let mut writer = LedgerWriter::open(&ledger_path, true).unwrap(); writer.write_entries(&entries).unwrap(); } // TODO more cases that make ledger_verify() fail // assert!(verify_ledger(&ledger_path).is_err()); assert!(verify_ledger(&ledger_path).is_ok()); let _ignored = remove_dir_all(&ledger_path); } #[test] fn test_get_entries_bytes() { use logger; logger::setup(); let entries = make_tiny_test_entries(10); let ledger_path = get_tmp_ledger_path("test_raw_entries"); { let mut writer = LedgerWriter::open(&ledger_path, true).unwrap(); writer.write_entries(&entries).unwrap(); } let mut window = LedgerWindow::open(&ledger_path).unwrap(); let mut buf = [0; 1024]; let (num_entries, bytes) = window.get_entries_bytes(0, 1, &mut buf).unwrap(); let bytes = bytes as usize; assert_eq!(num_entries, 1); let entry: Entry = deserialize(&buf[size_of::<u64>()..bytes]).unwrap(); assert_eq!(entry, entries[0]); let (num_entries, bytes2) = window.get_entries_bytes(0, 2, &mut buf).unwrap(); let bytes2 = bytes2 as usize; assert_eq!(num_entries, 2); assert!(bytes2 > bytes); for (i, ref entry) in entries.iter().enumerate() { info!("entry[{}] = {:?}", i, entry.id); } let entry: Entry = deserialize(&buf[size_of::<u64>()..bytes]).unwrap(); assert_eq!(entry, entries[0]); let entry: Entry = deserialize(&buf[bytes + size_of::<u64>()..bytes2]).unwrap(); assert_eq!(entry, entries[1]); // buf size part-way into entry[1], should just return entry[0] let mut buf = vec![0; bytes + size_of::<u64>() + 1]; let (num_entries, bytes3) = window.get_entries_bytes(0, 2, &mut buf).unwrap(); assert_eq!(num_entries, 1); let bytes3 = bytes3 as usize; assert_eq!(bytes3, bytes); let mut buf = vec![0; bytes2 - 1]; let (num_entries, bytes4) = window.get_entries_bytes(0, 2, &mut buf).unwrap(); assert_eq!(num_entries, 1); let bytes4 = bytes4 as usize; assert_eq!(bytes4, bytes); let mut buf = vec![0; bytes + size_of::<u64>() - 1]; let (num_entries, bytes5) = window.get_entries_bytes(0, 2, &mut buf).unwrap(); assert_eq!(num_entries, 1); let bytes5 = bytes5 as usize; assert_eq!(bytes5, bytes); let mut buf = vec![0; bytes * 2]; let (num_entries, bytes6) = window.get_entries_bytes(9, 1, &mut buf).unwrap(); assert_eq!(num_entries, 1); let bytes6 = bytes6 as usize; let entry: Entry = deserialize(&buf[size_of::<u64>()..bytes6]).unwrap(); assert_eq!(entry, entries[9]); // Read out of range assert!(window.get_entries_bytes(20, 2, &mut buf).is_err()); let _ignored = remove_dir_all(&ledger_path); } }
/** * Paints the specified component <code>c</code> on the {@link Graphics} * context <code>graphics</code>. The Graphics context is tranlated to * (x,y) and the components bounds are set to (w,h). If * <code>shouldValidate</code> * is set to true, then the component is validated before painting. * * @param graphics the graphics context to paint on * @param c the component to be painted * @param p the parent of the component * @param x the X coordinate of the upper left corner where c should be painted * @param y the Y coordinate of the upper left corner where c should be painted * @param w the width of the components drawing area * @param h the height of the components drawing area * @param shouldValidate if <code>c</code> should be validated before * painting */ public void paintComponent(Graphics graphics, Component c, Container p, int x, int y, int w, int h, boolean shouldValidate) { addImpl(c, null, 0); Rectangle oldClip = graphics.getClipBounds(); boolean translated = false; try { graphics.translate(x, y); translated = true; graphics.clipRect(0, 0, w, h); c.setBounds(0, 0, w, h); if (shouldValidate) { c.validate(); } c.paint(graphics); } finally { if (translated) graphics.translate(-x, -y); graphics.setClip(oldClip); } }
Uber, however, told VICE News that the 14,000 cards held no authority, since the ATU was not organizing against an employer, but a regulatory agency, that is, the Taxi Commission. Since Uber doesn't categorize its drivers as employees, organizers admit they're having trouble finding the best way to get drivers recognized. "We're asking the Commission to order Uber and Lyft and those other companies to negotiate with us, and we believe under their charter, they have the ability to do so," said local President Michael Cordeillo. The ride-share workers — categorized as "independent contractors" rather than employees by tech companies like Uber and Lyft — had joined up with the Amalgamated Transit Union Local 1181, which represents city bus drivers. Copies of over 14,000 signed union cards sat in a fat bundle on the table in the center of the demonstration, 10,000 cards thicker since May. "We demand living wage fares, no pool fares, protection from exploitation, union representation," read one big green sign held up by one Uber driver, a middle-aged black man with a tan jacket and blue pork pie hat. Drivers for the ride-hailing service Uber turned out in the streets of Queens on Tuesday morning, demanding their right to unionize outside the New York City Taxi and Limousine Commission in Long Island City. Read more Drivers for the ride-hailing service Uber turned out in the streets of Queens on Tuesday morning, demanding their right to unionize outside the New York City Taxi and Limousine Commission in Long Island City. "We demand living wage fares, no pool fares, protection from exploitation, union representation," read one big green sign held up by one Uber driver, a middle-aged black man with a tan jacket and blue pork pie hat. The ride-share workers — categorized as "independent contractors" rather than employees by tech companies like Uber and Lyft — had joined up with the Amalgamated Transit Union Local 1181, which represents city bus drivers. Copies of over 14,000 signed union cards sat in a fat bundle on the table in the center of the demonstration, 10,000 cards thicker since May. "We're asking the Commission to order Uber and Lyft and those other companies to negotiate with us, and we believe under their charter, they have the ability to do so," said local President Michael Cordeillo. Uber, however, told VICE News that the 14,000 cards held no authority, since the ATU was not organizing against an employer, but a regulatory agency, that is, the Taxi Commission. Since Uber doesn't categorize its drivers as employees, organizers admit they're having trouble finding the best way to get drivers recognized. "It's uncharted territory," said Chris Townsend, field director at the ATU. It was an old-fashioned rally. The ride-share workers, joined by bus drivers, marched in front of the Taxi Commission barking out chants from a bullhorn. Cop cars flanked either side of the street as people who worked inside the Commission building slowed down to check out the protest. A few passing Uber and Lyft drivers liked what they heard and waded into the demonstration to sign union cards. "I support this," said Jaydip Ray, 36, a skinny guy with a blue hoodie, moments after walking away from joining up, as another young man took his place. "We need benefits. Without benefits, we don't have any future." Ray is happy to be a career Uber-driver, he said, so long as he gets some protections. "I want to stay with this, if it's good and I'm making money with benefits and a future." Two or three years ago, you could make an actual living as a driver. That was after taxes, and even after you paid for the gas, tolls, car maintenance, and insurance, expenses that add up to thousands of dollars each month. (Part of the tech companies' model is passing these costs to workers.) But in January, Uber slashed its fares and rates, and now drivers are scrambling to chase their old daily income. Base fare in New York went from $3 to $2.55; the per-mile rate from $2.15 to $1.75; and the per-minute rate from 40 cents to 35 cents. "Before they lowered the rates, I used to make $400 or more than that a day," said John Zapata, 53. "Now I have to work harder than that — now sometimes there's a fare for as little as $3.00." Zapata signed up with the union three or four months back. "A full work week, without wasting or losing a day, is 60 to 70 hours," he said. "As drivers, we spend so many hours working in order to make a living when the wages are so low — the lower the wages, the harder we have to work." "They dropped the fares so much that we have to work 15, 16, 17 hours a day to make some money," said Pedro Acosta, 49. "I work around 15 hours every day, so I put in maybe 90 hours a week." An official statement from Uber on the protest read: "Uber NYC strives to offer drivers the best and most flexible earning opportunity. There is more competition for drivers in New York than ever before across every part of the commercial car industry. Making Uber the top choice for drivers is more important than ever which is why we are working closely with drivers to listen to their feedback on how we can improve the app." An Uber spokesman needled Tuesday's turnout, adding that the crowd was padded with bus drivers who stopped by to cheer it on. It's certainly true that the rally fell short of the hundreds that came out to protest when Uber slashed their fares. Acosta said his fellow drivers might have been too busy trying to make a living. "I think [drivers] think they can't come down for two hours, they don't have time," he said, adding that there wasn't space for parking for drivers to stop by. "But they know how important it is." The next crisis, Townsend says, will be when the city imposes a new 12-hour limit on how long drivers can hustle. It's meant to be for the benefit of workers, but with the way Uber and Lyft pay their drivers, the regulation would likely claw even more money away from them. Back in May, Uber agreed to let a new branch of the International Association of Machinists "represent" its drivers, but the new Independent Drivers Guild is more of labor-management relations board than an actual union. Crucially, the "guild" isn't allowed to let drivers collectively bargain for contracts and actually agreed to refrain from encouraging unionization. The ATU may not win this round, but it has tapped into a movement that isn't going away. "We're searching for some lawmaker or regulator, him or her, who wants to step up and say, 'This is an unacceptable situation,'" Townsend said. One such lawmaker is City Councilman Daneek Miller, a former president of the ATU and chair of the Labor Committee. He's looking to pass legislation akin to the bill passed by the Seattle city council last year that gave Uber and other ride-share drivers the ability to unionize. It was the first city in America to do so, and Miller hopes it's not the last. "Thirty years I've been a part of this union," he told onlookers through the megaphone. "And you've chosen the right family."
import {platform} from 'os' import * as core from '@actions/core' import {BaseContext, Cli} from 'clipanion' import {UploadCommand} from '@datadog/datadog-ci/dist/commands/dsyms/upload' // Create a local clipanion cli and register the dsyms UploadCommand. export const cli = new Cli() cli.register(UploadCommand) /** * Uploads Dsym files at the given path. * * @param path The path to the dsym files * @param dry_run If set to `true`, it will run the command without the * final step of upload. All other checks are performed. * @param context The cli command context. * @returns 0 for success, 1 for failure. */ export const upload = async (path: string, dry_run: boolean, context: BaseContext): Promise<number> => { const cmd = ['dsyms', 'upload', path] if (dry_run) cmd.push('--dry-run') return cli.run(cmd, context) } export const main = async (): Promise<void> => { try { if (platform() !== 'darwin') { throw new Error('This Action runs on macOS only.') } process.env.DATADOG_API_KEY = core.getInput('api_key', {required: true}) process.env.DATADOG_SITE = core.getInput('site') const context = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, } as BaseContext const paths = core.getMultilineInput('dsym_paths', {required: true}) const dry_run = core.getBooleanInput('dry_run') for (const path of paths) { await upload(path, dry_run, context) } } catch (error) { if (error instanceof Error) core.setFailed(error.message) } } if (require.main === module) { main() }
<reponame>wfnex/OpenBRAS<filename>src/ace/ACE_wrappers/examples/Logger/Acceptor-server/server_loggerd.cpp // server_loggerd.cpp,v 4.29 2003/12/30 23:18:59 shuston Exp // This server daemon collects, formats, and displays logging // information forwarded from client daemons running on other hosts in // the network. In addition, this example illustrates how to use the // ACE_Reactor, ACE_Acceptor, ACE_Singleton, and the ACE_Test_and_Set // components. #include "ace/OS_NS_string.h" #include "ace/Get_Opt.h" #include "ace/Acceptor.h" #include "ace/Null_Mutex.h" #include "ace/SOCK_Acceptor.h" #include "ace/Singleton.h" #include "ace/CDR_Stream.h" #include "ace/Auto_Ptr.h" #include "ace/Test_and_Set.h" // FUZZ: disable check_for_streams_include #include "ace/streams.h" #include "ace/Log_Record.h" #include "ace/Test_and_Set.h" #include "server_loggerd.h" // ---------------------------------------- // Return the port number. u_short Options::port (void) { return this->port_; } // Parse the command-line options. void Options::parse_args (int argc, ACE_TCHAR *argv[]) { this->port_ = ACE_DEFAULT_SERVER_PORT; ACE_Get_Opt get_opt (argc, argv, ACE_TEXT ("p:")); for (int c; (c = get_opt ()) != -1; ) switch (c) { case 'p': this->port_ = ACE_OS::atoi (get_opt.opt_arg ()); break; default: break; } } // ---------------------------------------- // Our Reactor Singleton. typedef ACE_Singleton<ACE_Reactor, ACE_Null_Mutex> REACTOR; // Our Options Singleton. typedef ACE_Singleton<Options, ACE_Null_Mutex> OPTIONS; // Our ACE_Test_and_Set Singleton. typedef ACE_Singleton<ACE_Test_and_Set <ACE_Null_Mutex, sig_atomic_t>, ACE_Null_Mutex> QUIT_HANDLER; // ---------------------------------------- // Specialize a Logging Acceptor. typedef ACE_Acceptor <Logging_Handler, ACE_SOCK_ACCEPTOR> Logging_Acceptor; // Default constructor. Logging_Handler::Logging_Handler (void) { } int Logging_Handler::handle_timeout (const ACE_Time_Value &, const void *arg) { #if defined (ACE_NDEBUG) ACE_UNUSED_ARG (arg); #endif /* ACE_NDEBUG */ ACE_ASSERT (arg == this); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) handling timeout from this = %@\n"), this)); return 0; } // Perform the logging record receive. int Logging_Handler::handle_input (ACE_HANDLE) { ACE_Log_Record log_record; // We need to use the old two-read trick here since TCP sockets // don't support framing natively. Allocate a message block for the // payload; initially at least large enough to hold the header, but // needs some room for alignment. ACE_Message_Block *payload_p = 0; ACE_Message_Block *header_p = 0; ACE_NEW_RETURN (header_p, ACE_Message_Block (ACE_DEFAULT_CDR_BUFSIZE), -1); auto_ptr <ACE_Message_Block> header (header_p); // Align the Message Block for a CDR stream ACE_CDR::mb_align (header.get ()); ACE_CDR::Boolean byte_order; ACE_CDR::ULong length; ssize_t count = ACE::recv_n (this->peer ().get_handle (), header->wr_ptr (), 8); switch (count) { // Handle shutdown and error cases. default: case -1: case 0: ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("server logging daemon closing down\n"))); return -1; /* NOTREACHED */ case 8: // Just fall through in this case.. break; } header->wr_ptr (8); // Reflect addition of 8 bytes. // Create a CDR stream to parse the 8-byte header. ACE_InputCDR header_cdr (header.get ()); // Extract the byte-order and use helper methods to disambiguate // octet, booleans, and chars. header_cdr >> ACE_InputCDR::to_boolean (byte_order); // Set the byte-order on the stream... header_cdr.reset_byte_order (byte_order); // Extract the length header_cdr >> length; ACE_NEW_RETURN (payload_p, ACE_Message_Block (length), -1); auto_ptr <ACE_Message_Block> payload (payload_p); // Ensure there's sufficient room for log record payload. ACE_CDR::grow (payload.get (), 8 + ACE_CDR::MAX_ALIGNMENT + length); // Use <recv_n> to obtain the contents. if (ACE::recv_n (this->peer ().get_handle (), payload->wr_ptr (), length) <= 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("recv_n()"))); return -1; } payload->wr_ptr (length); // Reflect additional bytes ACE_InputCDR payload_cdr (payload.get ()); payload_cdr.reset_byte_order (byte_order); payload_cdr >> log_record; // Finally extract the <ACE_log_record>. log_record.length (length); log_record.print (ACE_TEXT_CHAR_TO_TCHAR (this->peer_name_), 1, stderr); return 0; } int Logging_Handler::open (void *) { ACE_INET_Addr addr; if (this->peer ().get_remote_addr (addr) == -1) return -1; else { ACE_OS::strncpy (this->peer_name_, addr.get_host_name (), MAXHOSTNAMELEN + 1); if (REACTOR::instance ()->register_handler (this, READ_MASK) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%P|%t) can't register with reactor\n")), -1); else if (REACTOR::instance ()->schedule_timer (this, (const void *) this, ACE_Time_Value (2), ACE_Time_Value (2)) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%P|%t) can't register with reactor\n")), -1); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) connected with %C\n"), this->peer_name_)); return 0; } } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { // Acceptor factory. Logging_Acceptor peer_acceptor; OPTIONS::instance ()->parse_args (argc, argv); // We need to pass in REACTOR::instance () here so that we don't use // the default ACE_Reactor::instance (). if (peer_acceptor.open (ACE_INET_Addr (OPTIONS::instance ()->port ()), REACTOR::instance ()) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("open")), -1); // Register QUIT_HANDLER to receive SIGINT commands. When received, // QUIT_HANDLER becomes "set" and thus, the event loop below will // exit. else if (REACTOR::instance ()->register_handler (SIGINT, QUIT_HANDLER::instance ()) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("registering service with ACE_Reactor\n")), -1); // Run forever, performing logging service. ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) starting up server logging daemon\n"))); // Perform logging service until QUIT_HANDLER receives SIGINT. while (QUIT_HANDLER::instance ()->is_set () == 0) REACTOR::instance ()->handle_events (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) shutting down server logging daemon\n"))); return 0; } //typedef ACE_Test_and_Set<ACE_Null_Mutex, sig_atomic_t> ACE_SINGLETON_TEMPLATE_INSTANTIATE(ACE_Singleton, ACE_Reactor, ACE_Null_Mutex); ACE_SINGLETON_TEMPLATE_INSTANTIATE(ACE_Singleton, Options, ACE_Null_Mutex); #define ACE_Test_and_Set_type \ ACE_Test_and_Set<ACE_Null_Mutex, sig_atomic_t> ACE_SINGLETON_TEMPLATE_INSTANTIATE(ACE_Singleton, ACE_Test_and_Set_type, ACE_Null_Mutex);
#include "TestPrologue.h" TEST(Sampler) { string source = "uniform sampler2D texture\n" "gl_Position = ftransform\n" "gl_FragColor = texture2D texture gl_MultiTexCoord0.xy\n" ; string VS = "varying vec2 _ren_v0;\n" "void main()\n" "{\n" " gl_Position = ftransform();\n" " _ren_v0 = gl_MultiTexCoord0.xy;\n" "}\n" ; string FS = "uniform sampler2D texture;\n" "varying vec2 _ren_v0;\n" "void main()\n" "{\n" " gl_FragColor = texture2D(texture, _ren_v0);\n" "}\n" ; CHECK_COMPILE(source, VS, FS); }
Manila, June 28, 2003 (Star) Hong Kong-based East Asia Bank has closed down its representative office in the Philippines due to weak regional economic conditions. The Bangko Sentral ng Pilipinas (BSP) said EAB decided to withdraw its representative office after conducting a thorough review of its banking strategy in the region. EAB is the only Hong Kong bank in the country and with the closure of its representative office, the BSP said there are only 16 representative offices now left operating in the Philippines. The BSP said EAB’s representative office mainly provided information to its clients in the country although it did not offer banking services which only overseas banking units (OBUs) were allowed to provide. According to the BSP, EAB’s closure of its representative office marked the bank’s streamlining and the primary reason cited was the weakening of the regional economy which no longer necessitated its presence in the Philippines. Foreign banks that have initially expressed enthusiasm over the country’s effort to open up the banking industry have recently started to reassess their positions in the industry especially after Congress removed the tax-exempt status of offshore banking units and foreign currency deposit units. So far, three OBUs have closed down, namely Standard Chartered Bank of Australia, United Overseas Bank Limited and the Bank of Novascotia. The removal of OBU exemption would mean the imposition of additional taxes over and above the 10-percent tax on interest income paid by foreign banks. Congress passed the law that reinstated all other taxes that local banks pay, including taxes on income, documentary stamps and profit remittances. According to some legislators, there was no intention to remove the tax-exempt status of foreign banks but an "oversight" could result in overtaxing of OBUs and FCDUs while making other Asian countries seem more hospitable and attractive. "The loss of tax exemption simply due to an inadvertent omission will render the operations of FCDUs and OBUs unsustainable and will have serious economic consequences for the country," said BSP Governor Rafael B. Buenaventura. Earlier, Buenaventura said the failure to reinstate the previous tax-exempt status of dollar deposits would drive away OBUs and discourage FCDUs in the country. In turn, this would make the local economy susceptible to financial shocks brought about by political or economic crises.
#include <bits/stdc++.h> #include <iomanip> using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef long double LD; typedef pair<LD, LD> PLDLD; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define CLR(a) memset((a), 0 ,sizeof(a)) #define ALL(a) a.begin(),a.end() int main() { int n; cin>>n; vector<int> a(n); REP(i,n) cin>>a[i]; vector<vector<int>> g(n); REP(i,n-1) { int s,t; cin>>s>>t; s--;t--; g[s].push_back(t); g[t].push_back(s); } if(n==2) { if(a[0]==a[1]) cout<<"YES"<<endl; else cout<<"NO"<<endl; return 0; } int root=0; while(g[root].size()<=1) root++; //cout<<"root:"<<root<<endl; function<int(int,int)> dfs=[&](int v,int vs) { if(g[v].size()==1) return a[v]; int cnt=0; vector<int> c; int cmax=0; for(auto&& e:g[v]) { if(e==vs)continue; int tmp=dfs(e,v); if(tmp<0) return -1; cnt+=tmp; c.push_back(tmp); if(tmp>cmax) cmax=tmp; } /*if(g[v].size()==2) { if(a[v]!=cnt) return -1; }*/ if(a[v]>cnt) return -1; int pair=cnt-a[v]; if(cnt-cmax < pair) return -1; return a[v]*2-cnt; }; if(dfs(root,-1)==0) cout<<"YES"<<endl; else cout<<"NO"<<endl; }
package controller.menusControllers; import model.Team; public class TeamsMenuController extends MenuController { public TeamsMenuController() { super("Teams Menu"); } public String teamEnter(String teamName) { if (Team.getTeamByName(teamName) == null) { return "team with name " + teamName + " does not exist"; } else { return "team entered successfully"; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hops.transaction.context; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import io.hops.exception.LockUpgradeException; import io.hops.exception.StorageException; import io.hops.exception.TransactionContextException; import io.hops.metadata.common.FinderType; import io.hops.metadata.hdfs.dal.INodeDataAccess; import io.hops.transaction.lock.BaseINodeLock; import io.hops.transaction.lock.Lock; import io.hops.transaction.lock.TransactionLockTypes; import io.hops.transaction.lock.TransactionLocks; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hdfs.server.namenode.INode; import org.apache.hadoop.hdfs.server.namenode.INodeDirectory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class INodeContext extends BaseEntityContext<Integer, INode> { protected final static Log LOG = LogFactory.getLog(INodeContext .class); private final INodeDataAccess<INode> dataAccess; private final Map<String, INode> inodesNameParentIndex = new HashMap<>(); private final Map<Integer, List<INode>> inodesParentIndex = new HashMap<>(); private final List<INode> renamedInodes = new ArrayList<>(); public INodeContext(INodeDataAccess dataAccess) { this.dataAccess = dataAccess; } @Override public void clear() throws TransactionContextException { super.clear(); inodesNameParentIndex.clear(); inodesParentIndex.clear(); renamedInodes.clear(); } @Override public INode find(FinderType<INode> finder, Object... params) throws TransactionContextException, StorageException { INode.Finder iFinder = (INode.Finder) finder; switch (iFinder) { case ByINodeIdFTIS: return findByInodeIdFTIS(iFinder, params); case ByNameParentIdAndPartitionId: return findByNameParentIdAndPartitionIdPK(iFinder, params); } throw new RuntimeException(UNSUPPORTED_FINDER); } @Override public Collection<INode> findList(FinderType<INode> finder, Object... params) throws TransactionContextException, StorageException { INode.Finder iFinder = (INode.Finder) finder; switch (iFinder) { case ByParentIdFTIS: return findByParentIdFTIS(iFinder, params); case ByParentIdAndPartitionId: return findByParentIdAndPartitionIdPPIS(iFinder,params); case ByNamesParentIdsAndPartitionIds: return findBatch(iFinder, params); case ByNamesParentIdsAndPartitionIdsCheckLocal: return findBatchWithLocalCacheCheck(iFinder, params); } throw new RuntimeException(UNSUPPORTED_FINDER); } @Override public void remove(INode iNode) throws TransactionContextException { super.remove(iNode); inodesNameParentIndex.remove(iNode.nameParentKey()); if (isLogDebugEnabled()) { log("removed-inode", "id", iNode.getId(), "name", iNode.getLocalName(), "parent_id", iNode.getParentId(), "partition_id", iNode.getPartitionId()); } } @Override public void update(INode iNode) throws TransactionContextException { super.update(iNode); inodesNameParentIndex.put(iNode.nameParentKey(), iNode); if(isLogDebugEnabled()) { log("updated-inode", "id", iNode.getId(), "name", iNode.getLocalName(), "parent_id", iNode.getParentId(), "partition_id", iNode.getPartitionId()); } } @Override public void prepare(TransactionLocks lks) throws TransactionContextException, StorageException { // if the list is not empty then check for the lock types // lock type is checked after when list length is checked // because some times in the tx handler the acquire lock // function is empty and in that case tlm will throw // null pointer exceptions Collection<INode> removed = getRemoved(); Collection<INode> added = new ArrayList<>(getAdded()); added.addAll(renamedInodes); Collection<INode> modified = getModified(); if (lks.containsLock(Lock.Type.INode)) { BaseINodeLock hlk = (BaseINodeLock) lks.getLock(Lock.Type.INode); if (!removed.isEmpty()) { for (INode inode : removed) { TransactionLockTypes.INodeLockType lock = hlk.getLockedINodeLockType(inode); if (lock != null && lock != TransactionLockTypes.INodeLockType.WRITE && lock != TransactionLockTypes.INodeLockType.WRITE_ON_TARGET_AND_PARENT) { throw new LockUpgradeException( "Trying to remove inode id=" + inode.getId() + " acquired lock was " + lock); } } } if (!modified.isEmpty()) { for (INode inode : modified) { TransactionLockTypes.INodeLockType lock = hlk.getLockedINodeLockType(inode); if (lock != null && lock != TransactionLockTypes.INodeLockType.WRITE && lock != TransactionLockTypes.INodeLockType.WRITE_ON_TARGET_AND_PARENT) { throw new LockUpgradeException( "Trying to update inode id=" + inode.getId() + " acquired lock was " + lock); } } } } dataAccess.prepare(removed, added, modified); } @Override public void snapshotMaintenance(TransactionContextMaintenanceCmds cmds, Object... params) throws TransactionContextException { HdfsTransactionContextMaintenanceCmds hopCmds = (HdfsTransactionContextMaintenanceCmds) cmds; switch (hopCmds) { case INodePKChanged: //delete the previous row from db INode inodeBeforeChange = (INode) params[0]; INode inodeAfterChange = (INode) params[1]; super.remove(inodeBeforeChange); try { inodeAfterChange.setPartitionIdNoPersistance(INode.calculatePartitionId(inodeAfterChange.getParentId(),inodeAfterChange .getLocalName(), inodeAfterChange.myDepth())); } catch (StorageException e) { throw new TransactionContextException(e); } renamedInodes.add(inodeAfterChange); if (isLogDebugEnabled()) { log("removed-inode-snapshot-maintenance", "id", inodeBeforeChange.getId(), "name", inodeBeforeChange.getLocalName(), "parent_id", inodeBeforeChange.getParentId(), "partition_id", inodeBeforeChange .getPartitionId()); log("added-inode-snapshot-maintenance", "id", inodeAfterChange.getId(), "name", inodeAfterChange.getLocalName(), "parent_id", inodeAfterChange.getParentId(), "partition_id", inodeAfterChange.getPartitionId()); } break; case Concat: // do nothing // why? files y and z are merged into file x. // all the blocks will be added to file x and the inodes y and z will be deleted. // Inode deletion is handled by the concat function break; } } @Override Integer getKey(INode iNode) { return iNode.getId(); } private INode findByInodeIdFTIS(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { INode result = null; final Integer inodeId = (Integer) params[0]; if (contains(inodeId)) { result = get(inodeId); if(result!=null) { hit(inodeFinder, result, "id", inodeId, "name", result.getLocalName(), "parent_id", result.getParentId(), "partition_id", result.getPartitionId()); }else{ hit(inodeFinder, result, "id", inodeId); } } else { aboutToAccessStorage(inodeFinder, params); result = dataAccess.findInodeByIdFTIS(inodeId); gotFromDB(inodeId, result); if (result != null) { inodesNameParentIndex.put(result.nameParentKey(), result); miss(inodeFinder, result, "id", inodeId, "name", result.getLocalName(), "parent_id", result.getParentId(), "partition_id", result.getPartitionId()); }else { miss(inodeFinder, result, "id"); } } return result; } private INode findByNameParentIdAndPartitionIdPK(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { INode result = null; final String name = (String) params[0]; final Integer parentId = (Integer) params[1]; final Integer partitionId = (Integer) params[2]; Integer possibleInodeId = null; if (params.length == 4) { possibleInodeId = (Integer) params[3]; } final String nameParentKey = INode.nameParentKey(parentId, name); if (inodesNameParentIndex.containsKey(nameParentKey)) { result = inodesNameParentIndex.get(nameParentKey); if (!preventStorageCalls() && (currentLockMode.get() == LockMode.WRITE_LOCK)) { //trying to upgrade lock. re-read the row from DB aboutToAccessStorage(inodeFinder, params); result = dataAccess.findInodeByNameParentIdAndPartitionIdPK(name, parentId, partitionId); gotFromDBWithPossibleInodeId(result, possibleInodeId); inodesNameParentIndex.put(nameParentKey, result); missUpgrade(inodeFinder, result, "name", name, "parent_id", parentId, "partition_id", partitionId); } else { hit(inodeFinder, result, "name", name, "parent_id", parentId, "partition_id", partitionId); } } else { if (!isNewlyAdded(parentId) && !containsRemoved(parentId, name)) { if (canReadCachedRootINode(name, parentId)) { result = RootINodeCache.getRootINode(); LOG.debug("Reading root inode from the cache. "+result); } else { aboutToAccessStorage(inodeFinder, params); result = dataAccess.findInodeByNameParentIdAndPartitionIdPK(name, parentId, partitionId); } gotFromDBWithPossibleInodeId(result, possibleInodeId); inodesNameParentIndex.put(nameParentKey, result); miss(inodeFinder, result, "name", name, "parent_id", parentId, "partition_id", partitionId, "possible_inode_id",possibleInodeId); } } return result; } private List<INode> findByParentIdFTIS(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { final Integer parentId = (Integer) params[0]; List<INode> result = null; if (inodesParentIndex.containsKey(parentId)) { result = inodesParentIndex.get(parentId); hit(inodeFinder, result, "parent_id", parentId ); } else { aboutToAccessStorage(inodeFinder, params); result = syncInodeInstances( dataAccess.findInodesByParentIdFTIS(parentId)); inodesParentIndex.put(parentId, result); miss(inodeFinder, result, "parent_id", parentId); } return result; } private List<INode> findByParentIdAndPartitionIdPPIS(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { final Integer parentId = (Integer) params[0]; final Integer partitionId = (Integer) params[1]; List<INode> result = null; if (inodesParentIndex.containsKey(parentId)) { result = inodesParentIndex.get(parentId); hit(inodeFinder, result, "parent_id", parentId, "partition_id",partitionId); } else { aboutToAccessStorage(inodeFinder, params); result = syncInodeInstances( dataAccess.findInodesByParentIdAndPartitionIdPPIS(parentId, partitionId)); inodesParentIndex.put(parentId, result); miss(inodeFinder, result, "parent_id", parentId, "partition_id",partitionId); } return result; } private List<INode> findBatch(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { final String[] names = (String[]) params[0]; final int[] parentIds = (int[]) params[1]; final int[] partitionIds = (int[]) params[2]; return findBatch(inodeFinder, names, parentIds, partitionIds); } private List<INode> findBatchWithLocalCacheCheck(INode.Finder inodeFinder, Object[] params) throws TransactionContextException, StorageException { final String[] names = (String[]) params[0]; final int[] parentIds = (int[]) params[1]; final int[] partitionIds = (int[]) params[2]; List<String> namesRest = Lists.newArrayList(); List<Integer> parentIdsRest = Lists.newArrayList(); List<Integer> partitionIdsRest = Lists.newArrayList(); List<Integer> unpopulatedIndeces = Lists.newArrayList(); List<INode> result = new ArrayList<>(Collections.<INode>nCopies(names .length, null)); for(int i=0; i<names.length; i++){ final String nameParentKey = INode.nameParentKey(parentIds[i], names[i]); INode node = inodesNameParentIndex.get(nameParentKey); if(node != null){ result.set(i, node); hit(inodeFinder, node, "name", names[i], "parent_id", parentIds[i], "partition_id", partitionIds[i]); }else{ namesRest.add(names[i]); parentIdsRest.add(parentIds[i]); partitionIdsRest.add(partitionIds[i]); unpopulatedIndeces.add(i); } } if(unpopulatedIndeces.isEmpty()){ return result; } if(unpopulatedIndeces.size() == names.length){ return findBatch(inodeFinder, names, parentIds, partitionIds); }else{ List<INode> batch = findBatch(inodeFinder, namesRest.toArray(new String[namesRest.size()]), Ints.toArray(parentIdsRest), Ints.toArray(partitionIdsRest)); Iterator<INode> batchIterator = batch.listIterator(); for(Integer i : unpopulatedIndeces){ result.set(i, batchIterator.next()); } return result; } } private List<INode> findBatch(INode.Finder inodeFinder, String[] names, int[] parentIds, int[] partitionIds) throws StorageException { INode rootINode = null; if (canReadCachedRootINode(names[0], parentIds[0])) { rootINode = RootINodeCache.getRootINode(); LOG.debug("Reading root inode from the cache "+rootINode); if (rootINode != null) { names = Arrays.copyOfRange(names, 1, names.length); parentIds = Arrays.copyOfRange(parentIds, 1, parentIds.length); partitionIds = Arrays.copyOfRange(partitionIds, 1, partitionIds.length); } } List<INode> batch = dataAccess.getINodesPkBatched(names, parentIds, partitionIds); miss(inodeFinder, batch, "names", Arrays.toString(names), "parent_ids", Arrays.toString(parentIds), "partition_ids", Arrays.toString(partitionIds)); if (rootINode != null) { batch.add(0, rootINode); } return syncInodeInstances(batch); } private List<INode> syncInodeInstances(List<INode> newInodes) { List<INode> finalList = new ArrayList<>(newInodes.size()); for (INode inode : newInodes) { if (isRemoved(inode.getId())) { continue; } gotFromDB(inode); finalList.add(inode); String key = inode.nameParentKey(); if (inodesNameParentIndex.containsKey(key)) { if (inodesNameParentIndex.get(key) == null) { inodesNameParentIndex.put(key, inode); } } else { inodesNameParentIndex.put(key, inode); } } //Collections.sort(finalList, INode.Order.ByName); return finalList; } private boolean containsRemoved(final Integer parentId, final String name) { return contains(new Predicate<ContextEntity>() { @Override public boolean apply(ContextEntity input) { INode iNode = input.getEntity(); return input.getState() == State.REMOVED && iNode.getParentId() == parentId && iNode.getLocalName().equals(name); } }); } private void gotFromDBWithPossibleInodeId(INode result, Integer possibleInodeId) { if (result == null && possibleInodeId != null) { gotFromDB(possibleInodeId, result); } else { gotFromDB(result); } } private boolean canReadCachedRootINode(String name, int parentId) { if (name.equals(INodeDirectory.ROOT_NAME) && parentId == INodeDirectory.ROOT_PARENT_ID) { if (RootINodeCache.isRootInCache() && currentLockMode.get() == LockMode.READ_COMMITTED) { return true; } else { return false; } } return false; } }
<filename>src/ecs/ecs.c #include "ecs.h" #include <assert.h> #include <memory.h> #include <string.h> #include "../utils/macro.h" #include "private/componentsInit.h" #define ILLEGAL_ENTITY MAX_ENTITIES ECS ecsInit() { ECS res; memset(res.componentLists, 0, COMPONENT_COUNT * sizeof(ComponentList)); memset(res.usedComponentFlag, 0, MAX_ENTITIES * sizeof(Bitset)); res.flagEntities = bitsetInit(); bitsetAlloc(&res.flagEntities, MAX_ENTITIES); res.capacity = MAX_ENTITIES; res.nextEntity = 0; initComponets(&res); return res; } CVOX_STATIC_INLINE u32 _nextEntity(ECS *ecs) { for (size_t i = 0; i < ecs->flagEntities.size; i++) { if (!bitsetTest(&ecs->flagEntities, i)) { return i; } } return ILLEGAL_ENTITY; } Entity ecsNewEntity(ECS *ecs) { Entity res = _nextEntity(ecs); assert(res < MAX_ENTITIES); if (!ecs->usedComponentFlag[res].data) bitsetAlloc(&ecs->usedComponentFlag[res], MAX_COMPONENTS); bitsetSet(&ecs->flagEntities, res); return res; } bool ecsHasComponent(ECS *ecs, Entity entity, u32 component) { assert(ecs); return bitsetTest(&ecs->usedComponentFlag[entity], component); } void *ecsAddComponent(ECS *ecs, Entity entity, u32 component, void *data) { assert(ecs); if (ecsHasComponent(ecs, entity, component)) return (void*)(0 - 1); ComponentList *list = &ecs->componentLists[component]; if (data != NULL) memcpy(list->components + entity * list->typeSize, data, list->typeSize); bitsetSet(&ecs->usedComponentFlag[entity], component); return (list->components + entity * list->typeSize); } void *ecsGetComponent(ECS *ecs, Entity entity, u32 component) { assert(ecsHasComponent(ecs, entity, component)); return (ecs->componentLists[component].components + entity * ecs->componentLists->typeSize); } void ecsFree(ECS *ecs) { assert(ecs); bitsetFree(&ecs->flagEntities); for (size_t i = 0; i < MAX_ENTITIES; i++) bitsetFree(&ecs->usedComponentFlag[i]); for (size_t i = 0; i < MAX_COMPONENTS; i++) free(ecs->componentLists[i].components); }
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.common.server.bo; import com.navercorp.pinpoint.common.PinpointConstants; import com.navercorp.pinpoint.common.util.BytesUtils; import com.navercorp.pinpoint.common.server.util.RowKeyUtils; import com.navercorp.pinpoint.common.util.TimeUtils; import java.util.Objects; /** * @author emeroad * @author jaehong.kim */ public class ApiMetaDataBo { private String agentId; private long startTime; private int apiId; private String apiInfo; private int lineNumber = -1; private MethodTypeEnum methodTypeEnum = MethodTypeEnum.DEFAULT; public ApiMetaDataBo() { } public ApiMetaDataBo(String agentId, long startTime, int apiId) { this.agentId = Objects.requireNonNull(agentId, "agentId"); this.startTime = startTime; this.apiId = apiId; } public String getAgentId() { return agentId; } public void setAgentId(String agentId) { this.agentId = agentId; } public int getApiId() { return apiId; } public void setApiId(int apiId) { this.apiId = apiId; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public String getApiInfo() { return apiInfo; } public void setApiInfo(String apiInfo) { this.apiInfo = apiInfo; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public MethodTypeEnum getMethodTypeEnum() { return methodTypeEnum; } public void setMethodTypeEnum(MethodTypeEnum methodTypeEnum) { this.methodTypeEnum = Objects.requireNonNull(methodTypeEnum, "methodTypeEnum"); } public String getDescription() { if (lineNumber != -1) { return apiInfo + ":" + lineNumber; } return apiInfo; } public void readRowKey(byte[] bytes) { this.agentId = BytesUtils.safeTrim(BytesUtils.toString(bytes, 0, PinpointConstants.AGENT_NAME_MAX_LEN)); this.startTime = TimeUtils.recoveryTimeMillis(readTime(bytes)); this.apiId = readKeyCode(bytes); } private static long readTime(byte[] rowKey) { return BytesUtils.bytesToLong(rowKey, PinpointConstants.AGENT_NAME_MAX_LEN); } private static int readKeyCode(byte[] rowKey) { return BytesUtils.bytesToInt(rowKey, PinpointConstants.AGENT_NAME_MAX_LEN + BytesUtils.LONG_BYTE_LENGTH); } public byte[] toRowKey() { return RowKeyUtils.getMetaInfoRowKey(this.agentId, this.startTime, this.apiId); } @Override public String toString() { final StringBuilder sb = new StringBuilder("ApiMetaDataBo{"); sb.append("agentId='").append(agentId).append('\''); sb.append(", startTime=").append(startTime); sb.append(", apiId=").append(apiId); sb.append(", apiInfo='").append(apiInfo).append('\''); sb.append(", lineNumber=").append(lineNumber); sb.append(", methodTypeEnum=").append(methodTypeEnum); sb.append('}'); return sb.toString(); } }
An emergency situation on the campus of a Boston University on Friday morning was a hoax. Boston Police Commissioner William Evans said a man called Boston University police at 8:30 a.m. saying he was barricaded in a “booby-trapped room” on the fourth floor of the Mugar Memorial Library. Evans said the man called back a few minutes later to say he was armed and that he had shot a hostage. The school sent an alert warning students to stay away from the library at 771 Commonwealth Ave as police searched the building. “It was a phone call, and we were on the line with the individual, so we treated it like it was the real deal,” Evans said. “It was so detailed that we had to take it serious.” BU spokesman Colin Riley said police evacuated the library and student union. "It was not a robocall. It was an actual person on the other end of the line answering questions," said Boston University Chief of Police Scott Pare, adding that the caller identification was blocked. The area was cleared after determining that the threat was a hoax. "Although an investigation is ongoing, we believe that the call came from an international location and was a hoax," BU President Robert Brown said in a letter to the campus. "The nature of the threat required that the buildings be immediately closed and searched by the police." "What we practiced last month in a drill -- actually in the same, exact building -- it worked, unfortunately, perfectly for us with Boston police, State Police and Brookline police all showing up," Pare said. Officials said the caller had an accent, and they are working to trace the hoax call. An emergency situation on the campus of a Boston University on Friday morning was a hoax. Boston Police Commissioner William Evans said a man called Boston University police at 8:30 a.m. saying he was barricaded in a “booby-trapped room” on the fourth floor of the Mugar Memorial Library. Advertisement Evans said the man called back a few minutes later to say he was armed and that he had shot a hostage. The school sent an alert warning students to stay away from the library at 771 Commonwealth Ave as police searched the building. “It was a phone call, and we were on the line with the individual, so we treated it like it was the real deal,” Evans said. “It was so detailed that we had to take it serious.” BU spokesman Colin Riley said police evacuated the library and student union. "It was not a robocall. It was an actual person on the other end of the line answering questions," said Boston University Chief of Police Scott Pare, adding that the caller identification was blocked. The area was cleared after determining that the threat was a hoax. "Although an investigation is ongoing, we believe that the call came from an international location and was a hoax," BU President Robert Brown said in a letter to the campus. "The nature of the threat required that the buildings be immediately closed and searched by the police." "What we practiced last month in a drill -- actually in the same, exact building -- it worked, unfortunately, perfectly for us with Boston police, State Police and Brookline police all showing up," Pare said. Officials said the caller had an accent, and they are working to trace the hoax call. AlertMe
package br.com.jornadacolaborativa.microservice.consumer.model; import java.io.Serializable; import lombok.Data; @Data public class Payment implements Serializable { private String cPF; private String nome; private String numeroCartaoCredito; private String dataValidade; private String codigoVerificador; }
The reason your dishes have been turning out filmy, dirty and spotted is because of a change in the detergent. In July 2010, sixteen states banned the use of phosphates in dishwasher detergent because of its effect on waterways. Since then, the major manufacturers of detergents have stopped using them. Phosphates encourage algea growth, which hogs oxygen in the water away from fish. Many places (including Columbia) treat the water to remove some of the phosphate. I am not a card-carrying member of the Sierra Club, so this is the extent of my knowledge on this angle of the story. Where my expertise lies is in the much-less-scientific but very valuable role as Head Dishwasher of my house. So, of course I got annoyed when my dishes seemed to retain many of the crumbs and smears they had before being washed. After a few months of steady decline on the part of the dishwasher, I feared the worst. I called Downtown Appliance, fully expecting the service call to result in the purchase of a new machine. It turns out that the only problem I have with my dishwasher is that it is chock full of calcium deposits. I kind of knew this, but I had tried pouring a cup of CLR or vinegar into the tub and running a cycle, with little to no improvement. For about $70, I learned that I need to use tons more vinegar and add phosphates to my detergent to keep the calcium deposits from clogging up the appliance (thereby rendering it totally ineffective). The EPA ban on phosphates only applies to items sold as detergent, so "additives" slip under the wire. I bought three boxes of Finish Glass Magic last week and my dishes have never looked so shiny. 1. Set an EMPTY dishwasher to the rinse cycle. Allow the machine to drain. When it starts to fill with water (you can tell by the sound), stop the machine and add an entire gallon of white vinegar. Run the machine until it finishes filling and starts to rinse. Stop the machine and let it sit overnight. In the morning, finish the cycle. You can now put dishes in it and wash them as usual. It will only smell like vinegar until you wash once. 3. In the meantime, get some phosphates. You can buy Glass Magic by Finish or a phosphate product at Lowe's. I stumbled upon some helpful advice and entertaining banter in an appliance blog. Do I feel bad about algae growing in the area? A little. Am I happy to have saved the landfill from a perfectly good dishwasher or one million paper plates and plastic forks per year? For sure. I'm sure there are plenty of green eco-snobs out there who will judge me for making my own "Cascade Moonshine" during the era of phosphate prohibition. Those people should use their energy to promote development of new phosphate-free detergents that actually work. Or, they could encourage the manufacturers of dishwashers to tweak their products to withstand the new standards. If you need clean dishes but feel guilty about having them, you can always wash them by hand.
/****************************************************************************************************/ /** * CANopen_NmtBootup() * * @brief Performs the bootup protocol to the configured CAN bus. * * @param p_nmt Pointer to NMT structure. * * @param p_err Error pointer. * * @note (1) The bootup protocol is used to signal that a NMT slave has entered the node state * PRE-OPERATIONAL after the state INITIALISING. *******************************************************************************************************/ void CANopen_NmtBootup(CANOPEN_NMT *p_nmt, RTOS_ERR *p_err) { CANOPEN_NODE_HANDLE handle; CANOPEN_IF_FRM frm; CANOPEN_NODE_HANDLE_SET(handle, p_nmt->NodePtr); if (p_nmt->State == CANOPEN_INIT) { CANopen_NmtStateSet(handle, CANOPEN_PREOP, p_err); if (RTOS_ERR_CODE_GET(*p_err) != RTOS_ERR_NONE) { return; } CANOPEN_FRM_SET_COB_ID(&frm, CANOPEN_COB_ID_NMT_ERR_CTRL_START + p_nmt->NodePtr->NodeId); CANOPEN_FRM_SET_DLC(&frm, 1); CANOPEN_FRM_SET_BYTE(&frm, 0, 0); CANopen_IfWr(&p_nmt->NodePtr->If, &frm, p_err); } else { RTOS_ERR_SET(*p_err, RTOS_ERR_INVALID_STATE); } }
#ifndef __VERTEX_ARRAY__ #define __VERTEX_ARRAY__ struct attribute_array{ unsigned int stride; unsigned int components; er_Bool enabled; float *pointer; }; struct er_VertexArray{ struct attribute_array vertex; struct attribute_array normal; struct attribute_array color; struct attribute_array tex_coord; struct attribute_array fog_coord; }; extern struct er_VertexArray *current_vertex_array; void vertex_assembly(struct er_VertexArray* vertex_array, struct er_VertexInput *vertex, unsigned int vertex_index); #endif
/** * Returns true if the given signature is valid for the bytes passed to update. */ public boolean validate(byte[] signature) { boolean ret = false; try { ret = this.signature.verify(signature); } catch (Exception x) { DSException.throwRuntime(x); } return ret; }
<reponame>kjthegod/chromium<gh_stars>1000+ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from appengine_wrappers import db from appengine_wrappers import BlobReferenceProperty BLOB_REFERENCE_BLOBSTORE = 'BlobReferenceBlobstore' class _Model(db.Model): key_ = db.StringProperty() value = BlobReferenceProperty() class BlobReferenceStore(object): """A wrapper around the datastore API that can store blob keys. """ def _Query(self, namespace, key): return _Model.gql('WHERE key_ = :1', self._MakeKey(namespace, key)).get() def _MakeKey(self, namespace, key): return '.'.join((namespace, key)) def Set(self, namespace, key, value): _Model(key_=self._MakeKey(namespace, key), value=value).put() def Get(self, namespace, key): result = self._Query(namespace, key) if not result: return None return result.value def Delete(self, namespace, key): result = self._Query(namespace, key) if not result: return None blob_key = result.value result.delete() return blob_key
<reponame>lbfjoin/JavaSEcode package com.company.exercise; /** * @author lbf * @date 2020/7/26 15:12 */ public class Student extends Person { private int grade; public Student(){ } public Student(String name,int age,int grade){ super(name,age); this.grade = grade; } public int getGrade(){ return grade; } public void setGrade(){ this.grade = grade; } @Override public void showMsg() { System.out.println(getName()+"同学" + ",考试得了:" + grade + "分"); } }
Hyaluronate-gold nanoparticle/tocilizumab complex for the treatment of rheumatoid arthritis. Rheumatoid arthritis (RA) is a chronic inflammatory immune disease causing the inflammation of synovial membrane and the articular cartilage destruction. In this work, hyaluronate-gold nanoparticle/Tocilizumab (HA-AuNP/TCZ) complex was prepared for the treatment of RA. AuNP was used as a drug carrier with antiangiogenic effect. TCZ is a humanized monoclonal antibody against the interleukin-6 (IL-6) receptor and used as an immunosuppressive drug by interfering IL-6 in the pathogenesis of RA. HA is known to have cartilage-protective and lubricant effects. HA was modified with cystamine via reductive amination, which was reduced with dithiothreitol (DTT) to prepare end-group thiolated HA (HA-SH). AuNP was chemically modified with HA-SH and physically modified with TCZ. The formation of HA-AuNP/TCZ complex was corroborated by UV-vis spectroscopy, dynamic light scattering (DLS), and transmission electron microscopy (TEM). The therapeutic effect of HA-AuNP/TCZ complex on RA was confirmed in collagen-induced arthritis (CIA) model mice by ELISA, histological, and Western blot analyses.
(a) Field of the Invention This invention relates to chewable calcium carbonate-containing antacid tablets. (b) Description of the Prior Art The use of calcium carbonate as the effective acid neutralizing agent in antacid tablets is known. The problem with calcium carbonate as an ingredient in antacid tablets, however, is that, unless formulated in special ways, it produces tablets which taste gritty and chalky and which thus lack the desirable quality in chewable antacid tablets known as good "mouthfeel". The problem of overcoming this undesirable gritty and chalky taste in chewable calcium carbonate-containing antacid tablets has either been ignored by the prior art, or the problem has been addressed by use of flavoring agents or other ingredients intended to mask the undesirable taste. Thus neither Palermo, U.S. Pat. No. 3,384,546, which discloses, in Example 6, a chewable antacid tablet containing calcium carbonate, magnesium trisilicate, mannitol, sorbitol, sodium saccharin, mint flavoring and magnesium stearate, nor British Pat. No. 1,056,212 which discloses the use of a combination of urea and glycine as an extended buffering agent for calcium carbonate, addresses the question of the chalky taste of calcium carbonate containing antacids. Diamond et al., U.S. Pat. No. 3,843,778, which discloses the use of calcium carbonate as one of several "preferred" ingredients for antacids, overcomes the taste problem by coating the calcium carbonate particles with oil. The particle size of the antacid ingredient is disclosed as being in the range from 0.5 to 300 microns, although no reason for the particular choice of particle size is given. In British Pat. No. 1,401,256 the chalky taste of calcium carbonate-containing antacids is overcome by spray drying the calcium carbonate with a surfactant which also aids in dissolution of the tablet. Granatek, U.S. Pat. No. 3,452,138 teaches that mannitol provides a very astringent tablet which must be taken with water, while Rubino, U.S. Pat. No. 4,115,553 discloses the use of basic aluminum bicarbonate/carbonate co-dried with a di- or trihydroxyalcohol to provide chewable antacid tablets with a good disintegration rate. The use of mannitol alone or in combination with sorbitol is also described, and sucrose is disclosed as an excipient that can be used either instead of, or in combination with, mannitol. A number of publications have reported studies comparing the relative antacid efficacies of calcium carbonate and other acid neutralizing agents. For example Rider et al., Clin, Med., 73, 44-46 (1966) describe comparative tests in patients suffering from various stomach ailments using antacid tablets made either from calcium cabonate, magnesium carbonate or a powdered milk/cream formula; Broda et al., Farm. Pol., 36(4), 215-219 (1980); C.A., 93, 173683g (1980) describe tests to determine the relative acid neutralizing capabilities of different antacids containing either magnesium oxide, aluminum hydroxide, magnesium carbonate, basic bismuth nitrate, magnesium hydroxide, calcium carbonate or sodium bicarbonate; Van de Loo, Munchen med. Wschr., 118, 271-274 (1976) report the results of the clinical treatment of ulcerous diseases with antacids containing either aluminum hydroxide, magnesium carbonate or calcium carbonate; and Smyth et al., J. Pharm. Sci., 65 (7), 1045-1047 (1976) disclose the results of a study of the correlation between in vitro and in vivo methods for assessing antacids containing either magnesium hydroxide, aluminum hydroxide or calcium carbonate. Other publications have reported studies on various physical properties of calcium carbonate-containing antacids. For example Madee et al., Arzneimittel Forsch., 25 (1), 122-123 (1975) report a comparison of the disintegration rates, as measured by an intragastric pH probe, of two formulations of calcium carbonate-containing antacid tablets, one in which the particles were wax coated and the other in which they were uncoated; and Salakawy et al., Pharmazie, 27 (9), 595-599 (1972) report the results of a study of the cause of darkening of calcium carbonate/glycine-containing antacid tablets in the presence of aldo or keto sugars.
The characteristics of peptide uptake in Streptococcus faecalis: studies on the transport of natural peptides and antibacterial phosphonopeptides. Transport of natural peptides and antibacterial phosphonopeptide analogues was studied in Streptococcus faecalis ATCC 9790. Competition studies, and the isolation of peptide-transport deficient mutants, indicate the presence of two peptide permeases. One is a high-rate system used by dipeptides, and to a lesser extent tripeptides; the other is a low-rate oligopeptide system. Following uptake, peptides are cleaved and their amino acid residues may undergo rapid exodus. Different strains of S. faecalis differ in their rates of peptide transport.
// TODO(kortschak): Use cmpimg when rings lives in plot. func equalImage(raw1, raw2 []byte) (bool, error) { v1, _, err := image.Decode(bytes.NewReader(raw1)) if err != nil { return false, err } v2, _, err := image.Decode(bytes.NewReader(raw2)) if err != nil { return false, err } return reflect.DeepEqual(v1, v2), nil }
package tool.clients.forms; import java.io.PrintStream; import java.util.Hashtable; import java.util.Vector; import java.util.concurrent.CountDownLatch; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javafx.application.Platform; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import tool.clients.Client; import tool.clients.EventHandler; import tool.xmodeler.XModeler; import xos.Message; import xos.Value; public class FormsClient extends Client { public FormsClient() { super("com.ceteva.forms"); setDebug(true); theClient = this; } public static void start(TabPane tabFolder) { FormsClient.tabFolder = tabFolder; } public static final int HIGH_RESOLUTION_FACTOR_OLD = 2; public static int getDeviceZoomPercent() { return XModeler.getDeviceZoomPercent(); } public static FormsClient theClient() { return theClient; } static FormsClient theClient; static TabPane tabFolder; static Hashtable<String, Tab> tabs = new Hashtable<String, Tab>(); static Vector<Form> forms = new Vector<Form>(); static Hashtable<String, FormTools> toolDefs = new Hashtable<String, FormTools>(); private void addComboItem(Message message) { String parentId = message.args[0].strValue(); String value = message.args[1].strValue(); addComboItem(parentId, value); } private void addComboItem(final String parentId, final String value) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.addComboItem(parentId, value); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void addItem(Message message) { if (message.arity == 2) addComboItem(message); else addListItem(message); } private void addListItem(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); String value = message.args[2].strValue(); addListItem(parentId, id, value); } private void addListItem(final String parentId, final String id, final String value) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.addListItem(parentId, id, value); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void addNodeWithIcon(Message message) { String parentId = message.args[0].strValue(); String nodeId = message.args[1].strValue(); String text = message.args[2].strValue(); boolean editable = message.args[3].boolValue; String icon = message.args[4].strValue(); int index = -1; if (message.arity == 6) index = message.args[5].intValue; addNodeWithIcon(parentId, nodeId, text, editable, icon, index); } private void addNodeWithIcon(final String parentId, final String nodeId, final String text, final boolean editable, final String icon, final int index) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newNodeWithIcon(parentId, nodeId, text, editable, icon, index); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } public Value callMessage(Message message) { if (message.hasName("getText")) return getText(message); else if (message.hasName("getTextDimension")) throw new RuntimeException("The method getTextDimension(message) was removed."); // return getTextDimension(message); else return super.callMessage(message); } private Value getText(Message message) { final String id = message.args[0].strValue(); final String[] text = new String[] { "" }; CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) { String textIn = form.getText(id); if (textIn != null) text[0] = textIn; } l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } return new Value(text[0]); } private void clearForm(Message message) { String id = message.args[0].strValue(); final Form form = getForm(id); if (form != null) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { form.clear(); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } else System.err.println("cannot find form to clear " + id); } private Form getForm(String id) { for (Form form : forms) if (form.getId().equals(id)) return form; return null; } private FormTools getFormTools(String id) { if (toolDefs.containsKey(id)) return toolDefs.get(id); else { FormTools formTools = new FormTools(id); toolDefs.put(id, formTools); return formTools; } } private void inflateButton(String parentId, Node button) { String id = XModeler.attributeValue(button, "id"); String text = XModeler.attributeValue(button, "text"); newButton(parentId, id, text); } private void inflateCheck(String parentId, Node check) { String id = XModeler.attributeValue(check, "id"); boolean checked = XModeler.attributeValue(check, "checked").equals("true"); String labelText = XModeler.attributeValue(check, "label"); newCheckBox(parentId, id, checked, labelText); } private void inflateCombo(String parentId, Node combo) { String id = XModeler.attributeValue(combo, "id"); newComboBox(parentId, id); NodeList items = combo.getChildNodes(); for (int i = 0; i < items.getLength(); i++) { Node item = items.item(i); addComboItem(id, XModeler.attributeValue(item, "item")); } } private void inflateForm(Node form) { String id = XModeler.attributeValue(form, "id"); String label = XModeler.attributeValue(form, "label"); boolean selected = XModeler.attributeValue(form, "selected").equals("true"); newForm(id, label, selected); NodeList elements = form.getChildNodes(); for (int i = 0; i < elements.getLength(); i++) inflateFormElement(id, elements.item(i)); } private void inflateFormClientElement(Node element) { if (element.getNodeName().equals("Form")) inflateForm(element); if (element.getNodeName().equals("FormTools")) inflateFormTools(element); } private void inflateFormElement(String parentId, Node element) { if (element.getNodeName().equals("TextField")) inflateTextField(parentId, element); else if (element.getNodeName().equals("Label")) inflateLabel(parentId, element); else if (element.getNodeName().equals("TextBox")) inflateTextBox(parentId, element); else if (element.getNodeName().equals("Combo")) inflateCombo(parentId, element); else if (element.getNodeName().equals("Check")) inflateCheck(parentId, element); else if (element.getNodeName().equals("Button")) inflateButton(parentId, element); else if (element.getNodeName().equals("Tree")) inflateTree(parentId, element); else if (element.getNodeName().equals("List")) inflateList(parentId, element); else System.err.println("Unknown type of form element: " + element.getNodeName()); } private void inflateFormTools(Node formTools) { String id = XModeler.attributeValue(formTools, "id"); FormTools tools = getFormTools(id); NodeList children = formTools.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); String toolId = XModeler.attributeValue(node, "id"); String event = XModeler.attributeValue(node, "event"); // String icon = XModeler.attributeValue(node, "icon"); tools.addTool(event, toolId); } } private void inflateLabel(String parentId, Node label) { String id = XModeler.attributeValue(label, "id"); String string = XModeler.attributeValue(label, "string"); System.out.println("InflateLabel: " + string); newText(parentId, id, string); getForm(parentId).getLabels().get(id).setText(string); } private void inflateList(String parentId, Node list) { String id = XModeler.attributeValue(list, "id"); String labelText = XModeler.attributeValue(list, "label"); newList(parentId, id, labelText); NodeList items = list.getChildNodes(); for (int i = 0; i < items.getLength(); i++) { String itemId = XModeler.attributeValue(items.item(i), "id"); String value = XModeler.attributeValue(items.item(i), "value"); addListItem(parentId, itemId, value); } } private void inflateTextBox(String parentId, Node textBox) { String id = XModeler.attributeValue(textBox, "id"); String string = XModeler.attributeValue(textBox, "string"); boolean editable = XModeler.attributeValue(textBox, "editable").equals("true"); String labelText = XModeler.attributeValue(textBox, "label"); newTextBox(parentId, id, editable, labelText); getForm(parentId).getBoxes().get(id).setText(string); } private void inflateTextField(String parentId, Node textField) { String id = XModeler.attributeValue(textField, "id"); String string = XModeler.attributeValue(textField, "string"); boolean editable = XModeler.attributeValue(textField, "editable").equals("true"); String labelText = XModeler.attributeValue(textField, "label"); newTextField(parentId, id, editable, labelText); getForm(parentId).getTextFields().get(id).setText(string); } private void inflateTree(String parentId, Node tree) { String id = XModeler.attributeValue(tree, "id"); newTree(parentId, id, true); inflateTreeItems(tree); } private void inflateTreeItems(Node node) { String id = XModeler.attributeValue(node, "id"); NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String childId = XModeler.attributeValue(child, "id"); String text = XModeler.attributeValue(child, "text"); String image = XModeler.attributeValue(child, "image"); boolean expanded = XModeler.attributeValue(child, "expanded").equals("true"); addNodeWithIcon(id, childId, text, expanded, image, i); inflateTreeItems(child); } } public void inflateXML(final Document doc) { // CountDownLatch l = new CountDownLatch(1); // Platform.runLater(() ->{ try { NodeList formClients = doc.getElementsByTagName("Forms"); if (formClients.getLength() == 1) { Node formClient = formClients.item(0); NodeList forms = formClient.getChildNodes(); for (int i = 0; i < forms.getLength(); i++) { Node element = forms.item(i); inflateFormClientElement(element); } } else System.err.println("expecting exactly 1 editor client got: " + formClients.getLength()); } catch (Throwable t) { t.printStackTrace(System.err); } } private void newButton(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); String label = message.args[2].strValue(); int zoom = getDeviceZoomPercent(); newButton(parentId, id, label); } private void newButton(final String parentId, final String id, final String label) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newButton(parentId, id, label); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void newCheckBox(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); boolean checked = message.args[2].boolValue; String labelText = message.args[3].strValue(); newCheckBox(parentId, id, checked, labelText); } private void newCheckBox(final String parentId, final String id, final boolean checked, final String labelText) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newCheckBox(parentId, id, checked, labelText); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void newComboBox(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); newComboBox(parentId, id); } private void newComboBox(final String parentId, final String id) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newComboBox(parentId, id); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void newForm(Message message) { String id = message.args[0].strValue(); // String type = message.args[1].strValue(); // needed? String label = message.args[2].strValue(); System.err.println("*** NEW FORM *** " + id + " *** " + label + " ***"); newForm(id, label, true); System.err.println("NEW FORM done"); } private void newForm(final String id, final String label, final boolean selected) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { Tab tabItem = new Tab(label); tabFolder.getTabs().add(tabItem); tabs.put(id, tabItem); Form form = new Form(tabItem, id); forms.add(form); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void newList(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); String labelText = message.args[2].strValue(); newList(parentId, id, labelText); } private void newList(String parentId, String id, String labelText) { for (Form form : forms) form.newList(parentId, id, labelText); } private void newText(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); String string = message.args[2].strValue(); newText(parentId, id, string); } private void newText(final String parentId, final String id, final String string) { final Form form = getForm(parentId); if (form != null) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { form.newText(id, string); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } else System.err.println("cannot find text parent " + parentId); } private void newTextBox(Message message) { String parentId = message.args [0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); boolean editable = message.args[2].boolValue; String labelText = message.args[3].strValue(); newTextBox(parentId, id, editable, labelText); } private void newTextBox(final String parentId, final String id, final boolean editable, final String labelText) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newTextBox(parentId, id, editable, labelText); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void newTextField(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); boolean editable = message.args[2].boolValue; String labelText = message.args[3].strValue(); newTextField(parentId, id, editable, labelText); } private void newTextField(final String parentId, final String id, final boolean editable, final String labelText) { final Form form = getForm(parentId); if (form != null) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { form.newTextField(id, editable, labelText); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } else System.err.println("cannot find text field parent " + parentId); } private void newTree(Message message) { String parentId = message.args[0].strValue(); String id = message.args[1].strValue(); int zoom = getDeviceZoomPercent(); boolean editable = message.args[6].boolValue; newTree(parentId, id, editable); } private void newTree(final String parentId, final String id, final boolean editable) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.newTree(parentId, id, editable); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } public boolean processMessage(Message message) { return false; } private void selectForm(final String id) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { if (tabs.containsKey(id)) { Tab tab = tabs.get(id); if (!tabFolder.getTabs().contains(tab)) { tabFolder.getTabs().add(tab); } tabFolder.getSelectionModel().select(tabs.get(id)); } l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void removeNode(Message message) { final String id = message.args[0].strValue(); CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) { form.removeItem(id); } l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void maximiseToCanvas(Message message) { final String id = message.args[0].strValue(); CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.maximiseToCanvas(id); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void changesMade(Message message) { final String id = message.args[0].strValue(); final boolean made = message.args[1].boolValue; CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.changesMade(id, made); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } public void sendMessage(final Message message) { System.err.println("***FORMMESSAGE: " + message); if (message.hasName("newForm")) newForm(message); else if (message.hasName("setTool")) setTool(message); else if (message.hasName("newText")) { newText(message); String string = message.args[2].strValue(); if (string.length() < 150) { System.err.println("####### MESSAGE TO FORM CLIENT FOR EMPTY LABEL: " + string); } } else if (message.hasName("setText")) setText(message); else if (message.hasName("newXYLayout")) newXYLayout(message); else if (message.hasName("newTextField")) newTextField(message); else if (message.hasName("clearForm")) clearForm(message); else if (message.hasName("newList")) newList(message); else if (message.hasName("addItem")) addItem(message); else if (message.hasName("newTextBox")) newTextBox(message); else if (message.hasName("newComboBox")) newComboBox(message); else if (message.hasName("setSelection")) setSelection(message); else if (message.hasName("newCheckBox")) newCheckBox(message); else if (message.hasName("newButton")) newButton(message); else if (message.hasName("newTree")) newTree(message); else if (message.hasName("addNodeWithIcon")) addNodeWithIcon(message); else if (message.hasName("setVisible")) setVisible(message); else if (message.hasName("clear")) clear(message); else if (message.hasName("check")) check(message); else if (message.hasName("uncheck")) uncheck(message); else if (message.hasName("removeNode")) removeNode(message); else if (message.hasName("maximiseToCanvas")) maximiseToCanvas(message); else if (message.hasName("changesMade")) changesMade(message); else if (message.hasName("move")) move(message); else if (message.hasName("setSize")) setSize(message); else if (message.hasName("delete")) delete(message); else { super.sendMessage(message); } } private void newXYLayout(Message message) { Value parentId = message.args[0]; Value id = message.args[1]; Value rows = message.args[2]; Value columns = message.args[3]; } private void move(Message message) { Value id = message.args[0]; Value x = message.args[1]; Value y = message.args[2]; for (Form form : forms) form.move(id.strValue(), x.intValue, y.intValue); } private void setSize(Message message) { final Value id = message.args[0]; final Value width = message.args[1]; final Value height = message.args[2]; for (Form form : forms) form.setSize(id.strValue(), width.intValue, height.intValue); //TODO: java.lang.RuntimeException: The setSize()-operation for this type of Display is not yet implemented... } private void delete(Message message) { final Value id = message.args[0]; for (Form form : forms) form.delete(id.strValue()); } private void check(Message message) { String id = message.args[0].strValue(); check(id); } private void check(final String id) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.check(id); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void uncheck(final String id) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.uncheck(id); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void uncheck(Message message) { String id = message.args[0].strValue(); uncheck(id); } private void clear(Message message) { String id = message.args[0].strValue(); clear(id); } private void clear(final String id) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) { form.clear(id); } l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void setSelection(Message message) { String comboId = message.args[0].strValue(); int index = message.args[1].intValue; setSelection(comboId, index); } private void setSelection(final String comboId, final int index) { CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) form.setSelection(comboId, index); l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void setText(Message message) { final Value id = message.args[0]; final Value text = message.args[1]; CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { for (Form form : forms) { form.setText(id.strValue(), text.strValue()); } l.countDown(); }); try { l.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void setTool(Message message) { System.err.println("setTool: " + message); Value id = message.args[0]; Value name = message.args[1]; Value enabled = message.args[2]; // if (enabled.boolValue) { if (tabs.containsKey(id.strValue())) { FormTools formTools = getFormTools(id.strValue()); // formTools.addTool(name.strValue(), id.strValue(), enabled.boolValue); formTools.setTools(name.strValue(), id.strValue(), enabled.boolValue); } else System.err.println("cannot find form " + id); // }else{ // System.err.println("disabled tool: " + name.strValue()); // } } private void setVisible(Message message) { String id = message.args[0].strValue(); selectForm(id); // runOnDisplay(new Runnable() { // public void run() { // select(); // } // }); } public void toolItemEvent(String event, String id, boolean enabled) { Message m = null; if (event.equals("lockForm")) { m = getHandler().newMessage(event, 2); Value v = new Value(id); m.args[0] = v; Value enabled_value = new Value(!enabled); m.args[1] = enabled_value; } else { m = getHandler().newMessage(event, 1); Value v = new Value(id); m.args[0] = v; } getHandler().raiseEvent(m); } public void toolItemEvent(String event, String id) { toolItemEvent(event, id, false); } public void writeXML(PrintStream out) { out.print("<Forms>"); for (Form form : forms) form.writeXML(out, tabFolder.getSelectionModel().getSelectedItem() == tabs.get(form.getId()), tabs.get(form.getId()).getText()); for (FormTools tools : toolDefs.values()) tools.writeXML(out); out.print("</Forms>"); } public void doubleClick(String id) { EventHandler handler = getHandler(); Message message = handler.newMessage("doubleSelected", 1); message.args[0] = new Value(id); handler.raiseEvent(message); } }
package seedu.address.model; import java.util.Arrays; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ObservableBooleanValue; import seedu.address.model.battleship.Battleship; import seedu.address.model.battleship.Orientation; import seedu.address.model.cell.Cell; import seedu.address.model.cell.Coordinates; import seedu.address.model.cell.Status; /** * Represents a mapGrid of a player. A {@code MapGrid} acts as a container of {@Cell} objects. */ public class MapGrid { private Cell[][] cellGrid; private int size; private BooleanProperty uiUpdateSwitch = new SimpleBooleanProperty(); public MapGrid() { this.size = 0; cellGrid = new Cell[0][0]; } public MapGrid(MapGrid mapGrid) { size = mapGrid.size; cellGrid = new Cell[mapGrid.getMapSize()][mapGrid.getMapSize()]; copy2dArray(cellGrid, mapGrid.cellGrid); } // 2D map grid operations /** * Initialises the 2D Map from the given 2D Cell array * @param map to initialise the map from. */ public void initialise(Cell[][] map) { this.size = map.length; cellGrid = new Cell[size][size]; copy2dArray(cellGrid, map); updateUi(); } /** * Returns a copy of the MapGrid in a 2D array format. * Any changes done to the copy will not affect the internal grid. * @return copy of the map. */ public Cell[][] get2dArrayMapGridCopy() { Cell[][] mapCopy = new Cell[size][size]; copy2dArray(mapCopy, cellGrid); return mapCopy; } /** * Returns a 2D array of {@code Status} which represents the view of this map from this map owner's perspective. * @return statuses of cells. */ public Status[][] getPlayerMapView() { Status[][] playerMapView = new Status[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { playerMapView[i][j] = cellGrid[i][j].getStatus(); } } return playerMapView; } /** * Returns a 2D array of {@code Status} which represents the view of this map from * the perspective of the enemy of this map's owner. * @return statuses of cells. */ public Status[][] getEnemyMapView() { Status[][] enemyMapView = new Status[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Status cellStatus = cellGrid[i][j].getStatus(); enemyMapView[i][j] = (cellStatus == Status.EMPTY || cellStatus == Status.SHIP) ? Status.HIDDEN : cellStatus; } } return enemyMapView; } /** * Utility function to do a deep copy of a 2D array * @param output 2D array to copy to. * @param toBeCopied 2D array to copy from. */ private void copy2dArray(Cell[][] output, Cell[][] toBeCopied) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { output[i][j] = new Cell(toBeCopied[i][j]); } } } /** * Returns map size. * @return map size. */ public int getMapSize() { return cellGrid.length; } // UI operations /** * A listener will be added to this observable value in the UI. * Once this value changes the UI will be updated. * @return observableValue for the UI to listen to. */ public ObservableBooleanValue getObservableValue() { return uiUpdateSwitch; } /** * Updates the UI. */ public void updateUi() { if (uiUpdateSwitch.getValue() == false) { uiUpdateSwitch.setValue(true); } else { uiUpdateSwitch.setValue(false); } } //// cell-level operations /** * Returns the cell in the given coordinates. * @param coordinates of the cell. */ private Cell getCell(Coordinates coordinates) { return cellGrid[coordinates.getRowIndex().getZeroBased()][coordinates.getColIndex().getZeroBased()]; } /** * Returns the status of the specified {@code Cell}. * @param coord specifies which {@code Cell} to get {@code Status} from. * @return {@code Status} of the cell. */ public Status getCellStatus(Coordinates coord) { return getCell(coord).getStatus(); } /** * Returns the name of the {@code Battleship} in the specified {@code Cell} * @param coord specifies which {@code Cell} to get the name of {@code Battleship} from. * @return Name of the {@code Battleship} as a {@code String}. */ public String getShipNameInCell(Coordinates coord) { return getCell(coord).getBattleship().get().toString(); } /** * Attack a specified cell. * @param coordinates of the cell. * @return boolean which specifies hit or miss. */ public boolean attackCell(Coordinates coordinates) throws ArrayIndexOutOfBoundsException { if (coordinates.getColIndex().getOneBased() > getMapSize()) { throw new ArrayIndexOutOfBoundsException("Coordinates are outside of the map"); } boolean isSuccessfulHit = cellGrid[coordinates.getRowIndex().getZeroBased()][coordinates.getColIndex().getZeroBased()] .receiveAttack(); updateUi(); return isSuccessfulHit; } /** * Put battleship on map grid. */ public void putShip(Battleship battleship, Coordinates coordinates, Orientation orientation) throws ArrayIndexOutOfBoundsException { int rowIndexAsInt = coordinates.getRowIndex().getZeroBased(); int colIndexAsInt = coordinates.getColIndex().getZeroBased(); if ((coordinates.getColIndex().getOneBased() > getMapSize()) || (coordinates.getRowIndex().getOneBased() > getMapSize())) { throw new ArrayIndexOutOfBoundsException("Coordinates are outside of the map"); } int rowInt = rowIndexAsInt; int colInt = colIndexAsInt; for (int i = 0; i < battleship.getLength(); i++) { if (orientation.isHorizontal()) { colInt = colIndexAsInt + i; } else { rowInt = rowIndexAsInt + i; } cellGrid[rowInt][colInt].putShip(battleship); } } //// util methods @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof MapGrid // instanceof handles nulls && Arrays.deepEquals(cellGrid, ((MapGrid) other).cellGrid)); } @Override public int hashCode() { return cellGrid.hashCode(); } }
import { databaseProviders } from "./provider/database.provider"; import { AppointmentProviders, clinicHistoryProviders, DiaryProviders, ophthalmologistProviders, patientProviders, PresciptionProviders, RolProviders, UsersProviders } from "./migrations/entities.provider"; import { Module } from "@nestjs/common"; @Module( { providers: [ ...databaseProviders, ...ophthalmologistProviders, ...patientProviders, ...clinicHistoryProviders, ...PresciptionProviders, ...DiaryProviders, ...AppointmentProviders, ...UsersProviders, ...RolProviders ], exports: [ ...databaseProviders, ...ophthalmologistProviders, ...patientProviders, ...clinicHistoryProviders, ...PresciptionProviders, ...DiaryProviders, ...AppointmentProviders, ...UsersProviders, ...RolProviders ] } ) export class DatabaseModule{}
<reponame>Kao-Group/SCoVMod /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package scovmod.model; import java.time.LocalDate; import java.time.Month; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import scovmod.model.input.config.ConfigParameters; import scovmod.model.movements.LocationIncomingPersons; import scovmod.model.movements.MovementEventManager; import scovmod.model.movements.MovementStepper; import scovmod.model.movements.TimeStepMovements; import scovmod.model.output.HealthBoardLookup; import scovmod.model.output.StatisticsCollector; import scovmod.model.setup.Initialiser; import scovmod.model.state.StateQuery; import scovmod.model.time.TaskTimeManager; import scovmod.model.time.TimeConversions; import scovmod.model.time.TimeManager; import scovmod.model.transition.TransitionManager; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static scovmod.model.util.TestUtils.intSetOf; import static scovmod.model.util.TestUtils.setOf; public class ModelTest { private int STOCHASTIC_INCREMENT = 15; private long CURRENT_TIMESTEP = 1100; private long LAST_TIMESTEP = 1101; private LocalDate CURRENT_DATE = LocalDate.of(2003, Month.JANUARY, 1); private LocalDate LAST_DATE = LocalDate.of(2008, Month.JANUARY, 1); private LocalDate LAST_DATE_WITHLOOP = LocalDate.of(2013, Month.JANUARY, 1); private static final String MODEL_ID = "m1"; private int LOCATION = 100; @Before public void setup() { } @Test public void run_noScenario() { TimeManager timeMgr = mock(TimeManager.class); Initialiser initialiser = mock(Initialiser.class); ConfigParameters configParams = mock(ConfigParameters.class); MovementEventManager mover = mock(MovementEventManager.class); MovementStepper movStepper = mock(MovementStepper.class); StatisticsCollector stats = mock(StatisticsCollector.class); TimeConversions tcv = mock(TimeConversions.class); TransitionManager tm = mock(TransitionManager.class); StateQuery sq = mock(StateQuery.class); HealthBoardLookup hbl = mock(HealthBoardLookup.class); TaskTimeManager ttm = mock(TaskTimeManager.class); when(tcv.toTimeStepStartDate(CURRENT_TIMESTEP)).thenReturn(CURRENT_DATE); when(tcv.toTimeStepStartDate(LAST_TIMESTEP)).thenReturn(LAST_DATE); when(timeMgr.getTimeStep()).thenReturn(CURRENT_TIMESTEP, LAST_TIMESTEP); when(configParams.getFirstTimeStep()).thenReturn(CURRENT_TIMESTEP); when(configParams.getLastTimeStep()).thenReturn(LAST_TIMESTEP); when(movStepper.getTimeStepSize()).thenReturn(STOCHASTIC_INCREMENT); when(sq.getAllActiveLocationIds()).thenReturn(intSetOf(LOCATION)); Set<LocationIncomingPersons> ias = setOf( new LocationIncomingPersons(LOCATION, intSetOf(10001), null)); TimeStepMovements tsm1 = mock(TimeStepMovements.class); when(movStepper.getNextTimeStepMovements()).thenReturn(tsm1); when(tsm1.getMovements()).thenReturn(ias); Model instance = new Model( MODEL_ID, initialiser, configParams, movStepper, timeMgr, sq, mover, tm, stats, tcv, ttm, hbl); instance.run(); InOrder inOrder = inOrder(initialiser, mover, mover, tm, stats); inOrder.verify(initialiser).seedPeople(configParams, STOCHASTIC_INCREMENT); inOrder.verify(mover).doMovements(ias,null,null,null); inOrder.verify(tm).doTransitions(ias); } }
Image copyright EPA Image caption Jean-Claude Juncker became European Commission president in November The new president of the European Commission has warned the UK not to "beat up" EU migrants as it tries to cut immigration. Jean-Claude Juncker said people from Poland, Romania and Bulgaria were "earning their wages" and should not be treated as criminals. Prime Minister David Cameron wants to change Britain's relationship with the EU ahead of an in/out referendum. Last month he urged EU support for curbs on welfare payments to migrants. The UK government has admitted the scale of EU migration means it is likely to miss its target of cutting net migration to the tens of thousands before the general election in 2015. 'Fundamental right' Mr Cameron had previously vowed to "get what Britain needs" and change the free movement of people, but this met strong resistance from his European counterparts who see it as a fundamental principle of the EU. During a debate on Austrian TV, Mr Juncker, who came to office at the start of November, said he wanted Britain to remain an active member of the EU. But he went on to suggest that the knock-on effects of curbing free movement could have a negative impact on the City of London. Image caption David Cameron unveiled his plans to cut EU migration in November He said: "This fundamental right of free movement of workers cannot be questioned existentially because if you question the free movement of workers, Great Britain has to know that one day the free movement of capital will also have to be called into question. "Then it will be the end for London's tax rulings, that will no longer be possible in London." Mr Juncker said free movement of labour should not be "abused", adding: "But it is the national legislatures who should fight against this abuse and I am utterly against behaving as if all Poles, all Romanians, all Bulgarians in the European labour market are of a basic mentality that is criminal. "These are people who are working and earning their wages. "One should stop - especially Great Britain which always fought for the enlargement of the European Union - discriminating against countries just because, in the current context, it goes down well when one beats up others. Self-flagellation is sometimes appropriate." Mr Cameron has said he is confident he can secure agreement for his reforms and would therefore campaign for the UK to stay in the EU in the referendum planned for 2017. But he warned that if the UK's demands fell on "deaf ears" he would "rule nothing out". His proposals include stopping EU migrants from claiming in-work benefits for four years, preventing migrants from claiming child benefit for dependants living outside the UK, and removing migrants from the country after six months if they have not found work.
#pragma once #include "Module.h" #include <linux/usbdevice_fs.h> namespace WPEFramework { namespace Plugin { class SystemCommandsImplementation { public: SystemCommandsImplementation() = default; ~SystemCommandsImplementation() = default; uint32_t USBReset(const std::string& device) { uint32_t result = Core::ERROR_NONE; int fd = open(device.c_str(), O_WRONLY); if (fd < 0) { TRACE(Trace::Error, (_T("Opening of %s failed."), device.c_str())); result = Core::ERROR_GENERAL; } else { int rc = ioctl(fd, USBDEVFS_RESET, 0); if (rc < 0) { TRACE(Trace::Error, (_T("ioctl(USBDEVFS_RESET) failed with %d. Errno: %d"), rc, errno)); result = Core::ERROR_GENERAL; } close(fd); } return result; } private: SystemCommandsImplementation(const SystemCommandsImplementation&) = delete; SystemCommandsImplementation& operator=(const SystemCommandsImplementation&) = delete; }; } // namespace Plugin } // namespace WPEFramework
Investigation of temperature fields of a glass furnace The pricing policy of the fuel and energy market is constantly growing. The urgency of research is to adjust the optimization of fuel consumption in the glass furnace to obtain the maximum economic effect of production. Using the developed mathematical model of the glass furnace, the analysis was carried out: temperature modes of the furnace, temperature fields of glass and masonry. The temperature distribution in the sections of the glass furnace is performed by means of simulation modeling. The object of research consists of glass mass, gas space, masonry and divided into conditional sections (zones), according to the installation of temperature measuring instruments. In cross sections, the main ones are those that correspond to the position of the burners. In sections on the layers of glass mass, the starting point of the measurement is the surface of the glass mass, and the final bottom of the furnace. The longitudinal sections show the melting behavior of the charge pieces to the state of homogeneity - the transition of glass mass from the loading point of the charge to full melting. The dynamics of glass mass temperature change in the depth of the glass mass layer is the heating curve, the lower the layer considered - the lower the temperature due to the distance from the burners, but within one layer the temperature increases the closer the section to the point. Glass furnace refers to reversible - switching burners to the left or right group. Accordingly, the reverse switching takes place according to a given algorithm, which consists in adjusting the operating time of the group of burners depending on the temperature of the glass mass. The temperature distribution in the glass mass according to the temperature field at a depth of 0.1 m from the upper level of the glass mass is lower by 5-6% from the data of technological regulations. To do this, increased fuel consumption on the burners of the left group, made it possible to optimize fuel consumption. The study of the temperature field of the vault masonry made it possible to avoid problems with overheating and possible collapse of the masonry. Heating of the masonry within the permissible limits from a temperature of 10000C at the edges of the vault and 13800C in the central zone. The cross-section shows the loading channel of the charge, which borders the gas space, so the charge at the entrance to the cooking zone of the furnace receives additional heating and reduces fuel consumption in the first zone for heating the charge. The temperature distribution in the surface layer of the glass mass contains inhomogeneity in the first zone, to achieve uniformity increases fuel consumption on the first pair of burners, which optimizes the consumption of other pairs of burners and prevents excessive gas consumption. The overlap of two thirds of the corresponding plane when leaving the burner of the first section is increased from the required by 5%. In the second section, due to underheating of the selected plane, the value of fuel consumption increased by 12%. The temperature distribution is the lowest in the loading zone, the highest - after the third zone to the fifth (in the cave point). If the composition of the charge is changed (the action of uncontrolled perturbation), and the gas flow through the burners remains unchanged, it is impossible to achieve the value of temperature fields in accordance with the technological regulations. A scientific novelty is the study of cross-sections of glass mass in different planes, made it possible to analyze the temperature fields of glass mass at points where it is technologically impossible to organize measurements.
1. Field of the Invention The present invention relates to an apparatus for displaying a frequency received by a radio receiver. More specifically, the present invention relates to an apparatus for displaying in a digital manner a frequency being received by a radio receiver by counting the local oscillation frequency pulses obtainable from a local oscillator of the radio receiver. 2. Description of the Prior Art It has been proposed that the frequency of a signal received by a radio receiver be displayed in a digital manner. For example, U.S. Pat. No. 3,244,983, issued Apr. 5, 1966 to Robert J. Ertman and entitled "Continuously Tunable Direct Reading High Frequency Converter" discloses that a numerical value associated with the intermediate frequency is preset in a preset counter and the local oscillation frequency is evaluated by counting the local oscillation frequency output by means of the said preset counter, whereupon the count value is displayed in a digital manner. On the other hand, the actual intermediate frequency of the respective radio receivers, as manufactured, is determined by the accuracy of adjustment of the intermediate frequency transformers, the frequency characteristic of ceramic filters used in the intermediate frequency amplifiers, and the like. However, it is usually not possible to achieve exactly the same adjustment of the intermediate frequency transformers or obtain ceramic filters of exactly the same frequency characteristics in all the radio receivers, as manufactured, and thus some deviation of the actual intermediate frequency of the intermediate frequency stage unavoidably results among the radio receivers, as mass-produced. Hence, it is appreciated that only if a predetermined numerical value associated with the prescribed intermediate frequency is fixedly preset in the preset counter, then some frequency deviation occurs in indicating of the frequency being received. Thus, ideally it is necessary to correct the numerical value being preset in the preset counter in association with the deviation of the intermediate frequency of the intermediate frequency stage of the respective radio receivers by virtue of the deviation of adjustment of the intermediate frequency transformers, the frequency characteristics of the ceramic filters and the like. However, since it was conventionally adapted such that the preset numerical value was read out from a masked read only memory, for example, it was impossible to make such correction of the preset value. Thus, it was required that the accuracy of adjustment of the intermediate frequency transformers be strictly controlled or that ceramic filters of an accurate frequency characteristic were selected, which caused an increase of the cost. On the other hand, Japanese Patent Publication Gazette No. 44167/1977, as published Nov. 5, 1977 for opposition, discloses a dial display in a radio receiver, wherein in order to avoid .+-.1 count error occurring in the least significant digit of the displayed number counters are used the number of which is larger by at least one digit than the number of digits being displayed so that the additional counter is allotted for the digit position less significant than the least significant digit of the number being displayed and, for example, the number "5" is preset in the additional counter, whereby the number being displayed is rounded at the digit less significant than the least significant digit so as to count fractions of 5 and over as a whole number and to disregard the rest, with the result that an error is eliminated from an apparent digital display. Even such prior art display involves a problem to be solved and hence leaves room for improvement. More specifically, according to the above described approach, the preset value per se is not corrected in association with the deviation of the actual intermediate frequency of the receivers from the prescribed intermediate frequency but instead the displayed number is merely rounded at an additional digit position less significant than the least significant digit of the number being displayed, thereby to achieve an apparently corrected digital display of the frequency being received. Therefore, if and when deviations of the adjustment of the intermediate frequency transformers or the deviation of the frequency characteristic of the ceramic filters used in the intermediate frequency amplifiers exceeds the range in which any error can be eliminated in accordance with the above described approach disclosed in the referenced Japanese Patent Publication Gazette, then it follows that such deviation appears as an error in indicating the frequency being received which is made in the conventional display. In other words, the approach disclosed in the above referenced Japanese Patent Publication Gazette merely broadens a permissible error range in which an error of adjustment of the intermediate frequency transformers or an error of the frequency characteristic of the ceramic filters is permissible and totally fails to provide any scheme for correcting the preset value per se fundamentally in association with such deviation.
Urinary excretion of beta2-microglobulin and other proteins in workers exposed to cadmium, lead or mercury. For the range of exposure to heavy metals sustained by the different groups of workers, a significant increase in the urinary excretion of low and/or high molecular weight proteins was found in the workers exposed to cadmium or to lead + cadmium, but no in those exposed to lead only and those exposed to mercury. Our observations suggest that the classical "tubular" proteinuria induced by cadmium has two not necessarily concomitant components : a "tubular type" component with increased excretion of low molecular weight proteins and a "glomerular type" component with increased excretion of high molecular weight proteins.
Q: How would life adapt to survive in an environment with winters of varying length? In his answer to a question on our Science Fiction and Fantasy SE about how Westeros in Game of Thrones produces food during the winters, Superbest says: "Martin's conception of a multi-annual winter is a little bizarre in my opinion. If this has been going on a geological time scale (eg. millions of years) it would either create flora and fauna radically different from what we see here on Earth, while the novels seem to portray basically the same animals and plants we have, with the occasional exotic exception". So, how would an animal evolve to survive on a planet where winters and summers lasted varying, random lengths like in Game of Thrones? What common traits would develop among animals in general? (I know there would be wild differences based on predator/prey status and such, but there would also be similarities - what would they be?) Assumptions: Winters can last anywhere between 1 and 30 years at a time. 99% of the time it will be somewhere between the 2 and 10 mark, however. Summers work the same way, with summer instantly kicking in after winter ends. The length of a summer has no relation on and in no way impacts the length of a winter and vice versa - it is totally random within the above parameters. We will also assume that this world has obviously been like this for long enough for animals to evolve, if not from its beginning. Edit 1: The sun remains in "summer mode" for the duration of summer, and "winter mode" for the duration of winter in regards to the length of the day. It is also, obviously going to be horrendously cold for the duration of winter in the northern hemisphere. Outside of this, the world is exactly like Earth. A: I have always thought of the Westeros cycle as more like climate change than like seasons. Specifically, there are seasons, just like in Europe or North America, and superimposed over the annual cycle of seasons there are climate oscillations induced by some kind of oceanic phenomenon, somewhat similar to the El Niño / La Niña phenomena on Earth. The transition from a warm period to a cold period may be very short or it may last a few years -- my impression from the books and from the TV series is that when winter comes the years get progressively colder, but then I may be wrong. It may be that such a world will give preference to hardy animal and plant species which can survive both cold and warm times. It may also be that some areas are always cold and some are always warm -- for example, the area beyond the wall seems to be always cold and the areas inhabited by those barbarian nomads and amoral slavers seem to be always warm; the areas in between would then be colonised by cold-loving species in cold times and by warmth-loving species in warm times. Probably a mix of both. The main threat posed by cold spells in Westeros (forgetting about undead foes) is that agricultural output collapses, as expected. The long winters are times of hunger. Think of how many animal and plant species can be found everywhere from the Artic Circle to the tropics: fir trees, and deer, and wolves, and grasses, and birds. They may dominate the north and be restricted to higher altitudes in the south; they may thrive in more temperate areas and be restricted to favorable locales in the north; but definitely there are plants and animals which are (or would have been in the absence of humans) common to all Europe, from cold Norway to warm Italy or Greece. A: Unpredictable winters mean you need to be ready for them at any given time. I guess plants would have weak fast growing branches with thin leaves or something. They're easy to grow and not a huge loss if frost suddenly kicks in. Then when it's cold you hibernate. Same goes for animals though I don't think a single complex organism exists that can hibernate for years. Tardigrades totally can but they're not that complex. They build wouldn't work for a more advanced creature like a primate. I actually think the whole setting would exclude the evolution of advanced fauna. Flora will be things like trees that can survive outside combined with plants that use an extensive root system to survive the cold. This can't support large animals as there would be little nutrients above ground. Smaller animals could probably survive if they produce very 'expensive' eggs that can hibernate through winter. Probably buried underground. Animals living short lives while they pour all their energy into hibernating eggs who would emerge at first spring. Of course there is one exception, the ocean. The water would largely nullify the effects of the winters. Underwater you'd have a teaming ecosystem. A: Flora Trees - Pine trees and other coniferous trees are actually already decently suited to this setup. Their seeding usually depends on fire and not a normal spring thaw seed that many other plants use, which means prolonged winters are not a threat to their reproduction. We already see much of this in the north. That said, these trees need the root structure and therefore can't survive in tundra/marsh and will be more common in mountainous terrain. Trees that loose their leaves wouldn't fare well in this setup. Bush/shrub. Take from the current tundra, there are some hardy plants out there. Moss and the sort also tend to do quite well out here. I believe you will see some berry plants (wild blueberry) capable of surviving the elongated winters as well, some adaptations to the seeds to stay dormant until the summer phase appears will likely allow for berries to exist in these setups. I don't think 'raspberries' and other semi-permanent bushes would do well. In both the cases above, it's likely these plants will support very expanded root systems for storing reserves through the elongated freezes. Animal life I believe hibernation is out as a survival technique...the lack of definite summers pretty much rules out the store up fat and sleep option simply because the animal has no ability to guess how long it would be asleep for and how many reserves it would need to build up. Life on land under ice - Ice is actually an excellent insulator and even in extreme cold, under the ice can still be inhabitable. Given the prediction of the expanded root systems, there should be additional nutrition to be found under the ice. Lemmings and other rodents could survive under the ice along the southern areas of this winterland. Life on the land, herbavores. Migration has always been a valid technique for animals. That being said, it's 'seasonal' migration based on a constant cycle...if the season instant predictable, then these animals are going to need to adapt and find food locations during the extended winters, while still having a trigger to go back north. If there are larger herbivores wandering around the region, they will likely be migratory. Life on the land, predators. I believe wolves living on the southern areas hunting both migratory and creatures under the ice should be able to adapt to these situations. Life on sea ice. Honestly, I don't think theres much of a change in behavior here. If you have frozen over sea water, life on and off the surface will not have the cyclical nature it currently does, but I suspect the life (seals/fish/whales/bears) would not be greatly effected. Side note: I live near the rocky mountains and am very familiar with the spring melt off. Winter snow packs up during the winter and when the warmer temperatures come, the water melts and the rivers greatly increase in volume and speed. With some rains added, we've seen some vicious flooding over the last decade. I would imagine a prolonged 30 year winter cycle jumping straight into a summer cycle would create some outright vicious flooding as the snow pack melts...rivers seeing 50x volume and low laying areas becoming completely waterlogged.
/// Notifies clients in area that a character has blade-stopped another (ZC_BLADESTOP). /// 01d1 <src id>.L <dst id>.L <flag>.L /// flag: /// 0 = inactive /// 1 = active void clif_bladestop(struct block_list *src, int dst_id, int active) { unsigned char buf[32]; nullpo_retv(src); WBUFW(buf,0)=0x1d1; WBUFL(buf,2)=src->id; WBUFL(buf,6)=dst_id; WBUFL(buf,10)=active; clif_send(buf,packet_len(0x1d1),src,AREA); }
/** * Copyright 2017 Smart Society Services B.V. * * 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 */ package org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.alarm; import java.io.IOException; import org.openmuc.jdlms.AccessResultCode; import org.openmuc.jdlms.AttributeAddress; import org.openmuc.jdlms.ObisCode; import org.openmuc.jdlms.SetParameter; import org.openmuc.jdlms.datatypes.DataObject; import org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.AbstractCommandExecutor; import org.opensmartgridplatform.adapter.protocol.dlms.domain.commands.utils.JdlmsObjectToStringUtil; import org.opensmartgridplatform.adapter.protocol.dlms.domain.entities.DlmsDevice; import org.opensmartgridplatform.adapter.protocol.dlms.domain.factories.DlmsConnectionManager; import org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ConnectionException; import org.opensmartgridplatform.adapter.protocol.dlms.exceptions.ProtocolAdapterException; import org.opensmartgridplatform.dto.valueobjects.smartmetering.ActionRequestDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.ActionResponseDto; import org.opensmartgridplatform.dto.valueobjects.smartmetering.ClearAlarmRegisterRequestDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class ClearAlarmRegisterCommandExecutor extends AbstractCommandExecutor<ClearAlarmRegisterRequestDto, AccessResultCode> { private static final Logger LOGGER = LoggerFactory.getLogger(ClearAlarmRegisterCommandExecutor.class); private static final int CLASS_ID = 1; private static final ObisCode OBIS_CODE = new ObisCode("0.0.97.98.0.255"); private static final int ATTRIBUTE_ID = 2; private static final int ALARM_CODE = 0; public ClearAlarmRegisterCommandExecutor() { super(ClearAlarmRegisterRequestDto.class); } @Override public ActionResponseDto asBundleResponse(final AccessResultCode executionResult) throws ProtocolAdapterException { this.checkAccessResultCode(executionResult); return new ActionResponseDto("Clear alarm register was successful"); } @Override public ClearAlarmRegisterRequestDto fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException { this.checkActionRequestType(bundleInput); return (ClearAlarmRegisterRequestDto) bundleInput; } @Override public AccessResultCode execute(final DlmsConnectionManager conn, final DlmsDevice device, final ClearAlarmRegisterRequestDto clearAlarmRegisterRequestDto) throws ProtocolAdapterException { LOGGER.info("Clear alarm register by request for class id: {}, obis code: {}, attribute id: {}", CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final SetParameter setParameter = this.getSetParameter(); conn.getDlmsMessageListener().setDescription( "ClearAlarmRegister, with alarm code = " + ALARM_CODE + "and set attribute: " + JdlmsObjectToStringUtil .describeAttributes(new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID))); final AccessResultCode resultCode; try { resultCode = conn.getConnection().set(setParameter); } catch (final IOException e) { throw new ConnectionException(e); } if (resultCode != null) { return resultCode; } else { throw new ProtocolAdapterException("Error occurred for clear alarm register."); } } private SetParameter getSetParameter() { final AttributeAddress alarmRegisterValue = new AttributeAddress(CLASS_ID, OBIS_CODE, ATTRIBUTE_ID); final DataObject data = DataObject.newUInteger32Data(ALARM_CODE); return new SetParameter(alarmRegisterValue, data); } }
Inner Workings: Was Jupiter born beyond the current orbits of Neptune and Pluto? Ancient people named the planet Jupiter well. Both its brilliance and its slow, regal movement across the sky evoked a king among gods. Today we know much more about the influence of Jupiter, a planet boasting more than twice as much mass as the solar systems other planets put together. Jupiters tremendous gravity stunted the growth of newborn Mars, sculpts the asteroid belt today, and may even help protect Earth from catastrophic comet impacts. A new theory suggests that Jupiter formed its core far from the Sun, then moved inward. Image credit: Hubble Space Telescope NASA, ESA, and Amy Simon (NASA Goddard). But how did such a behemoth arise? Conventional theory says that Jupiter formed more or less where it is now, about five times farther from the Sun than Earth is. At that distance, the disk of gas and dust that swirled around the young Sun was dense enough to give birth to the planetary goliath. In 2019, however, two groups of researchers unaware of each others workone in America, the other in Europe proposed a literally far-out alternative: Jupiter got its start in the solar systems hinterlands, probably beyond the current orbits of Neptune and Pluto, and then moved inward. Its the most fun Ive had with a paper for some time, says Karin Oberg, an astronomer at the Harvard-Smithsonian Center for Astrophysics in Cambridge, MA, and one of the theorys originators. You can explain it to almost anyone in a couple of minutes. The theory may be straightforward, but its consequences are profound: If its right, the solar systems biggest planet was born some 10 times farther from the Sun than it now is, which means that some of the other giant worlds in our solar system and beyond likely arose at vast distances from
. Thrombolysis in massive embolism is associated with a number of complications, mainly haemorrhagic, justifying an evaluation of the individual risk/benefit ratio before prescription. Major bleeding episodes, the most serious complication, are observed in 8 to 15% of cases and result from mechanisms involving the coagulation factors, platelet function and the vessel wall. In over 70% of cases, they are directly related to sites of vascular puncture, especially for the carrying out of pulmonary angiography which triples the haemorrhagic risk. Uncontrolled hypertension, the prescription of active oral anticoagulants at the time of thrombolysis, low body weight, diabetes, female gender, and ages over 70 have also been identified as factors predictive of bleeding. The prevention of haemorrhage is based on strict observance of the contraindications of thrombolysis and the limitation of early vascular puncture sites, especially femoral, for pulmonary angiography. In cases of haemorrhage, treatment requires interruption of thrombolysis and heparin, the neutralisation of circulating plasmin, inactivation of plasminogen and correction of fibrinogen-induced deficits. Allergic reaction may also occur during thrombolysis, especially with the use of streptokinase. They are usually mild and be prevented by prior routine administration of steroids. The same applies to hypotensive episodes, also more common with streptokinase and rapidly reversible by transient interruption of thrombolysis.
def genModel(): inp = (160, 320, 3) oup1 = (160, 320, 1) oup2 = (80, 320, 1) model = Sequential() model.add(Lambda(color2gray, input_shape = inp, output_shape= oup1)) model.add(Cropping2D(cropping=((50,30), (0,0)))) model.add(Lambda(lambda x: x/127.5 - 1., output_shape= oup2)) model.add(Convolution2D(24,5,5,subsample=(1,2), activation="relu")) model.add(Convolution2D(36,5,5,subsample=(2,2), activation="relu")) model.add(Convolution2D(48,5,5,subsample=(2,2), activation="relu")) model.add(Convolution2D(64,3,3, activation="relu")) model.add(Convolution2D(64,3,3, activation="relu")) model.add(Flatten()) model.add(Dropout(0.3)) model.add(Dense(180, activation="relu")) model.add(Dense(60)) model.add(Dense(10, activation="relu")) model.add(Dense(1)) for layer in model.layers: print(layer.get_output_at(0).get_shape().as_list()) return model
MRI of inner ear anatomy using 3D MP-RAGE and 3D CISS sequences. The aim of this study was to compare contrast enhanced 3D MP-RAGE (magnetization prepared rapid gradient echo), unenhanced 3D MP-RAGE and 3D CISS (constructive interference in steady state) in the evaluation of anatomical detail of the inner ear and facial nerve. 60 persons with no abnormalities and no or non-specific symptoms were examined with MRI. All examinations were performed using a 1.5 T MR unit. The detectability of anatomical details was evaluated by agreement of three radiologists. Statistical evaluation of the results was achieved by the two-tailed Wilcoxon's test. In 86-95% of the cases, 3D CISS resulted in excellent visibility of the basal and second turn and apex of the cochlea, the vestibule and semicircular canals, as well as the nerves within the internal auditory canal. There was a significantly better visualization with CISS than with MP-RAGE. Detectability of the extrameatal facial nerve was best using contrast enhanced 3D MP-RAGE in 91-96% of the cases (labyrinthine segment 96.7%; geniculate ganglion 95%; tympanic segment 91.7%; vertical segment 95%). The detection of the meatal seventh nerve was best using CISS, whilst unenhanced MP-RAGE gave significantly better results than contrast enhanced MP-RAGE. These results suggest that unenhanced and contrast enhanced 3D MP-RAGE and 3D CISS sequences are complementary and not alternative MRI techniques. Both T1 and T2 weighted 3D MR imaging of the temporal bone is of advantage when compared with 2D MR sequences due to improved contrast, geometrical resolution and the possibility of adequate reconstruction of anatomical structures.
CLEVELAND, Ohio - Cuyahoga County plans to hire a consultant to help officials determine the future of the Justice Center. The consultant will assist the county and those who work in the Justice Center to "review facility requirements and opportunities," according to a request for qualifications issued by the county's public works department. "This may include reviewing options for renovating the entire complex, constructing a new one, or a combination of approaches." For four years, county officials have considered the future of the 41-year-old complex, which sits on prime land for development. They have commissioned reports and met with judges and other tenants of the building. The complex, which takes up a city block between St. Clair Avenue and Lakeside Avenue, includes a 25-story Court Tower, 10-story jail, 11-story jail addition, nine-story Cleveland Police Department Headquarters and 432,500 square feet of underground parking. The complex is connected by a sky-lit central atrium, which serves as the secure public entrance. The county was motivated to hire a consultant following an agreement with the city in June to take over jail operations and purchase Cleveland's police headquarters and jail for $9.25 million. What you need to know about the Cleveland-Cuyahoga County jail agreement According to the county's request for qualifications "the buildings that house most of the county's justice functions have not received significant renovation in many years. Opportunities may exist to rebuild or otherwise improve justice facilities, operations and efficiency for the benefit of the public, municipalities, the judiciary and many stakeholders." County officials have estimated the cost of repairs at $300 million. K2M Design, along with Osborne Engineering in 2014 completed an extensive assessment of the condition of the 2.29 million-square-foot Justice Center complex. The report, issued in spring 2014, included several options to upgrade or replace portions of the center. The most expensive option, at $429 million, was to demolish and rebuild the Cleveland police headquarters and the courts tower. The firms did not study the possibility of demolishing the entire complex and the cost to rebuild at another location. In December 2015 the county agreed to pay $50,000 to K2M and $12,500 to the Thompson Hine law firm to study those options. A county spokeswoman said she is trying to determine if the report has been completed. No report has been released. A former Cuyahoga County architect estimated it could cost up to $1 billion to replace the complex. Replacing Justice Center could cost more than $1 billion, says former Cuyahoga County architect County officials met with judges and others who use the building in 2016 to determine their views. Cuyahoga County Common Pleas and Cleveland Municipal Court judges had admonished County Executive Armond Budish's decision to hire an outside agency to consider building a new justice center without consulting the building's judicial tenants. The group this year developed eight guiding principles, which the consultant should follow, the document said. They are: Process - Implement a collaborative, inclusive and transparent process that involves key stakeholders in a confidential setting, but which will ultimately elicit public support. Cost Control - Optimize use of financial resources through efficient space planning and sharing, and balancing dignity with economy in design. Operations - Plan and design for efficient court operations, incorporating modern technology, paperless file management, and appropriate adjacencies. Dignity - Convey the authority of the courts and provide a positive impact on the civic character of the court complex and the immediate surrounding community. Security - Provide safe and secure environment for public, staff and detainees, including efficient and dignified security screening and separate circulation paths within the building. Access to Justice - Improve access to justice for litigants and victims, including simple wayfinding, efficient transaction counters and pro-se services. Flexibility - Plan for future change, incorporate flexible workplace design which maximizes open office systems furniture and integration of new technologies. Integration - Provide connectivity with ancillary facilities such as the Sheriff's office and Jail, co-location with related justice agencies where practical, and consideration of full courts consolidation within one Justice Center Visioning complex. The consultant will coordinate, plan and monitor whatever project is determined and will "make recommendations for short and long-term upgrades to the facilities to enable efficient operations and all considerations informed by the eight Guiding Principles, including new construction, if deemed necessary," the document says.
Once-daily OROS methylphenidate is safe and well tolerated in adolescents with attention-deficit/hyperactivity disorder. This 8-week, open-label extension of a double-blind study reports on safety data for 171 adolescents with attention-deficit/hyperactivity disorder (ADHD) who received once-daily OROS methylphenidate (MPH) (18-72 mg/day). Headache, anorexia, and insomnia were the most frequently reported treatment-related adverse events. The incidence of adverse events was not related to dose. OROS MPH was safe and well tolerated at doses up to 72 mg/day.
<reponame>maticzav/creato #!/usr/bin/env node import * as path from 'path' import * as fs from 'fs' import * as ora from 'ora' import * as inquirer from 'inquirer' import * as mkdirp from 'mkdirp' import { loadTemplate, Template } from './loader' export interface Options { force: boolean } /** * * Creates a CLI tool from description and templates. * * @param templates * @param options */ export async function creato( templates: Template[], options: Options, ): Promise<void> { /** * Inquier about template */ const { template } = await inquirer.prompt<{ template: Template }>([ { name: 'template', message: 'Choose a template!', type: 'list', choices: templates.map(template => ({ name: `${template.name} ${template.description}`, value: template, })), }, ]) const { dist } = await inquirer.prompt<{ dist: string }>([ { name: 'dist', message: 'Where should we scaffold your template?', type: 'input', }, ]) const absoluteDist = path.resolve(process.cwd(), dist) if (fs.existsSync(absoluteDist) && !options.force) { console.warn(`Directory ${absoluteDist} must be empty.`) return process.exit(1) } else { mkdirp.sync(absoluteDist) } /** * Load template */ const spinner = ora({ text: `Loading ${template.name} template.`, }).start() const res = await loadTemplate(template, absoluteDist) if (res.status === 'ok') { spinner.succeed() console.log(res.message) return process.exit(0) } else { spinner.fail() console.warn(res.message) return process.exit(1) } }
<reponame>antonyjm462/Fixel- export class User { name: any; email: any; password: any; }
string = str(input()) length = len(string) t = 0 c = 0 def check(moji1,moji2): moji2 = list(moji2) moji1 = list(moji1) count = 0 for i in range(t): if moji1[i] != moji2[i]: count += 1 return count if length % 2: t = int((length - 1)/2) mojimoji = list(string) newmoji1 = "" newmoji2 = "" for a in range(t): newmoji1 += mojimoji[a] newmoji2 += mojimoji[length-(1+a)] c = check(newmoji1,newmoji2) else: t = int(length/2) mojimoji = list(string) newmoji1 = "" newmoji2 = "" for a in range(t): newmoji1 += mojimoji[a] newmoji2 += mojimoji[length-(1+a)] c = check(newmoji1,newmoji2) print(c)
Afio Cox in 2011 was the driver of a car that crashed into a concrete pole and which killed his passenger, court documents say. A Superior Court of Guam judge on Thursday sentenced a man to two years in prison for vehicular homicide and driving under the influence with injuries. Afio Cox was driving a car that crashed into a concrete pole in Harmon, which led to the death of his passenger, his girlfriend, Maria Guevarra, after a night out during which they consumed alcohol, court documents state. Cox was convicted and appealed that conviction in the Supreme Court of Guam. "Cox testified that while he was driving, Guevarra punched him twice, slapped his hands and yanked the steering wheel, causing them to cross two traffic lanes and crash into a power pole on the side of the road. Guevarra died on impact as the result of a broken neck, an injury consistent with an unexpected collision," Cox's Supreme Court of Guam appeal states. The investigation revealed there weren't skid marks on the road and the crash may have been intentional, the appeal states. Court documents state Cox's blood alcohol concentration level after the accident was over the legal limit of about 0.106 percent. The Supreme Court vacated some convictions against Cox, including vehicular homicide while intoxicated, DUI with injuries and DUI as a misdemeanor. The court affirmed his convictions of vehicular homicide as a second-degree felony and DUI with injuries as a third-degree felony. Attorney James Maher, said Cox is a first-time offender and used to be a merchant marine and was left physically disabled from the accident. The prosecution asked for 10 years. Maher asked for a sentence of three years time served. Judge Vernon Perez decided on a seven-year sentence, with three years of credit for time served and about two years of credit for the past couple years, during which time Cox was on house arrest. "Given the seriousness, of course, of the offenses but treating you more in the view of a first-time offender, your sentence is technically seven years incarceration with credit for time served," Perez said. "You are facing two more years." Cox will serve those two years to serve at the Department of Corrections, beginning in April.
from PIL import Image, ImageDraw, ImageFont import os import sys def saveAsImage(image_path, new_height): chars = " .'`^\",:;I1!i><-+_-?][}{1)(|\/tfjrxnuvczXYUCLQ0OZmwqpbdkhao*#MW&8%B@$" fixed_height = new_height char_width = 9 char_height = 9 image = Image.open(image_path) height_percent = (fixed_height / float(image.size[1])) width_size = int((float(image.size[0]) * float(height_percent))) image = image.resize((width_size, fixed_height), Image.NEAREST) WIDTH, HEIGHT = image.size image = image.resize(( int(WIDTH / char_width), int(HEIGHT / char_height) ), Image.NEAREST) width, height = image.size image = image.load() ascii_image = Image.new('RGB', (WIDTH, HEIGHT), (0, 0, 0)) font = ImageFont.truetype("arial.ttf", 14) drawImage = ImageDraw.Draw(ascii_image) def getChar(value): return chars[int(value * (len(chars) / 256))] try: for i in range(height): for j in range(width): r, g, b = image[j, i] k = int((r + g + b) / 3) drawImage.text( (j * char_width, i * char_height), getChar(k), font=font, fill=(r, g, b) ) except: print('') return ascii_image
. In order to obtain the characteristics and incidence of adverse reactions of Shuxuening injection (Xingxue), the design method of a multi-center, large sample intensive monitoring in the hospitals was adopted. The hospitalized patients with use of Shuxuening injection from 27 medical institutions were enrolled as the research subjects to monitor their entire process of treatment cycle. The main content of monitoring included the patients' general information, diagnostic information, medication information, and adverse event information. A total of 30 209 patients with Shuxuening injection were enrolled; adverse reactions occurred in 34 cases, with an incidence of 0.113%, which belonged to the rare adverse reactions. Adverse reactions were characterized by headache, dizziness, pruritus, palpitations, nausea, et al. All the above results showed that Xingxue Shuxuening injection had high safety in clinical application.
An enabling Framework for Blockchain in Tourism This viewpoint article proposes an enabling framework that identifies the use of various blockchain technologies in tourism and their applications (digitalization, automation, disintermediation, and intelligent environment) across the different stages of travel (pre-trip, during the trip, and post-trip). As we know, the tourism sector contributes immensely to world GDP and job creation. However, the COVID-19 pandemic, even after two years since it first appeared, continues to adversely impact the tourism prospects of countries across the world due to nationwide lockdowns and travel restrictions. As the world tries to adapt to the new normal, the tourism sector is forced to re-think its ways of doing business and bring about innovations to facilitate the new norms of contactless and safe transactions. Also, the sector, more than ever, need to effectively deal with its inherent challenges such as transparency and credibility of information, fraudulent practices, opportunistic behavior of intermediaries, and foreign currency risks. Blockchain technology can transform the tourism sector by offering innovative solutions that address its pressing issues. However, our current understanding of blockchain application in tourism is quite limited, with previous work being largely fragmented and narrow in terms of both scope and application. We foresee that the insights offered in this viewpoint, including the framework, will advance both theory and practice and facilitate the implementation of blockchain-enabled solutions across different travel stages. Introduction The tourism sector is one of the significant contributors to the global economy. Before the pandemic, travel and tourism accounted for 10.4% of the global GDP (US$9.2 trillion) and 10.6% of all jobs in 2019 (WTTC 2021). The impact of COVID-19 on the tourism sector has been devastating, particularly for countries dependent on tourism, with travel bans, international border closures, isolation, and social distancing measures. In 2020, the tourism sector suffered from a staggering loss of US$4.5 trillion in comparison to 2019, and its contribution to global GDP declined to 5.5% (WTTC 2021). International tourist arrivals declined by almost 74% over the previous year (UNWTO 2021), and tourist spending decreased by approximately 70%, resulting in losses of around 62 million jobs in 2020 (WTTC 2021; ). It is clear from these figures that COVID-19 has severe economic consequences and continues to threaten the financial stability of the tourism sector (UNCTAD 2021). Most countries have implemented strategies and measures, including technologydriven ones, to revive the tourism economy during COVID-19 and stimulate the sector's recovery (OECD 2020). Technology-driven measures include digital payments, touchless service delivery, digital vaccination records, and crowd control technologies. However, the increase in digital technologies, automation, and online transactions has also aggravated the risk of misuse of personal information, privacy issues, cyber-attacks, and financial fraud (). Blockchain technologies can substantially transform the tourism sector. It is an "immutable distributed ledger" decentralized with no central authority and records are all validated as discrete and encrypted digital data events and transactions executed or shared among participants in a network (Irannezhad and Mahadevan 2021). It provides transparent, secure, trustworthy, and interoperable solutions, either as a standalone technology or integrated with other technologies (a). Blockchain, therefore, is a natural fit to overcome the problems brought by the COVID-19 pandemic and the inefficiencies inherent to the tourism sector, such as transparency and credibility of information, fraudulent practices, opportunistic behavior of intermediaries, and foreign currency risks (). For example, blockchain can enhance the trustworthiness and reliability of digital vaccination records. Further, blockchain could integrate the highly fragmented tourism value chain, including several actors, contracts, and transactions. The foundation for this viewpoint and the framework presented was a systematic review of the existing blockchain tourism literature. Our systematic review using the search terms "Blockchain and Tourism" OR "Block chain and Tourism" (extraction date -1st April 2021) in the Web of Science database initially identified 45 articles. After our screening protocols, we narrowed it to 26 relevant articles, and after a thorough synthesis, additional pertinent studies were identified and reviewed from the references cited. In addition, considering the still relevant novelty of the topic, various industry sources, including websites, magazines, reports, and news articles of leading consulting firms, governments, and global organizations, were reviewed to enrich our understanding of blockchain applications in tourism. We made several initial observations upon reviewing this nascent and still fragmented literature. First and foremost, most of these studies are narrow in scope (rightfully so), focusing on one or a few specific blockchain applications; for example, Treiblmaier et al. have focused on cryptocurrencies, while Veloso et al. study focused on crowdsourcing. Other studies have focused on blockchain applications in specific domains of tourism, such as medical tourism (Pilkington 2020;) or sustainable development in tourism (Tham and Sigala 2020). Many of the studies we have reviewed offer useful insights into specific applications, cases, or contexts; however, there has yet to be a systematic effort to understand the various use of blockchain technology across the lengthy tourism value chain (which begins before a tourists' search for information and continues beyond their return home). Given the importance of the future of blockchain for tourism, this viewpoint provides a timely contribution to support research, practice, and policy needed for the large-scale acceptability and implementation of blockchain in tourism. The enabling framework for blockchain in tourism we present highlights blockchain-enabled solutions and their applications across the different stages of the tourist experiences. Figure 1 presents a visual representation of our enabling framework for blockchain applications in tourism. Central to our framework is the 'Application Layer' of blockchain in tourism, indicating the meaningful and managerially relevant categories of blockchain applications (digitalization, automation, disintermediation, and intelligent environment). The 'Experience Layer' presents the three stages of the tourist experience. During the pre-trip stage, tourists decide where to go, how to get there, and where to stay, while during the trip, tourists choose where and what to eat or what activities to engage in. During the post-trip (evaluation) phase, tourists express varying degrees of satisfaction which they share (). This post-trip evaluation in reviews, blogs, and social posts is critical for inspiring other tourists in their pre-trip stage. The 'Use Layer' layer of the framework represents the uses of blockchain solutions in tourism (e.g., smart contracts, baggage tracking) across the different travel stages. Identifying these uses was a significant undertaking, given that the central task of developing any technology-enabled framework is identifying key technology solutions for inclusion (You and Feng 2020;bBalasubramanian et al., 2022. Development of the blockchain framework for tourism This application layer (top layer) connects the experience layer (middle layer) with the use layer (bottom layer). The interconnections in the framework between the application, experience, and use layers illustrate that all three tourist travel stages can benefit from blockchain solutions that foster digitalization, automation, disintermediation, and intelligent environment. For instance, the tourism sector can benefit from digitalization (e.g., digital payments) across all three travel stages. Cryptocurrencies and digital payments contribute to the tourism sector's digitalization drive by converting the physical ecosystem to a digital ecosystem, and this 'digitalization' may have different implications at different stages of the travel experience. Digitalization Digitalization uses digital technologies such as blockchain to convert the physical ecosystem to a digital ecosystem and then manage it virtually. It is changing the way people live, work, travel, and do business, and in the process, transforming and reshaping tourism (OECD 2020). As evident from the review, blockchain can enhance the digitalization drive of the tourism sector on a global scale and, in the process, improve the tourist experience and generate new business opportunities for the sector. For instance, blockchain solutions such as digital identity management, digital payments, and smart contracts have significantly reduced the inefficient paper-intensive processes seen in the tourism sector. Blockchain solutions have also increased transparency and minimized fraud and errors, processing times, and transaction costs for all parties involved (). Blockchain can support governments' drive towards cashless economies (nder and Gunter 2020). Further, blockchain promotes contact-less payments, which is strongly encouraged during the COVID-19 pandemic (nder and Gunter 2020). Therefore, international travelers could benefit from having a unified cashless and contactless payment system without the need to carry foreign currency cash. Finally, increasing P2P transactions via blockchain can further advance the sharing economy (Filimonau and Naumova 2020;Tham and Sigala 2020). Many governments, especially those relying heavily on tourism (e.g., Malta, the Caribbean economies, Aruba, and the Marshall Islands), have started to make significant investments in blockchain technology to enhance their tourism sector. Also, there are several blockchain-backed virtual tourism solutions. For tourists, who cannot travel due to COVID-19 travel restrictions, virtual reality allows them to virtu- ally visit and experience destinations from the comfort of their homes (Entrepreneur 2021). For example, Victoria VR is a blockchain-based ecosystem that unites multiple virtual reality platforms and creates a world filled with user-created photorealistic content recorded in the blockchain. Therefore, Victoria VR users can work, visit tourist destinations, participate in meetings, enjoy concerts and play games without any risks or need to travel (Entrepreneur 2021). Further, the virtual reality and augmented reality solutions powered by blockchain technology allow verified users to virtually participate in sold-out physical events such as music concerts by purchasing tokens (Mofokeng and Matima 2018). Given the significant investments in the Metaverse, we would expect blockchain applications supporting the tourism metaverse to be a key consideration in the near future. Automation Tourism process automation on a global scale can be significantly driven by or facilitated by blockchain, thereby increasing the sector's efficiency, accuracy, and productivity. For instance, blockchain can automate a range of business dealings or transactions between tourists and service providers, including insurance preapprovals, without human intervention from a legal perspective (Shen and Bai 2020). Blockchain-powered smart contracts are self-executing and self-enforcing, with predefined rules, procedures, and penalties (;Irannezhad and Mahadevan 2021). For example, blockchain offers automatic flight delay insurance for its customers; as soon as a flight delay is detected, compensation is initiated immediately and securely, thus avoiding additional paperwork (Radanovi and Liki 2018). Similarly, blockchain can automate secure check-ins at airports (e.g., digital passports, smart gates) and hotels through digital keys or biometric identification (). This automation creates mutually beneficial outcomes for tourists and service providers by reducing processing times. Disintermediation Blockchain's ability to increase the level of disintermediation (reduced need for intermediaries) is evident. Blockchain applications can remove intermediaries such as online travel agents from the tourism value chain (nder and Treiblamer 2018). Disintermediation enables tourists to make informed decisions and also makes travel more affordable. It shifts the balance of power from institution-centric to tourist-centric mode. Disintermediation increases accountability, transparency, trust, and collaboration among stakeholders in the tourism sector (Rashideh 2020). For example, digital payments using cryptocurrencies eliminate the need for a central authority such as banks or other intermediaries (Valeri and Baggio 2021). Also, blockchain helps tourism firms, especially smaller firms, to gain access to consumer data; they can buy data directly from the consumers rather than relying on and buying from Facebook and Google, which sells data to "anyone" who can afford to pay for it (Tham and Sigala 2020). Disintermediation also minimizes the privacy and security concerns of data theft, identity theft, and credit card theft, that tourists may have about sharing their sensitive data, including financial data, with travel agencies or other intermediaries (apar 2020). These concerns are reduced because blockchain is a 'privacy-by-design solution and will give data access only to authorized actors after verifying the identity, such as by using a digital signature or certificate. It also provides more control and ownership for tourists over the personal data they share with service providers (). Intelligent Environment Blockchain technologies have the potential to make the sector more intelligent. For instance, advances in blockchain combined with big data analytics and artificial intelligence can enhance understanding of tourist needs, enabling personalized recommendations of tourism products and services (). Similarly, blockchain combined with biometric readers can allow tourists to go through automated clearance gates and hotel check-in, significantly eliminating identity theft and fraud (;). Likewise, blockchain combined with the Internet of Things (IoTs), RFIDs, and QR codes can provide end-to-end supply chain visibility, reducing counterfeit and fake products and services. For example, blockchain can provide end-to-end supply chain traceability of wine, from grape cultivation to winemaking and distribution/sales until the final stage of consumption at the cellar door or restaurant (Tham and Sigala 2020). Blockchain solutions across stages of the tourist experience In the following sections, we explore some of the challenges and inefficiencies that can be addressed through blockchain solutions. We have organized this discussion into pre-trip, during-trip, and post-trip stages of travel. Pre-trip stage One of the challenges of the tourism sector is the lack of transparency, such as information on hotel's capacities, different rates at different source markets, and data discrepancies due to bookings passing through multiple systems, human errors, double booking, manual and paper-based communication (Irannezhad and Mahadevan 2021). It is estimated that data discrepancies can impact about 5-10% of bookings (around US$10 billion) due to the volume of bookings passing through multiple systems (Microsoft 2016). Blockchain provides various solutions to enhance transparency and minimize data discrepancies. First, it eliminates the need for manual or paperbased communications and payments (Irannezhad and Mahadevan 2021;). Blockchain provides a one-stop-shop for tourists to connect and coordinate tour and travel activities, improving their user experience and security where all price information and other aspects are continuously updated (;Irannezhad and Mahadevan 2021). It enables tourists open access to real-time information on availability and prices to find and book the best deals, enabling improved itinerary planning (nder and Gunter 2020;). It also reduces overbooking and manipulation of booking and prices (;Melki and avlek 2020). The other concern of tourists while performing enquires and booking is data ownership, use, and control resulting from the digitization of tourists' information (). Addressing tourists' privacy concerns, potential hacks, and identity theft are all critical for the sector (). Blockchain technology can address these challenges since privacy and data protection are built into the blockchain system from the inception of the system's design (). Data platforms built on permissioned blockchain give data access only to authorized actors by verifying their identity using a digital signature or certificate (). Blockchain provides more control and ownership for tourists of the personal data they share with service providers (Kwok and Koh 2019;). The data shared by tourists through blockchain can be used by service providers (with tourist consent) to create mutually beneficial outcomes for both parties, such as personalized products and services based on a complete picture of consumer preferences (Irannezhad and Mahadevan 2021;). Blockchain technology could link the complex system of data points that form consumers' online identities (;). It was evident that blockchain consumers are more comfortable receiving personalized products and services at their discretion and control (). Blockchain-powered tourism crowdsourcing platforms accumulate, centralize and process large volumes of tourism data to provide multiple value-added artificial intelligence-based services in real-time, including personalized recommendations and emerging trends for prospective tourists (). Further, knowledge of tourist preferences allows service providers to bundle several types of travel and tourism services such as accommodation, airline, cruise, and railway booking (Irannezhad and Mahadevan 2021). Also, blockchain enables peer-to-peer (P2P) transactions (e.g., customer to customer) for online bookings and reservations (e.g., hotel reservations; air tickets; tour packages) and permits tourists to use digital (crypto) currency (e.g., Bitcoin, Ripple) without being dependent on a financial institution or relying on third parties or other intermediaries (Valeri and Baggio 2021). The advantage of using crypto payments over conventional payments such as credit cards include non-existent or very low transaction fees and commissions (Melki and avlek 2020), instant transfer without any time lag compared to 3 to 5 business days for credit cards (Willie 2019), no maximum limit on transaction amount (Melki and avlek 2020), and elimination of currency exchange rate concerns for cross-border remittance (;apar 2020). Some travel companies have started to list their prices in cryptocurrencies such as Bitcoin, making the payment process easier (Rashideh 2020). Of course, the high volatility of cryptocurrencies is a key barrier to wide adoption across the sector. Another advantage of blockchain during the pre-travel stage is the execution of smart contracts, which can automate a range of business dealings or transactions between tourists and service providers without human intervention from a legal perspective (Irannezhad and Mahadevan 2021). Smart contracts can be self-executing and self-enforcing by nature as they essentially entail a coded program of an agreement between two or more parties (). Again, this can create mutually beneficial outcomes for tourists and service providers. It eliminates the need for intermediaries (e.g., notaries, banks, brokers, agents, or other companies), thereby reducing costs and processing times (). Rules, procedures, and penalties are defined and agreed upon by the parties involved in the smart contract (Willie 2019). It enables greater flexibility for tourists, which otherwise was not available with traditional transactions. For instance, with smart contracts, tourists can resell, trade, or exchange bookings such as airline tickets with other travelers if they cannot travel due to any circumstances (nder and Gunter 2020;Irannezhad and Mahadevan 2021). Some smart contracts allow tourists to rebook if prices decrease after purchase, and the price difference is credited instantly to the tourist's account (nder and Gunter 2020). Similarly, smart contracts allow easy cancellations, upgrades, or changes in bookings (Melki and avlek 2020;). Finally, tourist reviews and ratings of service providers (e.g., airlines, cruise, hotels, restaurants) are critical factors in purchasing a tourism product or service (Melki and avlek 2020). Although it has become popular, it has been lambasted for its inability to distinguish between genuine and falsified reporting and trustworthiness (;). Fake reviews, which can become recurring due to ever-increasing business competitiveness, represent a critical issue for tourism (Filimonau and Naumova 2020). The sector needs to ensure that the content of the reviews and ratings published on digital platforms is honest and trustworthy to ensure that consumers can rely on them when researching and planning their travels (). Blockchain can improve the trust and transparency of the online review system (). The immutability of records in blockchain ensures that any review posted on the blockchain platform cannot be deleted, and updates are only possible with a traceable history (). Secure digital identification can ensure authentic customer reviews are distinguishable from inauthentic ones through traceable identities (Filimonau and Naumova 2020). This traceability does not necessarily mean that personal identities have to be revealed; all entries are signed with a unique private key that confirms that a specific transaction comes from a particular user. As a result, users would be unable to create duplicate reviews with the same identity and could impede the manipulation of reviews (nder and Treiblmaier 2018). Tourists, therefore, can use these trusted rankings and ratings to select service providers. During the trip Tourists go through numerous identification and registration processes during their journey. For instance, they must carry and present identity documents for airport security, immigration, boarding gate, duty-free shopping, at a hotel, or securing a rental car (Irannezhad and Mahadevan 2021). Digital identification using blockchain technology could improve the way travelers are identified during their journey and avoid unpleasant encounters at various checkpoints. These unique digital IDs can replace passports and all identification-related documents such as birth certificates and driver's licenses (Rashideh 2020;nder and Gunter 2020). For instance, blockchain-powered digital identities such as e-passports or digital passports can minimize the waiting time of tourists at border control, especially when combined with smart gates and scanners through automated check-in/out (;). Blockchain-based identity systems (e.g., secure biometric identity systems) could potentially negate this issue of lost passports and reduce identity theft and fraud (;). Blockchain facilitates quick, automated, and seamless identification of tourists throughout their journey (Melki and avlek 2020;). Also, digital IDs enable archiving medical tourist health records in a secure digital infrastructure that can be accessed from anywhere in the world for those authorized by the patient (apar2020). The secure medical archives enable fast access to medical tourists' history, enabling correct diagnosis and treatment. It can also provide evidence for possible malpractice cases at medical tourist destinations (apar 2020). Blockchain-enabled smart contracts can instantly process travel insurance claims in case of flight delay or cancellation, thereby greatly enhancing the tourism experience (;Irannezhad and Mahadevan 2021). For instance, AXA, a leading French insurance group, has developed a blockchain platform called Fizzy on the Ethereum platform that offers automatic flight delay insurance for its customers; as soon as a flight delay is detected, compensation is initiated immediately and securely, thus avoiding the need for additional paperwork (Radanovi and Liki 2018). The use of blockchain-enabled digital payments and cryptocurrencies makes cross-border transactions easier and minimizes the risk of foreign currency exchange rates ). An increasing number of tourism vendors have started accepting cryptocurrencies. Importantly, it eliminates credit card thefts (a significant concern for tourists) during travel (Rashideh 2020). During their travels, tourists can use cryptocurrency to pay for admission tickets, souvenirs, public transport fares, ride-sharing, restaurants, and cafes ). For instance, as early as 2014, Pattaya and Bangkok in Thailand started accepting bitcoin from tourists due to the widespread ATM and credit card fraud (Irannezhad and Mahadevan 2021). Therefore, tourists who visit Thailand are increasingly looking for traders who accept Bitcoin (Rashideh 2020). Similarly, Travelflex coins can be used in the same way as travelers' checks. It also enables P2P transactions such as customer-to-customer (C2C) transactions as crypto coins can be sent and received directly between users (). Also, cryptocurrencies are convenient to use as they are typically stored in a prepaid digital wallet installed on a user's mobile phone (). The increasing acceptance of cryptocurrency has encouraged governments, especially those relying heavily on tourism, to recognize and support the use of cryptocurrencies and even consider creating their own cryptocurrencies (Kwok and Koh 2019;Rashideh 2020;). Another tourist concern that can be addressed using blockchain is baggage that is delayed, stolen, damaged, or sent to the wrong destination. Such incidents pose a high cost for the aviation sector and cause negative experiences for tourists. The International Airline and Travel Association estimates that the aviation sector could realize an annual savings of over US$500 million by reducing inefficiencies related to baggage mishandling (Irannezhad and Mahadevan 2021). Blockchain technology could significantly improve baggage handling, especially during international travel, as, in many instances, the tourist's baggage changes hands more than once during their trip (Rashideh 2020). The blockchain shared distributed ledger could allow for luggage and ownership details to be automatically logged on at various points, making it easier to locate luggage in real-time wherever it may be during transit (Willie 2019;nder and Gunter 2020). Additionally, it is possible to provide tourists with up-to-date information about the current location of their baggage on their smartphones (Willie 2019). Further, baggage tracking can be linked to smart contracts with airlines or travel insurance firms to automatically trigger compensation pay-out when the shared ledger records the lost, damaged, or delayed baggage information (). The peer-to-peer nature of the blockchain network encourages tourists to deal directly with suppliers, saving time and money (Rashideh 2020). For example, 'Beenest' is a blockchain-based firm that matches accommodation providers with seekers (tourists) and is a competitor to Airbnb (Irannezhad and Mahadevan 2021). Similarly, 'MeetnGreetMe' is a blockchain-based global C2C platform connecting international travelers with local guides. Tourists can select from approved local guides (Tham and Sigala 2020). Blockchain-based loyalty programs are another example of a helpful application of blockchain for tourists (nder and Gunter 2020). It addresses the limitation of most traditional loyalty programs that are neither transferrable nor can be utilized when purchasing from a third party, leading to low redemption rates and high switching costs (). In blockchain-based inter-operable loyalty programs, loyalty points (tokens) can be sold or exchanged with others and could earn or redeem loyalty points across multiple vendors throughout the journey (;nder and Gunter 2020). It enables different firms in the tourism sector (e.g., airlines, hotels, and car rentals) to consolidate and manage their loyalty programs under one blockchain-based loyalty program (Tham and Sigala 2020), thereby addressing the high fragmentation of countless loyalty points, cards, and earning systems (). Blockchain also enables tourists to earn and use their loyalty points in realtime and not wait for the points to be credited much later, as with traditional programs (Irannezhad and Mahadevan 2021). For example, with 'Trippki,' tourists can use their tokens or loyalty points to pay for a hotel stay, restaurant, etc. (). Similarly, 'Loyyal' is a blockchain-based platform that improves the interoperability of airline loyalty programs by easing the transfer of points to other airlines, partner hotels, and car rentals (Filimonau and Naumova 2020). Blockchain also facilitates innovative rewards programs through the real-time use of tourist locations to generate location-based privileges such as offers and discounts (). Further, blockchain can be used to reward tourists for their sustainable behavior (e.g., using less energy and water at hotels) (). Also, blockchain-based product labeling can significantly enhance the truthfulness of specific product labels (Filimonau and Naumova 2020; Rashideh 2020). All information regarding the product (e.g., the ingredients, when and where it is made, stored, and transported) will be available to tourists within seconds by scanning QR codes to determine whether the product is authentic and reliable (Willie 2019). Accurate food labeling is critical due to the rise in health-and allergen-conscious tourists (Filimonau and Naumova 2020). It also alleviates tourists' concerns with religious considerations such as halal compliance for Muslim tourists (Filimonau and Naumova 2020). Similarly, end-to-end supply chain traceability solutions using blockchain can tackle counterfeit, fake, and contaminated goods. For instance, foodrelated health and safety is a main concern of tourists. Blockchain solutions can track the food supply at each stage of its journey, from its origin until it reaches the end customer, i.e., from farm to fork, thereby avoiding food contamination and poisoning (nder and Gunter 2020). If the food supply arrives in bad condition, the offending incident can be tracked precisely, including detailed information on storage temperature, humidity, and GPS data (;nder and Gunter 2020). Overall, product labeling and supply chain traceability can address the growing demand of tourists to have food that is organic, local, authentic, sustainably sourced, safe, clean, fresh, and nutritious (;Willie 2019). Similarly, blockchain solutions can tackle drug counterfeiting, a potential problem affecting medical tourists (nder and Gunter 2020). Post-trip stage Blockchain technology can encourage tourists to post comments, opinions, pictures, reviews, and feedback about their post-trip experience as they receive crypto coins/ tokens as rewards in exchange (). Tourists can use these reward coins/ tokens for booking their next trip or convert them into cash or exchange them with other types of cryptocurrencies (). Also, to promote the quality of the review contents, the platform can enforce rules to link rewards to the review acceptance (high rewards for high approval and vice versa) by other users on the platform (). The posted reviews can be marked as "fake" or "genuine," or "high quality" or "low-quality" when the majority of users agree. As mentioned earlier, since blockchain uses secure digital identification (unique private key for each identity) with several independent verification processes, the tourist reviews in a tamper-resistance blockchain platform could be considered more reliable and trustworthy and prevent fake and duplicate reviews (nder and Treiblmaier 2018;Filimonau and Naumova 2020). For example, only reviews posted via verified personal profiles are marked as trusted reviews and monetized for tokens (). Overall, trusted post-trip reviews of tourists will significantly impact the decision-making behavior of potential tourists. Similarly, blockchain platforms can change the way data are collected in the reflective post-trip phase. Tourists are rewarded for sharing or authorizing the use of their post-trip data with service providers. This data could include transaction history, locations visited, events attended, and activities engaged from previous trips (;). Smart contracts could execute the transaction by autonomously collecting or sharing the data with the requesters (tourism service providers). At the same time, the smart contract would transfer the money (or other incentives) to the tourists (). Also, based on the shared data, tourists may receive personalized recommendations, bundle offers, and discounts for their next trip (). For example, 'Travel Chain' provides a blockchain platform that empowers travelers to share information such as their travel purchases, location, and stays in accommodations in exchange for tokens, which can be used for booking their next flights, hotels, or renting a car (). Finally, tourists can receive tokens as rewards for referring other tourists. For example, 'Travel Block' provide tourists 5% discount as a referral reward for their next booking (). Implications and concluding remarks The goal of this viewpoint article was to identify and integrate the scattered knowledge on blockchain in tourism into a meaningful and managerially relevant framework. The simplified yet comprehensive conceptualization of blockchain solutions and applications in tourism is critical for the progress of the field, given that the scientific contours of blockchain in tourism are not clearly defined. We expect practitioners and policymakers to find this framework useful for assessing the current and potential blockchain applications in the tourism sector. Given the proposed framework's conceptual comprehensiveness and generic nature, we hope that researchers in different countries could adopt, enhance, and use it in their respective contexts. The multitude of uses and applications of blockchain across the different stages of the tourist experience identified in the framework provides a foundation for future studies. Understanding the full potential of blockchain is important now, given its role in supporting the tourism sector to recover from the COVID-19 pandemic. We endeavored to write this viewpoint in an accessible way with the hope that it is useful for practitioners and policymakers to familiarize themselves with blockchain applications and the benefits afforded by the technology. The use of blockchain technologies in tourism can potentially bring down the overall cost structure and benefit tourists and various service providers in the sector. The decrease in costs will boost the sector, enabling price-sensitive people to undertake travel, especially in these economically challenging times brought about by the COVID-19 pandemic. Further, a reduction in manual processing and paper transactions will also prove helpful during the pandemic when people feel uncomfortable about face-to-face contact and handling paper. Blockchain can enhance the overall user experience in the tourism sector by increasing transparency and access to upto-date information, reducing costs, and minimizing the number of transactions and the need for intermediaries. Blockchain can increase opportunities for entrepreneurs in the tourism sector, whereby small tour operators and accommodation providers can set up shop and establish credible identities through blockchain platforms. The trust accorded by blockchain will enhance user (tourist) trust in using these entrepreneurial ventures' services and help expand the tourism market. Another benefit from the user perspective is that the use of blockchain shifts the ownership of data to users, thereby reducing the unilateral usage of customer data by service providers for marketing purposes or other activities that may result in financial gain to the provider without customer knowledge (). Moreover, blockchain can improve the coordination between stakeholders. For example, if a tourist does not check in for their flight, this can trigger an update of the car rental company's inventory and the hotel's availability (Treiblmaier 2020). Overall, the insights and the framework are helpful for practitioners and policymakers looking to take advantage of the full opportunities of blockchain in tourism. Given the uncertainty over how long this COVID-19 pandemic will last, with several countries experiencing or likely to experience the new wave of infections due to evolving COVID-19 variants, we anticipate the uptake of blockchain technology in the tourism sector to continue to accelerate. However, several factors limit the adoption of blockchain technology in the tourism sector. For instance, many countries have not developed a regulatory framework that legitimizes the use of cryptocurrency, which affects users' trust. Further, this legal vacuum could also lead to inappropriate use of cryptocurrencies, such as money laundering and funding terrorists or other illegal activities. Many blockchain applications rely on technical know-how, attitude towards trying out new technology, and access to mobile devices. There is still a digital divide between developed and underdeveloped nations (Sigala 2020). A significant proportion of the world population does not have the devices or the infrastructure to access the required technologies. This divide may prevent some countries and small businesses from reaping the benefits of blockchain-enabled technologies. The other concern of blockchain is the lack of system scalability, such as adapting to the increased data processing requirements (Melki and avlek 2020). In addition, the low transaction speed and high energy consumption of blockchain could hinder the widespread implementation of blockchain solutions (). Although we have presented a comprehensive blockchain framework for tourism, it still may not have covered every blockchain solution and application in tourism. Still, we are confident that the insights offered, including the framework, contribute towards advancing both theory and practice and offer pragmatic and managerially relevant blockchain-enabled solutions that could facilitate the widespread implementation of blockchain in the tourism sector. We are optimistic that our framework will encourage and help guide future research on this important domain. Open Access This article is licensed under a Creative Commons Attribution 4.0 International License, which permits use, sharing, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if changes were made. The images or other third party material in this article are included in the article's Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article's Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/ licenses/by/4.0/.
package com.foysal.cipher; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; public class RSA { public static int gcd(int a, int b) { if (a == 0) return b; else return gcd(b % a, a); } // //--------------------------------------------------------------------- // public static int Encryption(int plainText,int e, int n) { // double cipherText = (Math.pow(plainText, e)) % n; // System.out.println("Ciphertext: " + (int)cipherText); // return (int)cipherText; // } // // public static void Decryption(int cipherText, int d, int n) { // double plainText = (Math.pow(cipherText, d)) % n; // System.out.println("PlainText: " + (int)plainText); // } // //---------------------------------------------------------------------- private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) { System.out.println("Enter Plaintext for Encryption and Decryption: "); int plainText = scan.nextInt(); int p, q; System.out.println("Choose large prime (p): "); p = scan.nextInt(); System.out.println("Choose large prime (q): "); q = scan.nextInt(); int n = p * q; int z = (p - 1) * (q - 1); System.out.println("The value of z = " + z); int e = 13; // for (e = 2; e < z; e++) { // if (gcd(e, z) == 1) // e is for public key exponent // { // break; // } // } System.out.println("The value of e = " + e); int d = 0; for (int i = 0; i <= 9; i++) { int x = 1 + (i * z); if (x % e == 0) // d is for private key exponent { d = x / e; break; } } System.out.println("The value of d = " + d); System.out.println("Public key (e, n) = " + e + "," + n); System.out.println("Private key (d) = " + d); // int cipherText = Encryption(plainText, e, n); // // Decryption(cipherText, d, n); double cipherText = (Math.pow(plainText,e))%n; System.out.println("Ciphertext: " + (int)cipherText); //converting int value of n to BigInteger BigInteger N = BigInteger.valueOf(n); //converting float value of c to BigInteger BigInteger C = BigDecimal.valueOf(cipherText).toBigInteger(); BigInteger decryptedText; decryptedText = (C.pow(d)).mod(N); System.out.println("PlainText: " + decryptedText); } } /* The value of z = 60 The value of e = 13 The value of d = 37 Public key (e, n) = 13,77 Private key (d) = 37 Ciphertext: :26 PlainText : 5 */
Law, Capitalism and Power in Asia: The Rule of Law and Legal Institutions. Edited by Kanishka Jayasuriya. London and New York: Routledge, 1999. xiii, 345 pp. The volume ends with country studies of India, Indonesia, Japan, Korea, Mongolia, Papua New Guinea, China, the Philippines, Taiwan, and Thailand. The Thailand chapter, written by editor Herrmann, asks whether Thailand can save its premier position in Southeast Asia in view of the 1997 economic crisis. He deals with the question by laying out the strengths and weaknesses of the Kingdom, touching on Thailand's relations with colonialists and on the nation's political culture which he argues is marked by a high degree of individualism, and which manifests itself in the absence of political party organization and a consequent instability. He suggests that democratization is occurring, but on Thai terms: respect for hierarchy, fatalism, debts of gratitude, absence of open conflict, respect for individual freedom, and the preservation of face. He predicts that this political culture will preclude future military coups d'etat. Certainly, all of these points are complex and controversial, especially when the reader notes that Herrmann's analysis of Thai security concerns, the Thai economy, the Thai military, and Thai culture, take just ten pages. The result is necessarily simplistic but nevertheless thought-provoking. Asia's Security Challenges does not add significantly new data or interpretations to our understanding of the region. The volume does present the reader with an overview of the crucial issues and makes the important point that security is no longer a narrow field. On the contrary, the new specialists must be well grounded in the economic, cultural, political, and strategic aspects of Asian societies if they want to understand Asia's security challenges.
<filename>LX_Parser/stanford-parser-2010-11-30/src/edu/stanford/nlp/parser/lexparser/IntTaggedWord.java package edu.stanford.nlp.parser.lexparser; import edu.stanford.nlp.ling.TaggedWord; import edu.stanford.nlp.ling.Label; import edu.stanford.nlp.util.Numberer; import edu.stanford.nlp.util.StringUtils; import java.io.Serializable; /** Represents a WordTag (in the sense that equality is defined * on both components), where each half is represented by an * int indexed by a Numberer. In this representation, -1 is * used to represent the wildcard ANY value, and -2 is used * to represent a STOP value (i.e., no more dependents). * * @author <NAME> * @author <NAME> */ public class IntTaggedWord implements Serializable, Comparable<IntTaggedWord> { public static final int ANY_WORD_INT = -1; public static final int ANY_TAG_INT = -1; public static final int STOP_WORD_INT = -2; public static final int STOP_TAG_INT = -2; public static final String ANY = ".*."; public static final String STOP = "STOP"; private static Numberer wordNumberer; private static Numberer tagNumberer; static Numberer wordNumberer() { if (wordNumberer == null) { wordNumberer = Numberer.getGlobalNumberer("words"); } return wordNumberer; } static Numberer tagNumberer() { if (tagNumberer == null) { tagNumberer = Numberer.getGlobalNumberer("tags"); } return tagNumberer; } public static void setWordNumberer(Numberer wordNumberer) { IntTaggedWord.wordNumberer = wordNumberer; } public static void setTagNumberer(Numberer tagNumberer) { IntTaggedWord.tagNumberer = tagNumberer; } static void resetNumberers() { wordNumberer = null; tagNumberer = null; } public int word; public short tag; public int tag() { return tag; } public int word() { return word; } public String wordString() { String wordStr; if (word >= 0) { wordStr = (String) wordNumberer().object(word); } else if (word == ANY_WORD_INT) { wordStr = ANY; } else { wordStr = STOP; } return wordStr; } public String tagString() { String tagStr; if (tag >= 0) { tagStr = tagNumberer().object(tag).toString(); } else if (tag == ANY_TAG_INT) { tagStr = ANY; } else { tagStr = STOP; } return tagStr; } public Label tagLabel() { return (Label)(tagNumberer().object(tag)); } @Override public int hashCode() { return word ^ (tag << 16); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (o instanceof IntTaggedWord) { IntTaggedWord i = (IntTaggedWord) o; return (word == i.word && tag == i.tag); } else { return false; } } public int compareTo(IntTaggedWord that) { if (tag != that.tag) { return tag - that.tag; } else { return word - that.word; } } private static final char[] charsToEscape = new char[]{'\"'}; public String toLexicalEntry() { String wordStr = wordString(); String tagStr = tagString(); return '\"' + StringUtils.escapeString(tagStr, charsToEscape, '\\') + "\" -> \"" + StringUtils.escapeString(wordStr, charsToEscape, '\\') + '\"'; } @Override public String toString() { return wordString()+ '/' +tagString(); } public String toString(String arg) { if (arg.equals("verbose")) { return wordString() + '[' + word + "]/" + tagString() + '[' + tag + ']'; } else { return toString(); } } public IntTaggedWord(int word, int tag) { this.word = word; this.tag = (short) tag; } public TaggedWord toTaggedWord() { String wordStr = wordString(); String tagStr = tagString(); return new TaggedWord(wordStr, tagStr); } /** * Creates an IntTaggedWord given by the String representation * of the form &lt;word&gt;|&lt;tag*gt; */ public IntTaggedWord(String s, char splitChar) { // awkward, calls s.indexOf(splitChar) twice this(extractWord(s, splitChar), extractTag(s, splitChar)); // System.out.println("s: " + s); // System.out.println("tagNumberer: " + tagNumberer); // System.out.println("word: " + word); // System.out.println("tag: " + tag); } private static String extractWord(String s, char splitChar) { int n = s.lastIndexOf(splitChar); String result = s.substring(0, n); // System.out.println("extracted word: " + result); return result; } private static String extractTag(String s, char splitChar) { int n = s.lastIndexOf(splitChar); String result = s.substring(n + 1); // System.out.println("extracted tag: " + result); return result; } /** * Creates an IntTaggedWord given by the tagString and wordString */ public IntTaggedWord(String wordString, String tagString) { if (wordString.equals(ANY)) { word = ANY_WORD_INT; } else if (wordString.equals(STOP)) { word = STOP_WORD_INT; } else { word = wordNumberer().number(wordString); } if (tagString.equals(ANY)) { tag = (short) ANY_TAG_INT; } else if (tagString.equals(STOP)) { tag = (short) STOP_TAG_INT; } else { tag = (short) tagNumberer().number(tagString); } } private static final long serialVersionUID = 1L; } // end class IntTaggedWord
<reponame>norraell/ikozaeder<gh_stars>0 import _ from 'lodash'; import React from 'react'; import { makeStyles } from 'styles'; import { unescapeName } from 'math/polyhedra/names'; import { media, fonts } from 'styles'; // added (RG): changed styles const styles = makeStyles({ title: { fontFamily: fonts.andaleMono, fontSize: '1.8em', textAlign: 'center', color: '#000', margin: 'auto', [media.mobile]: { fontFamily: fonts.andaleMono, fontSize: '1.8em', textAlign: 'center', color: '#000', margin: 'auto', }, }, }); // added (RG): hard-coded title const Title = ({ name }: { name: string }) => { return ( <h1 className={styles('title')}>i:kozaeder</h1> ); }; export default Title;
. Scleromyxedema is a type of mucinosis that presents with some well defined clinical and histopathological characteristics. We describe the findings observed with transmission electron microscopy in a case that we recently studied. The patient was a 56-year-old female with a localized eruption of lichenoid papules on the face, upper trunk and limbs. It was accompanied by IgG lambda gammopathy. Optical microscopy showed the findings typical of scleromyxedema. Electron microscopy revealed the existence of a large number of fibroblasts with high activity levels in the synthesis and release of collagen fibers and a mucoid substance.
TEHRAN - Russian President Vladimir Putin is scheduled to visit India on October 4-5 for the 19th India-Russia annual bilateral summit, Indian government officially announced on Friday. Netanyahu says Persia made “an attempt to destroy the Jewish people nearly 2,500 years ago! TEHRAN - During a meeting on Thursday in Moscow, Russia’s President Vladimir Putin and Israel’s Prime Minister Benjamin Netanyahu exchanged opinions on the situation in the Middle East and discussed bilateral cooperation. TEHRAN – Russian President Vladimir Putin’s special envoy on Syria is scheduled to travel to Tehran on Sunday. President-elect Donald Trump has nominated Rex Tillerson for Secretary of State. President-elect Donald Trump has nominated Rex Tillerson for Secretary of State. Can Tillerson succeed as secretary of state? Having worked for half a dozen of his predecessors, here are several takeaways on the significance of his appointment. TEHRAN – The Russian deputy foreign minister for African and Arab affairs on Wednesday said his country informed Iran of the U.S. suggestions on Syria when he recently visited Iran, Tasnim reported. TEHRAN – The Kremlin says Russian President Vladimir Putin’s point man on Syria has delivered a “confidential” letter penned by the Russian head of state to Iranian President Hassan Rouhani. TEHRAN – Iranian President Hassan Rouhani said on Saturday that Iran and Russia will continue cooperation in fighting terrorism until it is eradicated. TEHRAN – Russia’s presidential representative for the Middle East and Africa is scheduled to visit Iran on Monday for talks on issues of mutual interest, including the ongoing crisis in Syria, Ebrahim Rahimpour, deputy foreign minister for Asia-Pacific Affairs, told IRNA on Thursday.
Comparison of refined and crude indigo naturalis ointment in treating psoriasis: randomized, observer-blind, controlled, intrapatient trial. individual cycles in secondary analyses. Cox proportional hazards regression models were used to estimate relative risks (RRs) and 95% CIs. Analyses were updated because the main exposure, outcome, and covariates were all time varying. We had multivariate models with or without smoking. Analyses were conducted using SAS software, version 9.2 (SAS Institute Inc). The study was approved by the institutional review board of Brigham and Womens Hospital. Our receipt of each completed questionnaire implied participants informed consent of the present study.
<reponame>petoandroide/RPAAutomatedTest import os import getpass from glob import glob from testConfig import config from logDriver import LogDriver from interactions.defaultInteractions import tailAndWaitFor from interactions.defaultInteractions import tailNAndSearchFor def argParser(kwargs): if kwargs: return f'{str(kwargs)}' def run(The=None, withArgs=None, **kwargs): task = The deafultRPATool = config['RPA_TOOl'] RPATaskFolder = config['RPA_TASK_FOLDER'] if 'uipath' in deafultRPATool.lower(): argx = argParser(withArgs) robotRunnerPath = glob( f'C:\\Users\\{getpass.getuser()}\\AppData\\Local\\UiPath\\app-*' )[0] UiRobotExe = f'{robotRunnerPath}\\UiRobot.exe' xaml = f'/file:"{RPATaskFolder}{task}"' if argx: robotRunnerCommand = f'{UiRobotExe} {xaml} /input:"{argx}"' else: robotRunnerCommand = f'{UiRobotExe} {xaml}' elif 'automationanywhere' in deafultRPATool.lower(): robotRunnerCommand = f'{RPATaskFolder}{task}' os.popen(f'"{robotRunnerCommand}"') return LogDriver def executeThe(log: LogDriver, **kwargs) -> LogDriver: tailAndWaitFor(log, kwargs['Process']) def finishTheExecution(log: LogDriver, **kwargs) -> LogDriver: tailNAndSearchFor(log, kwargs['inState'])
package behavioural.visitor; public class RealEstate implements Asset { private int estimatedValue; private int MonthlyRent; RealEstate(int estimatedValue, int monthlyRent) { this.estimatedValue = estimatedValue; MonthlyRent = monthlyRent; } public int getEstimatedValue() { return estimatedValue; } int getMonthlyRent() { return MonthlyRent; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
The Green & Gold Village is a co-ed Freshman housing complex at the College of William and Mary comprised of three buildings: Griffin, Eagle, and Lion. It is located across the street from William and Mary Hall. Construction on the Green & Gold Village took place in 2013. This page was last modified on 30 April 2016, at 18:30.
Directed by Directionality: Benefiting from the Gain Pattern of Active RFID Badges Tracking of people via active badges is important for location-aware computing and for security applications. However, the human body has a major effect on the antenna gain pattern of the device that the person is wearing. In this paper, the gain pattern due to the effect of the human body is experimentally measured and represented by a first-order directional gain pattern model. A method is presented to estimate the model parameters from multiple received signal strength (RSS) measurements. An alternating gain and position estimation (AGAPE) algorithm is proposed to jointly estimate the orientation and the position of the badge using RSS measurements at known-position anchor nodes. Lower bounds on mean squared error (MSE) and experimental results are presented that both show that the accuracy of position estimates can be greatly improved by including orientation estimates in the localization system. Next, we propose a new tracking filter that accepts orientation estimates as input, which we call the orientation-enhanced extended Kalman filter (OE-EKF), which improves tracking accuracy in active RFID tracking systems.
CAIRO—Three Egypt internationals and Al-Ahly players have retired from all football after witnessing the deadly clashes between fans at their league game against Al-Masry on Wednesday. Mohamed Aboutrika and Mohamed Barakat, who both have at least 70 caps for Egypt, told Al-Ahly TV that they would quit immediately after the mass violence that left at least 74 people dead at a stadium in the Mediterranean city of Port Said. Al-Ahly's soccer team poses for a photo before the start of their match against Al-Masry in the Egyptian coastal city of Port Said on Thursday. At least 74 people died in the clashes. ( AFP / GETTY IMAGES ) “I will not play football again,” Aboutrika said late Wednesday. Barakat told the channel that there would be “no football after today” for him. Emad Moteab also said he will refuse to play until there was “retribution for the people that died,” leaving the door open for an eventual return to the game. Aboutrika and Barakat started the game against Al-Masry, while Moteab was a substitute, and all were among the Al-Ahly players forced to flee the pitch after opposition supporters surged onto the field and clashes broke out. Article Continued Below Aboutrika criticized police and security officials for standing by as Al-Masry supporters, armed with knives, sticks and stones, chased Al-Ahly players and fans, who ran toward the exits and up the stands to escape, according to witnesses. “People here are dying and no one is doing a thing. It’s like a war,” Aboutrika told the team’s TV station. “Is life this cheap?” PHOTOS: Egypt mourns soccer deaths Al-Ahly’s Portuguese coach Manuel Jose has also reportedly asked the Cairo club — Egypt’s most successful ever — to cancel his contract and allow him to return to Portugal, while Al-Masry club president Kamel Abu Ali and coach Hossam Hassan have quit. The Egyptian Football Association suspended all league games indefinitely before Egyptian Prime Minister Kamal el-Ganzouri dissolved the federation’s board on Thursday. While Al-Ahly’s supporters apparently were not the instigators behind Wednesday’s violence, Egypt’s most successful club has a history of violent episodes connected to its matches. Al-Ahly was voted Africa’s club of the century in 2000 and has won a record 36 Egyptian league titles and the African Champions League six times — also a record. Article Continued Below But its renowned ultras — or hardline supporters — have often been involved in fighting with police or fans of other teams, and antiestablishment violence has often been associated with its games. Last year, Al-Ahly was forced by Africa’s football confederation to play games in the continental club competition behind closed doors after trouble with its fans. In September, more than 70 fans and riot police were hurt in clashes that spilled out from a stadium into a Cairo neighbourhood following an Al-Ahly game. It came amid long-standing and bitter animosity between the football supporters and Egyptian security forces after the uprising that toppled Egypt’s former president, Hosni Mubarak, was fueled by anger over police abuse and brutality. On Wednesday in Port Said, security forces were accused of doing nothing to stop the violence against Al-Ahly players, fans and officials. The ultras accused the military council and former members of Mubarak’s regime of retaliating against them for their role in the uprising last year and in anti-military protests since. “They want to punish us and execute us for our participation in the revolution against suppression,” the Ultras of Al-Ahly group said in a statement. Read more about:
Hazardous wastes in academia. As do many industries, colleges and universities encounter thorny problems in dealing with hazardous wastes. Industry and academia alike are saddled with the rising cost of waste management and face perpetual liability for costs of waste cleanup. Unlike many industries, however, colleges and universities generate small amounts of waste, most, but by no means all of which is generated in laboratories; almost every operation contributes a certain amount. The wastes consist of nearly every hazardous chemical listed by EPA, including hydrochloric acid, methanol, polychlorinated biphenyls (PCBs), and newly synthesized compounds of unknown toxicity. Moreover, their composition changes with each new research project and experiment.
// RootURL returns the base URL without path. func (c *Config) RootURL() string { if c.rootURL == "" { u, _ := url.Parse(c.BaseURL()) u.Path = "" c.rootURL = u.String() } return c.rootURL }
from .k_center_greedy import KCenterGreedy from .sampling_def import SamplingMethod __all__ = ["KCenterGreedy", "SamplingMethod"]
Induced Circular Dichroism in Phosphine Gold(I) Aryl Acetylide Urea Complexes through Hydrogen-Bonded Chiral Co-Assemblies. Phosphine gold(I) aryl acetylide complexes equipped with a central bis(urea) moiety form 1D hydrogen-bonded polymeric assemblies in solution that do not display any optical activity. Chiral co-assemblies are formed by simple addition of an enantiopure (metal-free) complementary monomer. Although exhibiting an intrinsically achiral linear geometry, the gold(I) aryl acetylide fragment is located in the chiral environment displayed by the hydrogen-bonded co-assemblies, as demonstrated by induced circular dichroism (ICD).
Abstract A059: Lifestyle and health-related quality of life in men with metastatic prostate cancer Background: Patients with metastatic prostate cancer live with a considerable disease burden that may have a profound impact on physical activity and quality of life. This patient group may survive for many years after disease onset; however, there is little evidence on their habitual levels of physical activity. The aim of this study was to investigate physical activity levels and associated health-related quality of life in prostate cancer patients with bone metastases. Methods: ExPeCT (Exercise, Prostate Cancer and Circulating Tumour Cells: CTRIAL-IE 15-21) (ClincalTrials.gov identifier NCT02453139) is an ongoing multicenter trial examining the effect of a 6-month structured exercise intervention for patients with metastatic prostate cancer. Participants complete questionnaires examining self-reported health-related quality of life (FACT-P), sleep (Pittsburgh Sleep Index), depression (PHQ-9), and physical activity (Harvard Health Professionals Study Questionnaire) at baseline, three, and six months. Analysis of 3- and 6-month data is ongoing. Result: An interim analysis of the baseline outcome measures of 64 patients with bone metastases was completed (mean age 69.4 (SD 7.35) years and mean BMI 29.2 (SD 5.8) kg/m2). Median time since diagnosis was 34 months (IQR 7-54) and 55% (n=35) of participants had >1 region affected by metastatic disease. Preliminary data demonstrated that 38% (n=24) of participants did not meet the current aerobic exercise guidelines for cancer survivors. In total, 20% (n=13) of participants reported engaging in vigorous activity and 16% (n=11) reported completing resistance exercise. There was no correlation found between physical activity levels and quality of life (r=0.01), sleep (r=0.02), or depression (r=-0.15) scores. The majority of participants (61% (n=41)) had sleep scores of >7, indicative of poor sleep quality. Sleep scores correlated negatively with global quality of life (r =-0.55, p Discussion: Findings highlight the association between reduced quality of life and poor sleep quality among men with metastatic prostate cancer. In addition, data suggest a high prevalence of suboptimal physical activity levels in this population. Patients with metastatic disease may benefit from lifestyle interventions that aim to increase physical activity levels. Citation Format: Grainne Sheill, Lauren Brady, Emer Guinan, Juliette Hussey, David Hevey, Tatjana Vlajnic, Orla Casey, Anne-Marie Baird, Fidelma Cahill, Mieke Van Hemelrijck, Nicola Peat, Sarah Rudman, Thomas Lynch, Rustom P. Manecksha, Brian Hayes, Moya Cunningham, Liam Grogan, John McCaffrey, Dearbhaile M. ODonnell, Ray McDermott, John O Leary, Stephen P. Finn. Lifestyle and health-related quality of life in men with metastatic prostate cancer . In: Proceedings of the AACR Special Conference: Prostate Cancer: Advances in Basic, Translational, and Clinical Research; 2017 Dec 2-5; Orlando, Florida. Philadelphia (PA): AACR; Cancer Res 2018;78(16 Suppl):Abstract nr A059.
Antiplasmodial activity of the ethanolic root bark extract of Icacina senegalensis in mice infected by Plasmodium berghei Abstract Background: The root of Icacina senegalensis is used for the treatment of malaria and related conditions in southeastern Nigeria. Methods: To establish its efficacy, the ethanolic root bark extract was investigated as antiplasmodial agent against Plasmodium berghei in mice. A 4-day suppressive test and the curative effect against established infection models of antiplasmodial studies were used. Results: The root bark extract of I. senegalensis (50, 100, and 200 mg/kg) exhibited a significant (p<0.05) dose-dependent activity against the parasite based on suppressive and curative study. The antimalarial effect of I. senegalensis is compared with that of chloroquine (10 mg/kg), the standard drug. The ethanolic root bark extract also prolonged the survival time of infected mice. Conclusions: The results showed that the root bark extract possesses a potential antiplasmodial activity, which can be exploited for the possible development of new antimalarial agent.
/// <reference path="android-declarations.d.ts"/> declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export class BootReceiver { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.BootReceiver >; public constructor(); public static setBootReceiverDelegate( param0: es.uji.geotec.taskdispatcher.BootReceiverDelegate ): void; public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export class BootReceiverDelegate extends es.uji.geotec.taskdispatcher .common.BroadcastReceiverDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.BootReceiverDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.BootReceiverDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; }); public constructor(); public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export class BuildConfig { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.BuildConfig >; public static DEBUG: boolean; public static LIBRARY_PACKAGE_NAME: string; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class AlarmReceiver { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.AlarmReceiver >; public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; public constructor(); public static setAlarmReceiverDelegate( param0: es.uji.geotec.taskdispatcher.alarms.AlarmReceiverDelegate ): void; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class AlarmReceiverDelegate extends es.uji.geotec .taskdispatcher.common.BroadcastReceiverDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.AlarmReceiverDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.alarms.AlarmReceiverDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; }); public constructor(); public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class AlarmRunnerService { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.AlarmRunnerService >; public static setAlarmRunnerServiceDelegate( param0: es.uji.geotec.taskdispatcher.alarms.AlarmRunnerServiceDelegate ): void; public constructor(); public onDestroy(): void; public onCreate(): void; public onBind( param0: globalAndroid.content.Intent ): globalAndroid.os.IBinder; public onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class AlarmRunnerServiceDelegate extends es.uji.geotec .taskdispatcher.common.ServiceDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.AlarmRunnerServiceDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.alarms.AlarmRunnerServiceDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCreate(param0: globalAndroid.app.Service): void; onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; onDestroy(): void; }); public constructor(); public onDestroy(): void; public onCreate(param0: globalAndroid.app.Service): void; public onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class WatchdogReceiver { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.WatchdogReceiver >; public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; public constructor(); public static setWatchdogReceiverDelegate( param0: es.uji.geotec.taskdispatcher.alarms.WatchdogReceiverDelegate ): void; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace alarms { export class WatchdogReceiverDelegate extends es.uji.geotec .taskdispatcher.common.BroadcastReceiverDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.alarms.WatchdogReceiverDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.alarms.WatchdogReceiverDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; }); public constructor(); public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace common { export class BroadcastReceiverDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.common.BroadcastReceiverDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.common.BroadcastReceiverDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; }); public constructor(); public onReceive( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ): void; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace common { export class ReceiverActivationCache { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.common.ReceiverActivationCache >; public constructor( param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent ); public getContext(): globalAndroid.content.Context; public getIntent(): globalAndroid.content.Intent; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace common { export class ServiceActivationCache { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.common.ServiceActivationCache >; public constructor(); public onStartCommandWasEarlyCalled(): boolean; public onStartCommandEarlyCalledHandled(): void; public onCreateWasEarlyCalled(): boolean; public getStartFlags(): number; public onCreateEarlyCalled(param0: globalAndroid.app.Service): void; public getStartIntent(): globalAndroid.content.Intent; public onCreateEarlyCalledHandled(): void; public onStartCommandEarlyCalled( param0: globalAndroid.content.Intent, param1: number, param2: number ): void; public getService(): globalAndroid.app.Service; public getStartId(): number; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace common { export class ServiceDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.common.ServiceDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.common.ServiceDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCreate(param0: globalAndroid.app.Service): void; onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; onDestroy(): void; }); public constructor(); public onDestroy(): void; public onCreate(param0: globalAndroid.app.Service): void; public onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace runners { export class TaskChainRunnerService { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.runners.TaskChainRunnerService >; public constructor(); public onDestroy(): void; public onCreate(): void; public onBind( param0: globalAndroid.content.Intent ): globalAndroid.os.IBinder; public static setTaskChainRunnerServiceDelegate( param0: es.uji.geotec.taskdispatcher.runners.TaskChainRunnerServiceDelegate ): void; public onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; } } } } } } declare namespace es { export namespace uji { export namespace geotec { export namespace taskdispatcher { export namespace runners { export class TaskChainRunnerServiceDelegate extends es.uji.geotec .taskdispatcher.common.ServiceDelegate { public static class: java.lang.Class< es.uji.geotec.taskdispatcher.runners.TaskChainRunnerServiceDelegate >; /** * Constructs a new instance of the es.uji.geotec.taskdispatcher.runners.TaskChainRunnerServiceDelegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onCreate(param0: globalAndroid.app.Service): void; onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; onDestroy(): void; }); public constructor(); public onDestroy(): void; public onCreate(param0: globalAndroid.app.Service): void; public onStartCommand( param0: globalAndroid.content.Intent, param1: number, param2: number ): number; } } } } } } // Generics information:
<filename>modules/moisture_reducing/local_module.py # -*- coding: utf8 -*- import module from module import use_module import fields class MoistureReducing(module.Base): public_name = 'Humidite automatique' fan_actuator = use_module('FanActuator') moisture_sensor = use_module('MoistureSensor') moisture = fields.proxy.readable('moisture', 'MoistureSensor', 'sensor') fan = fields.proxy.readable('fan', 'FanActuator', 'fan') class moisture_value_limit(fields.syntax.Percentage, fields.io.Writable, fields.io.Readable, fields.syntax.Numeric, fields.persistant.Volatile, fields.Base): update_rate = 421337 public_name = 'Humidité maximale autorisée' init_value = 45.0 class controller(fields.Base): update_rate = 15 # update for half the sensor's time def always(self): logger = self.module.logger moisture_value = self.module.moisture_sensor.sensor()[1] moisture_value_limit = self.module.moisture_value_limit()[1] if moisture_value is None: return if moisture_value > moisture_value_limit: self.module.fan_actuator.fan(True) logger.info('moisture (%s %%) over limit (%s %%), running fan', moisture_value, moisture_value_limit) else: self.module.fan_actuator.fan(False) logger.info('moisture (%s %%) under limit (%s %%), stopping fan', moisture_value, moisture_value_limit)
Should They Stay or Should They Go: Applying the Forum Non Conveniens Doctrine to Foreign Plaintiffs Injured Abroad in Abad v. Bayer Corporation As globalization continues to make it easier for U.S. companies to export their products abroad, a defective product can cause lifethreatening harm to consumers throughout the world. For example, when U.S. drug companies exported defective blood clotting products to hemophiliacs worldwide, reports of hemophiliacs infected with Human Immunodeficiency Virus (HIV) arose in France, Japan, Iran, Canada, and Portugal, among other countries. When the product of a U.S. company injures a consumer outside of U.S. borders, the foreign plaintiff must choose the forum in which to bring suit. Historically, U.S. courts have been an attractive forum for foreign plaintiffs,
from ltypes import i32 def f(): i: i32 i = 5 res: i32 res = ~i assert res == -6 i = -235346 assert ~i == 235345 f()
Adaptation Trajectories of Dismissed Workers: A Critical Case Study of the Lithuanian Radio-Electronics Sector This article explores why some dismissed workers adapt successfully to the changing structure of an economy, while others remain trapped in low-quality jobs and experience deskilling. The associated case study relies on in-depth, semi-structured interviews with 50 former employees of four bankrupt radio-electronics factories in Lithuania. It is found that workers with inherited skills that are deep and technical are able to enter high-quality jobs when new firms emerge, recombining the physical, financial and human assets of destitute factories for new productive uses. However, if such economic opportunities are scarce, workers with inherited broad skill sets are relatively more successful in transitioning to services from manufacturing. Further, in line with the literature of the sociology of work, women and older workers are found to face more acute challenges in adapting to the economic shock associated with dismissal.
<reponame>adambrgmn/wp-bundler<gh_stars>1-10 import ts from 'typescript'; import { TranslationMessage } from './types'; import { isTranslatorsComment, trimComment, tsNodeToLocation } from './utils'; export function mightHaveTranslations(source: string): boolean { return source.includes('wp.i18n') || source.includes('@wordpress/i18n'); } export function extractTranslations(source: string, filename: string): TranslationMessage[] { let sourceFile = ts.createSourceFile('admin.ts', source, ts.ScriptTarget.ES2015, true, ts.ScriptKind.TSX); let relevantImports = findRelevantImports(sourceFile); let messages = findTranslatableMessages(sourceFile, relevantImports, { source, filename }); return messages; } const translatableMethods = ['_n', '_nx', '_x', '__'] as const; type TranslatableMethod = typeof translatableMethods[number]; const isTranslatableMethod = (name: any): name is TranslatableMethod => { return translatableMethods.includes(name); }; /** * Extract imported identifiers from a ts file. It will find default imports, * namespaced imports and named imports from '@wordpress/i18n'. * * @param sourceFile Source file to check for imports * @returns Array of imported identifiers */ function findRelevantImports(sourceFile: ts.SourceFile): ts.Identifier[] { let identifiers: ts.Identifier[] = []; visitAll(sourceFile, (node) => { if (ts.isImportDeclaration(node)) { if (node.moduleSpecifier.getText(sourceFile).includes('@wordpress/i18n')) { let clause = node.importClause?.name ?? node.importClause?.namedBindings; if (clause != null) { switch (clause.kind) { // Default import case ts.SyntaxKind.Identifier: identifiers.push(clause); break; // Namespace import (* as i18n) case ts.SyntaxKind.NamespaceImport: identifiers.push(clause.name); break; // Named import ({ __, _x }) case ts.SyntaxKind.NamedImports: let relevant = getRelevantNamedImports(clause); identifiers.push(...relevant); break; } } } return false; } }); return identifiers; } /** * Extract all translatable data from within a file. Based on the imported * variables. It will also find calls to `[window.]wp.i18n`. * * @param sourceFile Source file to traverse and search witin * @param imports Relevant imported variables to look for * @returns An array of translation messages */ function findTranslatableMessages( sourceFile: ts.SourceFile, imports: ts.Identifier[], locationMeta: { source: string; filename: string }, ) { let messages: TranslationMessage[] = []; let referencesImport = (expression: { getText(): string }) => { return imports.findIndex((imported) => imported.getText() === expression.getText()) > -1; }; let lastTranslators: string | undefined = undefined; visitAll(sourceFile, (node) => { let message: TranslationMessage | null = null; let translators = getTranslatorComment(node, locationMeta.source); if (translators) lastTranslators = translators; if (!ts.isCallExpression(node)) return; // __(...) if (ts.isIdentifier(node.expression) && referencesImport(node.expression)) { message = extractMessage(node.expression, node.arguments, imports, locationMeta); } // i18n.__(...) if (ts.isPropertyAccessExpression(node.expression) && referencesImport(node.expression.expression)) { message = extractMessage(node.expression.name, node.arguments, null, locationMeta); } // wp.i18n.__(...) || window.wp.i18n.__(...) if ( ts.isPropertyAccessExpression(node.expression) && (node.expression.expression.getText() === 'window.wp.i18n' || node.expression.expression.getText() === 'wp.i18n') ) { message = extractMessage(node.expression.name, node.arguments, null, locationMeta); } if (message != null) { message.translators = lastTranslators; lastTranslators = undefined; messages.push(message); return false; } }); return messages; } /** * Extract translation data from a caller. * * @param caller Caller variable * @param args Arguments passed to caller * @returns A compiled message */ function extractMessage( caller: ts.LeftHandSideExpression | ts.MemberName, args: ts.NodeArray<ts.Expression>, imports: ts.Identifier[] | null, { source, filename }: { source: string; filename: string }, ): TranslationMessage | null { let id = caller.getText(); /** * This lookup is looking to see if the caller variable is a reference to a * named import, an import which was renamed (`import { __ as translate }`). * We have previously identified that import, that's why it ends up here. * And by looking at the imported variable we can find the "real" method that * it references. */ if (Array.isArray(imports) && !isTranslatableMethod(id)) { let importVar = imports.find((imported) => imported.getText() === id); let parent = importVar?.parent; if (parent == null || !ts.isImportSpecifier(parent)) return null; id = parent.propertyName?.getText() ?? parent.name.getText(); } if (!isTranslatableMethod(id)) return null; let location = tsNodeToLocation(caller, id, source, filename); switch (id) { case '_n': return { location, single: getStringValue(args[0]), plural: getStringValue(args[1]), domain: args[3] ? getStringValue(args[3]) : undefined, }; case '_nx': return { location, single: getStringValue(args[0]), plural: getStringValue(args[1]), context: getStringValue(args[3]), domain: args[4] ? getStringValue(args[4]) : undefined, }; case '__': return { location, text: getStringValue(args[0]), domain: args[1] ? getStringValue(args[1]) : undefined, }; case '_x': return { location, text: getStringValue(args[0]), context: getStringValue(args[1]), domain: args[2] ? getStringValue(args[2]) : undefined, }; } } /** * Extract all relevant imports from a named imports declaration. It will also * look for aliased imports (`import { __ as translate }`) and push those to the * relevant array. * * @param clause Named imports node */ function getRelevantNamedImports(clause: ts.NamedImports): ts.Identifier[] { let relevant: ts.Identifier[] = []; for (let specifier of clause.elements) { if (isTranslatableMethod(specifier.propertyName?.getText() ?? specifier.name.getText())) { relevant.push(specifier.name); } } return relevant; } /** * A function to traverse all children within a source file. * * @param source The source file to visit node within * @param callback A callback fired on each node. Return `false` to prevent going deeper. */ function visitAll(source: ts.SourceFile, callback: (node: ts.Node) => boolean | undefined | null | void) { function visit(node: ts.Node) { let shouldContinue = callback(node); if (shouldContinue !== false) { node.getChildren(source).forEach(visit); } } visit(source); } /** * Extract the string representation of a string literal (or string like * literal). * * @param expression String literal expression * @returns String representation of the expression, or throws an error if it is not a StringLiteral */ function getStringValue(expression: ts.Expression): string { if (ts.isStringLiteral(expression) || ts.isStringLiteralLike(expression)) { return expression.text; } throw new Error('Given expression is not a string literal.'); } function getTranslatorComment(node: ts.Node, source: string): string | undefined { let comments = ts.getLeadingCommentRanges(source, node.pos); if (Array.isArray(comments)) { for (let commentNode of comments) { let comment = trimComment(source.substring(commentNode.pos, commentNode.end)); if (isTranslatorsComment(comment)) return comment; } } return undefined; }
Chromatographic competitive binding immunoassays: a comparison of the sequential and simultaneous injection methods. Two approaches for performing competitive binding immunoassays by HPLC and other flow-based systems are the simultaneous and sequential injection methods. Both these techniques make use of a column with a limited amount of antibody, onto which is injected a sample and a fixed amount of a labeled analyte analog. An indirect measure of the unlabeled analyte in the sample is then obtained by looking at the amount of analog in either the nonretained or retained peaks. In the simultaneous injection mode, the sample and labeled analog are applied at the same time to the column, while in the sequential mode the sample is injected first, followed by the analog. This results in a difference in the analytical characteristics of these two approaches. This study used chromatographic theory and previous data obtained for injections of human serum albumin (HSA) onto an anti-HSA antibody column to compare the response, detection limits, range, and sensitivity of these methods. Under equivalent conditions, it was found that the sequential method always provided the best lower limit of detection and sensitivity. However, the simultaneous mode had a broader dynamic range and higher upper limit of detection. From these observations, several guidelines were developed regarding the use and selection of such assays for new applications.
def flip_string(string): i = 0 reverse_string = '' string_length = len(string) while i < string_length: reverse_string += string[string_length-i-1] i += 1 return reverse_string
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticbeanstalk.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The application version lifecycle settings for an application. Defines the rules that Elastic Beanstalk applies to an * application's versions in order to avoid hitting the per-region limit for application versions. * </p> * <p> * When Elastic Beanstalk deletes an application version from its database, you can no longer deploy that version to an * environment. The source bundle remains in S3 unless you configure the rule to delete it. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/ApplicationVersionLifecycleConfig" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ApplicationVersionLifecycleConfig implements Serializable, Cloneable { /** * <p> * Specify a max count rule to restrict the number of application versions that are retained for an application. * </p> */ private MaxCountRule maxCountRule; /** * <p> * Specify a max age rule to restrict the length of time that application versions are retained for an application. * </p> */ private MaxAgeRule maxAgeRule; /** * <p> * Specify a max count rule to restrict the number of application versions that are retained for an application. * </p> * * @param maxCountRule * Specify a max count rule to restrict the number of application versions that are retained for an * application. */ public void setMaxCountRule(MaxCountRule maxCountRule) { this.maxCountRule = maxCountRule; } /** * <p> * Specify a max count rule to restrict the number of application versions that are retained for an application. * </p> * * @return Specify a max count rule to restrict the number of application versions that are retained for an * application. */ public MaxCountRule getMaxCountRule() { return this.maxCountRule; } /** * <p> * Specify a max count rule to restrict the number of application versions that are retained for an application. * </p> * * @param maxCountRule * Specify a max count rule to restrict the number of application versions that are retained for an * application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationVersionLifecycleConfig withMaxCountRule(MaxCountRule maxCountRule) { setMaxCountRule(maxCountRule); return this; } /** * <p> * Specify a max age rule to restrict the length of time that application versions are retained for an application. * </p> * * @param maxAgeRule * Specify a max age rule to restrict the length of time that application versions are retained for an * application. */ public void setMaxAgeRule(MaxAgeRule maxAgeRule) { this.maxAgeRule = maxAgeRule; } /** * <p> * Specify a max age rule to restrict the length of time that application versions are retained for an application. * </p> * * @return Specify a max age rule to restrict the length of time that application versions are retained for an * application. */ public MaxAgeRule getMaxAgeRule() { return this.maxAgeRule; } /** * <p> * Specify a max age rule to restrict the length of time that application versions are retained for an application. * </p> * * @param maxAgeRule * Specify a max age rule to restrict the length of time that application versions are retained for an * application. * @return Returns a reference to this object so that method calls can be chained together. */ public ApplicationVersionLifecycleConfig withMaxAgeRule(MaxAgeRule maxAgeRule) { setMaxAgeRule(maxAgeRule); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getMaxCountRule() != null) sb.append("MaxCountRule: ").append(getMaxCountRule()).append(","); if (getMaxAgeRule() != null) sb.append("MaxAgeRule: ").append(getMaxAgeRule()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ApplicationVersionLifecycleConfig == false) return false; ApplicationVersionLifecycleConfig other = (ApplicationVersionLifecycleConfig) obj; if (other.getMaxCountRule() == null ^ this.getMaxCountRule() == null) return false; if (other.getMaxCountRule() != null && other.getMaxCountRule().equals(this.getMaxCountRule()) == false) return false; if (other.getMaxAgeRule() == null ^ this.getMaxAgeRule() == null) return false; if (other.getMaxAgeRule() != null && other.getMaxAgeRule().equals(this.getMaxAgeRule()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMaxCountRule() == null) ? 0 : getMaxCountRule().hashCode()); hashCode = prime * hashCode + ((getMaxAgeRule() == null) ? 0 : getMaxAgeRule().hashCode()); return hashCode; } @Override public ApplicationVersionLifecycleConfig clone() { try { return (ApplicationVersionLifecycleConfig) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
The London Lightning are 38 games into their National Basketball League of Canada season and no one is quite sure who the Lightning are. The Lightning better find out in a hurrym because after finishing their season against the Orangeville A’s Friday in Orangeville and at home against the Windsor Express on Saturday, they roll into the best-of-five Central Division playoffs against the A’s May 2 and 4 at Budweiser Gardens. The Lightning clinched first place in the Central on Friday when the Express lost to Saint John. Meanwhile, the Lightning were losing to the A’s. Saturday in St. Catharines, the Lightning looked headed to another loss against the Niagara River Lions before hell and damnation turned into heaven and redemption. Trailing by 21 at one point in the second quarter and by 15 in the fourth, the Lightning came back to beat the River Lions 125-124 in a comeback that is still leaving the River Lions wondering how they managed to let that game get away from them. The game was classic Lightning. The first 20 minutes, the Lightning were present in an earthly form, but played like a shell vacuumed of all skill and intensity. Cocah Kyle Julius tried everything, but nothing worked. His team was so out of sorts that when Stephen Maxwell opted to keep the ball on a three-on-one going down the middle and was called for a charging foul on River Lion Sammy Zeglinski with the two other players open, Julius realized it was going to be a long night. Whether it was a foul call or not was secondary to the Lightning needing some sort of resuscitation. Julius let the referee get to the scorer’s table and blasted him. Within three seconds, Julius had two technical fouls and was tossed from the game with eight minutes left in the second quarter. Assistant coach Stu Julius took over and after going down by 21 points with the foul shots, the game took a different direction. The ejection energized the Lightning. They scored 71 points in the second half and came back to stun the River Lions. Julius wasn’t admitting to getting tossed deliberately as a last ditch effort to shake up his club. But . . . It wasn’t like the Lightning only had to come back once. They drew to within five points in the third quarter only to let the River Lions get back to a 15-point lead. The Lightning then cut it to three points in the fourth only to have the lead extended again to 14. On this day though, the Lightning never quit and simply wore down the River Lions. The Lightning comeback was only accomplished because big plays were made by several players. Akeem Scott had a big night missing a triple-double by one rebound. Scott had 26 points, 10 assists and nine rebounds. Nick Okorie hit for 18 points while Maxwell had 16 points and 10 rebounds, Akeem Wright 16 and nine and Ryan Anderson had 15 points. Wright made a last second block to preserve the victory. B. J. Monteiro was other-worldly for the River Lions. He had 44 points and 11 rebounds while Travis Releford had 22 points. The bad news is in two weekend games the Lightning gave up an average of 129 points. No team is going to win a championship giving up 129 points. Consistency remains the other issue especially in a short series. If you get behind in the playoffs it’s much more difficult to make it back. It’s the second time this month the Lightning have come back from 20-points down to win and Julius hopes his team reads the message correctly. It’s not about coming back to win.
<reponame>JavaFamilyClub/jfoa /* * Copyright (c) 2020, JavaFamily Technology Corp, All Rights Reserved. * * The software and information contained herein are copyrighted and * proprietary to JavaFamily Technology Corp. This software is furnished * pursuant to a written license agreement and may be used, copied, * transmitted, and stored only in accordance with the terms of such * license and with the inclusion of the above copyright notice. Please * refer to the file "COPYRIGHT" for further copyright and licensing * information. This software and information or any other copies * thereof may not be provided or otherwise made available to any other * person. */ package club.javafamily.runner.admin; import club.javafamily.runner.web.portal.service.SubjectVoteService; import org.springframework.jmx.export.annotation.*; import org.springframework.stereotype.Component; import java.util.*; /** * Subject Request Vote's MBean */ @Component @ManagedResource public class SubjectVoteMBean { public SubjectVoteMBean(SubjectVoteService voteService) { this.voteService = voteService; } @ManagedOperation(description = "Sync subject request vote from redis to db") public Map<String, Object> syncCachedToDb() { Map<String, Object> result = new HashMap<>(); voteService.syncCachedVoteToDb(result); return result; } @ManagedOperation(description = "Remove all cached subject request vote cached") public void destroyCachedVoteCount() { voteService.deleteAllCachedVoteCount(); } @ManagedAttribute(description = "Cached subject request vote count redis keys") public Set<String> getCachedVoteCountKeys() { return voteService.countKeys(); } @ManagedAttribute(description = "Cached subject request vote count ids") public Set<Integer> getCachedVoteCountIds() { return voteService.countIds(); } private final SubjectVoteService voteService; }
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: TraversingBinaryTree.py # @Author: olenji - <EMAIL> # @Description: # @Create: 2019-06-18 20:04 # @Last Modified: 2019-06-18 20:04 class TraversingBinaryTree: def __init__(self): self._list = [None] def __str__(self): return str(self._list) def append(self, value): self._list.append(value) def pre_traversing(self): i = 1 yield from self._ccc(i) def _pre(self, i): yield self._list[i] left = i * 2 try: if self._list[left] is not None: yield from self._pre(left) except IndexError: pass right = i * 2 + 1 try: if self._list[right] is not None: yield from self._pre(right) except IndexError: pass def in_traversing(self): yield from self._bbb(1) def _in(self, i): left = i * 2 try: if self._list[left] is not None: yield from self._in(left) except IndexError: pass yield self._list[i] right = i * 2 + 1 try: if self._list[right] is not None: yield from self._in(right) except IndexError: pass def post_traversing(self): yield from self._ddd(1) def _post(self, i): left = i * 2 try: if self._list[left] is not None: yield from self._post(left) except IndexError: pass right = i * 2 + 1 try: if self._list[right] is not None: yield from self._post(right) except IndexError: pass yield self._list[i] if __name__ == "__main__": tree = TraversingBinaryTree() for i in 'ABCDEFG': tree.append(i) print(tree) print('pre') for i in tree.pre_traversing(): print(i, end=' ') print('\nmid') for i in tree.in_traversing(): print(i, end=' ') print('\nlast') for i in tree.post_traversing(): print(i, end=' ')
The Pittsburgh Steelers have been fortunate over the past ten seasons to have a franchise quarterback that has kept them competitive, never finishing a season below 8-8, and always staying in the hunt for the playoffs. Unfortunately, all good things must come to an end, and eventually, the magic that Ben Roethlisberger has brought to the Steelers and to the city of Pittsburgh will end. And when that day comes, the Steelers had better be prepared. Most Steelers fans remember the period of dreadful quarterback play that existed in between the careers of Terry Bradshaw and Roethlisberger, and it was an epoch characterized by mediocre teams on the outside looking in at the playoffs, or when the overall team was good enough to make the playoffs, average quarterback play doomed the Steelers in the end. In a league that is dominated by elite quarterbacks, look no further than Sunday’s AFC Championship contest between Tom Brady and Peyton Manning, not having one is the difference between being a contender and a one-and-done. Without Roethlisberger, the Steelers would be an average, if not a below-average team, and the organization would be wise to prepare for his departure in advance. In other words, the Steelers should have a succession plan. Having a succession plan would be a proactive effort to ensure solid quarterback play to avoid a decline in play at the position. And while it doesn’t guarantee success, it is a strategic and smart attempt to avoid a backslide. And there is nothing to lose. If it works out, you’re a genius, if it doesn’t, the search for Roethlisberger’s replacement continues. The most recognized example of succession planning in the NFL is the Green Bay Packers and Aaron Rodgers. While Brett Favre still had life in his game, the Packers drafted Rodgers 24th overall in the first round in 2005, and it paid off as Rodgers watched and learned the ropes for three years and then stepped in to become one of the best quarterbacks in the game, including winning a Super Bowl in his sixth year. Roethlisberger still has five good years left, excluding a significant injury, and in three years, maybe even two, the Steelers would be wise to draft a potential successor. That would allow the new prospect the appropriate time to develop and become the QB of the Steelers future. The quarterback position is too important to leave to chance, and as the league evolves, I expect more and more teams with franchise quarterbacks to utilize such an approach moving forward. While it may not always work out as expected because of the erratic nature of the draft, it is an intelligent approach to building for the future of a team. It will be a sad, sad day when Ben plays his last down in a black and gold uniform, but having a young apprentice to graciously take the reins from the Pittsburgh legend can make the loss easier to manage.
/** * EAGER mode: required LAZY mode: N/A MANUAL mode: N/A Domain scheduled * for eager auto provision on this server. Scheduled domains must have * EAGER mode enabled in zimbraAutoProvMode. Multiple domains can be * scheduled on a server for EAGER auto provision. Also, a domain can be * scheduled on multiple servers for EAGER auto provision. * * @param zimbraAutoProvScheduledDomains new to add to existing values * @throws com.zimbra.common.service.ServiceException if error during update * * @since ZCS 8.0.0 */ @ZAttr(id=1237) public void addAutoProvScheduledDomains(String zimbraAutoProvScheduledDomains) throws com.zimbra.common.service.ServiceException { HashMap<String,Object> attrs = new HashMap<String,Object>(); StringUtil.addToMultiMap(attrs, "+" + Provisioning.A_zimbraAutoProvScheduledDomains, zimbraAutoProvScheduledDomains); getProvisioning().modifyAttrs(this, attrs); }
Immune factor and infertility. Infertility is a common problem seen in gynaecological practice. In a significant number of cases of infertility an immune factor may be operative. In our study of 200 cases, the presence of sperm antibodies was studied in sera of both males and females. The tests used were the gelatin and tube slide agglutination tests. In the infertile group with unexplained infertility (50 couples), 16% of males and 30% of females were positive by the gelatin agglutination test, and 18% of males and 30% of females were positive by the tube slide agglutination test. There was complete absence of positive test (by both methods) in male controls, but females had positive tests for antibodies by both methods in significant numbers.
When England’s most eligible bachelor heard that the “Harry Potter” star had split up with Oxford University rugby player Matthew Janney last year he sent her an email inviting her out, telling her he’d like to get to know her. The two went out on a big group date and hit it off, insiders say. “He’s smitten – and it’s more than Emma’s looks,” says one source. Just the mere thought of the two lovely people being a couple has royal watchers jumping for joy. “Watson and Harry might just be the best celebrity pairing since, well, ever,” opined Rachel Simon at Bustle.com on Friday. “Sure, it’s just a rumor, and yeah, there’s a big chance the extremely private Watson would never go for someone so famous, but still: can you imagine?! “The combination of their British accents, their bonding over unusual upbringings, the drop-dead gorgeous dress she’ll wear to the royal wedding — sorry, am I getting ahead of myself?
<gh_stars>1-10 const PORT:string = '8080'; const URI:string = `http://digi-planner-tool-digi-planner-tool.apps.192.168.127.12.nip.io`; //const clientId:string='610664320073-4ik734pbbflijv056jr130n5k6e7ia8q.apps.googleusercontent.com'; const clientId:string = '610664320073-4oui7dgr99meb3n28m5ljp25f65fmf79.apps.googleusercontent.com'; export {URI,clientId};
package me.legit.api.auth.guest; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthException; import com.google.firebase.auth.FirebaseToken; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import io.javalin.http.Context; import io.javalin.http.Handler; import io.sentry.Sentry; import io.sentry.event.BreadcrumbBuilder; import me.legit.APICore; import okhttp3.*; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class LoginByToken implements Handler { private static OkHttpClient client = new OkHttpClient.Builder().build(); public LoginByToken() { } @Override public void handle(@NotNull Context ctx) throws Exception { String token = ctx.header("Authorization").split("Bearer ")[1]; JSONObject object = new JSONObject(); object.put("token", token); object.put("returnSecureToken", true); RequestBody body = RequestBody.create(MediaType.parse("application/json"), object.toString()); String apiKey = "AIzaSyAEbxc1jwhD7tKL4V_oeDsTCH0Ees3DIng"; Request fetchLoginToken = new Request.Builder() .url("https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=" + apiKey) .post(body) .build(); ctx.contentType("application/json"); CompletableFuture<String> resultFuture = new CompletableFuture<>(); client.newCall(fetchLoginToken).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { APICore.getLogger().severe("An error occurred while attempting to fetch login token for a user! - " + "Call: " + call.request().toString()); Sentry.getContext().recordBreadcrumb( new BreadcrumbBuilder() .withData("clientCall", call.request().toString()) .build() ); e.printStackTrace(); Sentry.capture(e); ctx.status(500); resultFuture.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { String ltrBody = responseBody.string(); if (!response.isSuccessful()) { APICore.getLogger().severe("An error occurred while attempting to fetch login token for a user! - " + "Code: " + response.code() + " - Body: " + ltrBody); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(ltrBody); JsonObject errorObject = element.getAsJsonObject().getAsJsonObject("error"); if (errorObject != null) { Sentry.getContext().recordBreadcrumb( new BreadcrumbBuilder() .withData("code", String.valueOf(response.code())) .withData("body", ltrBody) .withData("errorObj", errorObject.toString()) .build() ); int code = errorObject.get("code").getAsInt(); Sentry.capture("An error occurred while attempting to fetch login token for a user!"); ctx.status(code); resultFuture.complete(returnErrorObject(errorObject).toString()); } else { Sentry.getContext().recordBreadcrumb( new BreadcrumbBuilder() .withData("code", String.valueOf(response.code())) .withData("body", ltrBody) .withData("errorObj", "Unknown") .build() ); Sentry.capture("An error occurred while attempting to fetch login token for a user!"); ctx.status(response.code()); resultFuture.complete(new JSONObject().put("status", response.code()).put("message", "An unknown error occurred while attempting to fetch a login token.").toString()); } } else { APICore.getLogger().info(ltrBody); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(ltrBody); JsonObject tokenObject = element.getAsJsonObject(); String accessToken = tokenObject.get("idToken").getAsString(); String refreshToken = tokenObject.get("refreshToken").getAsString(); try { FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(accessToken).get(); APICore.getLogger().info("Successfully decoded and verified login token for user: " + decodedToken.getUid()); JSONObject success = new JSONObject(); success.put("success", true); success.put("access_token", accessToken); success.put("refresh_token", refreshToken); success.put("uid", decodedToken.getUid()); resultFuture.complete(success.toString()); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseAuthException) { FirebaseAuthException authError = (FirebaseAuthException) e.getCause(); //TODO properly implement this #2 JSONObject authErrorObj = new JSONObject(); authErrorObj.put("error", 500); authErrorObj.put("type", authError.getErrorCode()); authErrorObj.put("message", "An error occurred while attempting to verify login token."); e.printStackTrace(); Sentry.getContext().addExtra("halted", true); Sentry.getContext().addExtra("errorObj", authErrorObj.toString()); Sentry.capture(e); ctx.status(500); resultFuture.complete(authErrorObj.toString()); } } catch (InterruptedException ex) { APICore.getLogger().severe("An error was thrown while attempting to verify ID token for a user (failed to resolve future)!"); ex.printStackTrace(); Sentry.capture(ex); ctx.status(500); resultFuture.completeExceptionally(ex); } } } } }); ctx.result(resultFuture); } private static JSONObject returnErrorObject(JsonObject object) { int code = object.get("code").getAsInt(); String message = object.get("message").getAsString(); JSONObject errorObject = new JSONObject(); errorObject.put("error", code); errorObject.put("type", message); errorObject.put("message", "An error occurred while attempting to login by token."); return errorObject; } }