content
stringlengths
10
4.9M
<filename>python_analysis/transiet_event_processing/cc_clustering.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 9 01:59:15 2019 @author: bolelang Using conneceted components to identify event clusters """ import scipy as sp import numpy as np array_x = np.random.uniform(0.0, 100, 35) array_y = np.random.uniform(0.0, 100, 35) print(array_x) print(array_y) for i in range
Visual prey categorization by a generalist jumping spider Abstract The majority of jumping spiders are visual hunters that capture a wide range of prey. While they are known to use specific predatory techniques against different prey, their prey identification mechanisms are poorly understood. A generalist jumping spider, Yllenus arenarius, employs different predatory techniques to capture prey with two different escape potentials. The aim of the present study was to identify the characteristics used by the spider to classify prey into one of these categories. Freshly-emerged spiderlings were used in the experiments to analyse pre-programmed visual predatory preferences. The spiders were presented with: a) their natural prey with different escape potentials (flies, thrips, caterpillars) and b) video images constructed from different combinations of features of their natural prey. The images varied with regard to five characteristics: body length (short vs long images), the presence or absence of details (0 or 4 details, including head spot, antennae, legs, wings), the local motion of legs (moving vs still), the type of global motion (crawling vs non-crawling) and the direction of global motion (horizontal motion vs vertical small scale jumps). Prey-specific behaviours indicated which characteristics were used by the spider to ascertain the prey’s escape potentials. Our findings indicate that during visual prey categorization, Y. arenarius can rely solely on general prey characteristics, such as body proportions and the type of prey motion, while ignoring other stimuli, such as the presence of details and the local motion of legs. This mechanism of prey identification, based on these two easily-recognizable prey characteristics, enables fairly quick and precise categorization of a wide range of prey according to their escape potentials. The study shows how generalist jumping spiders can categorize their diverse prey into a limited number of groups and discusses the presence of the mechanism in other jumping spiders and other animals. Introduction It is believed that animals are able to recognise objects by perceiving their physical characteristics and by assigning certain semantic features to perceived objects. This process enables them to classify the objects to categories, such as predators, prey, mates, others and distinguish between them. The study of visual object recognition has a long tradition going back to the early twentieth century and the competing theoretical frameworks of Gestalt Psychology, originating in the work of Max Wertheimer, and the structuralism of Wilhelm Wundt (Wagemans et al. 2012). The discussion has since evolved to include two concepts: global and local processing. The former postulates that all the elements of an object must be perceived to recognize it, while the latter assuming that only certain key elements need to be identified (Kimchi 1992;Förster & Higgins 2005). These hypotheses can be tested by establishing the cues used in visual identification. This has been widely performed in higher vertebrates, such as birds and mammals, as well as humans (Kourtzi & Connor 2011;Soto & Wasserman 2014), but computationally-limited animals, such as invertebrates and lower vertebrates, have been highly understudied (Enns 2004). Nevertheless, visual object recognition has been studied in toads and frogs (Ingle 1983;Ewert 2004), mantids (Kral & Prete 2004), cuttlefish (Darmaillacq et al. 2004) and jumping spiders (Forster 1985;Bednarski et al. 2012;Jackson & Nelson 2012;Nelson & Jackson 2012a,b;Dolev & Nelson 2014;. In toads and praying mantids, most studies have examined the characteristics used to distinguish prey from non-prey. It was found that the key features appear to be the movement and the shape of the object. Toads primarily rely on the motion of an object, its size and its length-to-width ratio in relation to the direction of movement (Wachowitz & Ewert 1996;Ewert 2004), while praying mantids look for the size of a compact stimulus, the length of the leading edge of an elongated stimulus, its contrast with the background, location of the stimulus in the visual field and the speed of the stimulus (Prete 1992a;b, 1993;Prete & Mahaffey 1993;Prete & McLean 1996Kral & Prete 2004). The experiments with toads and mantids provided an insight into the characteristics used during prey identification by generalist predators. These findings have been extended by other studies on jumping spiders that have shown how highly specialized predators, such as Portia spp. and Evarcha culicivora, identify their prey. Portia, a jumping spider that specializes in capturing other jumping spiders, uses its principal eyes as a major cue characteristic to distinguish between its preferred prey and other objects (Harland & Jackson 2000, 2002. In addition, E. culicivora uses female mosquito-specific cues to feed on blood-filled Anopheles mosquitoes; these clues include its characteristic resting posture, the blood-fed abdomen, and the thorax, head and the antennae of the mosquito Nelson & Jackson 2006. Interestingly, not only can an abstract stick figure be used to fool the spider into recognising an Anopheles mosquito, but also a figure composed of disarranged and disconnected elements (Dolev & Nelson 2014). Highly-specialized jumping spiders, such as Portia and Evarcha culicivora, were tested with stationary objects, which corresponds to the scenes these spiders often encounter in natural circumstances. Such identification and categorization of stationary objects based on configurational cues, a highly-demanding visual task initially attributed only to highlyspecialized spiders, has recently been found to also occur in nonspecialized euryphagous salticids, such as Salticus scenicus; this common jumping spider was found to be able to detect, recognize and appropriately respond to static predators (other jumping spiders) using salticid principal eyes as a major cue (Rößler et al. 2022). In addition, motion patterns have also been found to play a part in object identification, in invertebrates: Menemerus semilimbatus was reported to be able to distinguish biological motion from nonbiological motion (De Agrò et al. 2021). It has been suggested that motion pattern may be used by a number of jumping spiders (Edwards & Jackson 1993, 1994Bartos 2008;Bartos & Szczepko 2012), and this has been supported by experiments based on animations of modified prey with different motion patterns. As such, prey locomotion type has been added to the list of possible cues used in object recognition by jumping spiders (Nelson & Card 2016, Shamble et al. 2017. These elegant studies have revealed that jumping spiders can be extremely discerning predators (Jackson & Pollard 1996;Harland & Jackson 2004;Nelson & Jackson 2012a); however, both Portia and E. culicivora, being highly-specialized oligophagous predators, are rather atypical of the majority of Salticidae, the most diverse spider family with over 6400 species and 662 genera (World Spider Catalog 2022), which seems to consist mainly of euryphagous species. Most jumping spiders capture a diverse range of prey, often using prey-specific techniques. Evidence suggests that these spiders seek a wide range of prey, categorizing them into different groups based on prey-specific characteristics. Moreover, it has been reported that some prey capable of efficient escape, such as flies, leafhoppers and grasshoppers, are captured in a similar manner by various salticids (Forster 1977(Forster , 1982Freed 1984;Jackson 1988a;Richman & Jackson 1992;Edwards & Jackson 1993, 1994Li et al. 1996;Bear & Hasson 1997Bartos 2002;Nelson et al. 2005Nelson et al. , 2007, suggesting that at least some generalist jumping spiders use common characteristics during prey identification. However, the wide morphological diversity demonstrated by the prey, such as the presence of wings and antennae, the appearance of legs, and their sizes, shapes and colours, beg the question of how they can be recognised by the spiders. The study has three key aims. It examines whether a generalist visual predator capturing a wide range of diverse prey can 1) identify an object as prey based on simplified visual information (body outline with certain proportions of length to width devoid of any details (head spot, antennae, legs, wings) and natural forward movement; 2) use simplified information to discriminate between prey with high or low escape potentials (short vs long body, crawling vs non-crawling motion); 3) use prey details enhanced by the motion of legs in discrimination and categorization. In addition, the study aims to confirm whether virtual prey images are accepted by the spiders as equivalents of the Visual prey categorization by a jumping spider natural prey; this was tested using highly-simplified images based on natural prey. Jumping spiders are highly visual animals that depend on their exceptional eyesight during predation (Nelson & Jackson 2011), as well as communication with conspecifics (Forster 1982;Uhl & Elias 2011), locomotion and other activities (Jakob et al. 2011). Their modular visual system consists of eight simple eyes spaced around the carapace, which provide a combined visual field of about 360°. Six pairs of small "secondary eyes" positioned along the sides of the carapace have wide visual fields, but relatively low resolution (Land & Nilsson 2001;Zurek et al. 2010), while a pair of large forward-facing "principal eyes" has very high spatial resolution and enables these spiders to discern even very small image details (Williams & McIntyre 1980;Harland et al. 2012), perceive colours (Blest et al. 1981;Peaslee & Wilson 1989) and estimate distance (Nagata et al. 2012). In contrast to the secondary eyes, the principal eyes possess a very narrow horizontal visual field of about 2-5°, which can be enlarged to about 60° when the eye tubes move (Land 1969). In this modular visual system, the secondary eyes function primarily, but not exclusively, as movement detectors. They also initiate optomotor responses to an object that has entered the visual field, which allow the spider to face the object and engage in further visual inspection with the high-resolution principal eyes (Zurek & Nelson 2012a,b). The secondary eyes also mediate responses to looming objects (Spano et al. 2012), thus possibly playing a major role in initiating escape. To examine how a euryphagous predator categorizes prey based solely on visual signals, the study used Yllenus arenarius Menge 1868, a euryphagous jumping spider with a natural diet consisting of over 50 species of spiders and insects ranging from flies, wasps, ants and caterpillars, to thrips, aphids and antlion larvae (Bartos 2004(Bartos , 2011 (Figure 1). During prey capture, the spider uses a conditional predatory strategy with two easily-distinguishable prey-specific predatory techniques (Bartos 2002): one is used when capturing prey with high escape potentials, such as flies, orthopterans or wasps, and the other when capturing prey with low escape potentials, such as thrips or caterpillars. Both predatory techniques are observed during capture by freshly-hatched spiderlings, which suggests that these techniques, and the prey identification mechanisms, are preprogramed (Bartos 2008(Bartos , 2013Bartos & Szczepko 2012). Y. arenarius is also known to use a preprogramed identification mechanism when targeting predatory strikes, which has been revealed in a study (Bartos & Minias 2016) exploiting a similar experimental setup to that used herein. The authors manipulated the number of head-indicating details (ranging from prey with 1314 M. Bartos four details, including a head spot, antennae, legs and wings, to prey lacking any details), the position of these details in relation to motion direction (in the leading part of the body versus the trailing part), the local motion of legs and the presence of horizontal motion. They found that the spiders identify a preferred target on the prey's body using the direction of the prey's motion and the complex arrangement of head-indicating details. The present study uses images that differed according to five characteristics (Table I): a) body length (short vs long), b) the presence of horizontal motion (images proceeding forwards vs those staying in the same place but performing only slight vertical jerks to attract the spider's attention), c) the type of global motion (crawling like a caterpillar vs moving without caterpillar-like crawls), d) the complexity of the body (0 vs 4 details, viz. head spot, legs, wings and antennae), e) the local motion of the legs (legs moving vs legs still). General methods The methods used in this study are similar to those described by Bartos and Minias (2016). In this study, the same model spider and similar prey characteristics were used to analyse the cues used in targeting predatory strikes and test the efficacy of a "false head", an antipredator adaptation used by some animals to deflect initial predatory strikes. The spiders tested in this study were newlyhatched Yllenus arenarius (mean body length of 1.71 ± 0.11 mm) collected in Central Poland (Kwilno, Zgierz County). In order to collect the freshly-emerged spiderlings, dune patches were inspected daily, starting about two weeks before their expected time of hatching (Bartos 2005). The spiderlings were separately transported and caged in the lab. The spiders were not fed before the tests. Each spiderling was used only once and after two days, it was released in the field. Tests were carried out between 0900 h and 1600 h (laboratory photoperiod 12 L:12D, lights on at 0700 h). The predatory behaviours of test spiders (prey noticing, stalking, frontal approach and pouncing) were recorded during all experiments. Prey type was indicated by the use of stalk and frontal approach, previously recorded as specific for capturing prey with high (stalk) or low (frontal approach) escape potentials (Edwards & Jackson 1993, 1994Bartos 2007). Stalk is a slow choppy gait combined with visual fixation on the prey. Frontal approach on the other hand, is characterized by a quick walk or run towards the prey. The path of this movement is arc- Table I. The characteristics of images used in the tests: body length (short vs long); the presence of horizontal motion (images proceeding forward vs not proceeding); the type of global motion (crawling like a caterpillar vs moving without caterpillar-like crawls); the number of body details (0 vs 4 details, including head spot, legs, wings and antennae); the local motion of legs (legs moving vs legs still). shaped and it is accompanied by, at least temporary, principal eye-fixation on the prey, which results in sideways movement by the spider in the final part of approach. The spider stops several millimetres in front of the prey on its predicted path, turns to the prey and waits for the prey to approach. Finally the spider pounces on the prey. All behaviours used in this study as indicators of decisions by the spider (noticing, frontal approach, stalking and pouncing) are reliably identifiable and have already been used in other studies with various salticids (Forster 1977;Nelson & Jackson 2012b;Dolev & Nelson 2014) including Y. arenarius (Bartos 2008(Bartos , 2011. The study consisted of two experiments: Experiment 1, which uses natural prey (flies, thrips, caterpillars), and Experiment 2, using video images of virtual prey possessing different combinations of the features demonstrated by natural prey used in Experiment 1. Experiment 1 -with natural prey This experiment used three species of natural prey with different escape potentials and different appearances: Drosophila melanogaster (flies), Chirothrips manicatus (thrips) and the larvae of Pyralis farinalis (butterfly caterpillars). The aim of this experiment was to record the predatory behaviour demonstrated against natural prey; the recordings would be used for comparison with the behaviour expressed by the spiders approaching the virtual prey used in Experiment 2. All the insects used in Experiment 1 are readily captured by juvenile Y. arenarius in the field and in the laboratory (Bartos 2004(Bartos , 2011. The flies and the caterpillars were obtained from laboratory culture. Thrips were collected in the field on the day of the experiment or the previous day. All prey used in the tests were within the size range of ±20% of the spider's body length. Each prey was chosen randomly for each test. The test arena for natural prey experiments was a white cardboard cylinder (height: 150 mm; diameter: 200 mm) with a 10 mm thick layer of sand on the bottom. An incandescent light bulb (100 W) and a CCD camera with a macro lens were placed about 0.5 m above the centre of the arena. The camera was connected to a PC clone computer with a video card (Matrox Marvel G450 eTV). The test started when a spider was placed in the arena. After one minute, a prey animal was dropped at a distance of about 80 mm from the spider. In order to record when the spider noticed the prey it was placed 30°-40° to the left or to the right from the visual axis of the spider's AM eyes (position chosen at random). Before the tests, each prey was kept for 15 min in a refrigerator (5°C) to decrease its mobility and the risk of escape from the arena. Each prey was left with the spider for five minutes or until the prey was attacked. The test was aborted when the spider or prey climbed the walls of the arena or when the prey escaped. Between tests, the surface layer of the sand was removed to dispose of any draglines and chemical signals from a previously-used prey or a spider. The arena was refilled with new sand and evened with a wooden tile to the original level. Each individual was used in one test for only one type of prey. During the test, the spider was recorded and observed on the monitor and was unable to see the experimenter. Experiment 2 -with virtual prey The stimuli consisted of videos of continuouslymoving images created using Macromedia Flash 8 in greyscale (Table I). The images differed with respect to the five characteristics given above: body length (short images with a length-to-height ratio of 3/1 vs long images with a ratio of 10/1); the presence or absence of details (0 or 4 details, including head spot, antennae, legs, wings); the local motion of legs (moving vs still); the type of global motion (crawling vs non-crawling) and the direction of global motion (horizontal motion vs vertical small scale jerks). The global motion (horizontal and vertical) of the whole image and the local motion of the details were modelled on those demonstrated by the natural prey used in Experiment 1. All stimuli consisted of simplified images based on the general characteristics of flies (D. melanogaster), thrips (C. manicatus) and caterpillars (P. farinalis). Short images were based on body proportions of flies (D. melanogaster), while long images were based on body proportions of thrips (C. manicatus) and caterpillars (P. farinalis). The length on the screen of the short image was 1.17 mm, and of the long image was 3.89 mm. Both image lengths are within the preferred prey size range of juvenile Y. arenarius (Bartos 2011). The videos were displayed by a projector on a screen mounted into a wall of the cardboard arena ( Figure 2). The arena itself was a white cardboard cuboid with an isosceles trapezium as the bottom (height: 100 mm, trapezium legs: 250 mm, wide base: 200 mm, narrow base: 100 mm). The images were projected onto an unmarked fine = grained matt glass screen (height: 30 mm, length: 30 mm) built in the narrowest wall of the arena. The top half of the screen was masked to focus the attention of the spider on the bottom half with a displayed image. The arena was filled with dune sand, which is the natural substrate for 1316 M. Bartos Y. arenarius, successfully used in earlier studies with freshly-hatched juvenile spiderlings (Bartos 2008;Bartos & Szczepko 2012). The movies were rendered by a SHARP XR-10X-L data projector mounted about 100 mm behind the screen (1400 x 1050 pixels). The brightness of the image was reduced with neutral-density filters mounted between the screen and the projector. To display life-size images in high resolution, which makes them more realistic for visually-efficient jumping spiders, the images were displayed large and their size was subsequently reduced with a lens mounted between a projector and the screen. A similar approach was used in other studies with jumping spiders (Harland & Jackson 2002;Nelson & Jackson 2006Dolev & Nelson 2014). The videos were played on a continuous loop using Macromedia Flash Player 8. The images in the videos moved from one side of the screen to the other, then disappearing off the screen for 5 s, which resembled disappearing behind an obstacle. Following this, they re-entered the screen from the side they disappeared and moved in the opposite direction. At the beginning of the test, a spider was placed in the centre of the arena, at a distance of 25 mm from the screen: this equals about 15 body lengths of juvenile Y. arenarius. Before the test, the spider was kept in an opaque tube (length: 80 mm, inner diameter: 8 mm) sealed on one side with a plug (Figure 2). The tube was positioned parallel to the screen to prevent the spider from seeing the screen after the plug's removal. This allowed the moment when the spider faced the screen and noticed the image to be recorded. If the spider did not leave the tube within 10 minutes after plug removal, or jumped out of the tube during or after plug removal, or if the spider left the arena without noticing the image on the screen, the trial was excluded from the analyses. The playback projection started before the plug was removed, as the timing of playback initiation may influence the spider's decision (Clark & Uetz 1993). During the test, the spider was recorded and observed on a monitor and was unable to see the experimenter. Testing was carried out between 0900 and 1600 hours. In order to remove any draglines and chemical cues from previously-used spiders, the sand was brushed after each test and a 5 mm thick surface of sand was removed. The arena was refilled with new sand and evened with a wooden tile to the original level. After each test, the screen was wiped with a piece of cotton dipped in 95% ethanol and the screen was allowed to dry between trials. No individual spider was used in more than one test of any one image type. Behavioural analyses Video recordings were analysed frame-by-frame using VLC media player 3.0.11 Vetinari (http:// Visual prey categorization by a jumping spider www.videolan.org/). During the analyses it was recorded whether the spider engaged in prey noticing, frontal approach, stalking or pouncing. Statistical analyses The effects of body proportions and motion types, as well as the presence of details and the local motion of legs on the frequency of stalk and frontal approach were tested using logistic regression with binomial error. Nonsignificant (P ≥ 0.05) variables were removed by backward removal. The significance of particular effects was assessed with the Wald statistic (W). The strength of the overall association between the predictors in the model was estimated using Nagelkerke's R 2 (Nagelkerke 1991). Logistic regression coefficients (β) and standard errors (β, SE) were used to assess the character and strength of significant relationships. Effect sizes are quoted as odds ratios (OR) with 95% confidence intervals (CI). The logistic regression models contained all horizontally-moving prey (all images but VSN0, VLN0 shown in Table I). The responses of the spider to these two images were analysed separately due to the fact that VSN0 and VLN0 could not be described by all the variables included in the models, such as the type of motion and the local motion of legs. The responses of the spiders to natural prey (flies, thrips and caterpillars) and their analogous virtual images were tested using the G test. All values are presented as means ± SD. All analyses were performed using STATISTICA 10.0 software (Statsoft, Tulsa, OK, U.S.A.). Non-specific behaviours for natural prey types were uncommon. Stalk was observed in 2 of 25 spiders approaching caterpillars (8%) and in 3 of 26 spiders approaching thrips (12%), while frontal approach was observed in 1 of 28 spiders approaching flies (4%). The spiders that attacked VSN0 images (N = 9) and VLN0 images (N = 8) did not perform stalk or frontal approach in any of the predatory attempts. Instead they directly walked towards the images and onto the image presented on the screen. Discussion The main finding of this study is that Y. arenarius can rely solely on general prey characteristics during visual prey categorization, more specifically body proportions and the type of prey motion, and can ignore other details. Such a simplified mechanism of prey identification based on only two characteristics allows the spider, and possibly other generalist jumping spiders, to categorize a wide range of prey into a limited number of groups, and subsequently capture them with the use of prey-specific predatory techniques. For Y. arenarius and other such predators, precise and quick prey identification is crucial to ensure predatory success. The characteristics 1318 M. Bartos used by Y. arenarius, namely short vs long body and crawling vs non-crawling motion, seem to fulfil these requirements. These characteristics are easily visible, unambiguous and can be used against a potentially large number of prey. In addition, this approach seems to result in only a limited number of costly misinterpretations. For example, insect larvae incapable of efficient escape, such as caterpillars and maggots, adopt a crawling motion, while noncrawling insect larvae, such as campodeiforms, and some winged insect imagines, such as thrips and staphylinids, demonstrate elongated bodies. In contrast, a short body and (or) non-crawling motion are typical for the majority of arthropods with high escape potentials, such as flies, leafhoppers, grasshoppers and wasps. While a number of short-bodied and non-crawling arthropods are incapable of efficient escape, such as wingless aphids, aradids or lygaeids (Bartos 2004), any resulting misclassification of prey with regard to escape potentials seems to result in fairly low costs, related mainly to prolonged approach time rather than escape; these animals are nevertheless still found in the natural diet of Y. arenarius. Our findings also indicate that some prey identification mechanisms employed by generalist jumping spiders differ from those used by specialized jumping spiders. It seems likely that at least some generalist jumping spiders do not rely on diverse and complex prey-specific details to make correct predatory decisions, as Y. arenarius did not appear to use the wings, legs, antennae or head spot for prey identification and categorization. This observation corresponds with the lack of reaction to interior spatial detail observed in the experiments with Phidippus audax, another euryphagous jumping spider, showing no preference between moving images of a cricket and a rectangle of the same size and colour (Bednarski et al. 2012). These observations are particularly interesting when compared with previous reports that such details play a key role in visual prey identification by specialized jumping spiders like Portia (Harland & Jackson 2000, 2002 and E. culicivora Nelson & Jackson 2006. The observation that prey details may not have any strong influence on the resulting categorisation begs the question of whether they were relevant or realistic enough to be used in prey categorization, or if they were detected at all. The possibility of remaining undetected seems unlikely, as the resolution of jumping spider eyes enables adults (Nelson 2010;Harland et al. 2012;Nelson & Jackson 2012b) and juveniles (Goté et al. 2019) to detect very small objects, and generally speaking, jumping spiders strongly rely on such signals in communication (Clark & Uetz 1993;Nelson & Jackson 2007;Elias et al. 2012) and predation (Jackson & Pollard 1996;Nelson et al. 2005;Nelson & Jackson 2011). More importantly, however, such details were found to be detected and exploited by naïve Y. arenarius in targeting predatory strikes (Bartos & Minias 2016). While it appears likely that the details were perceived in the present experiment, their realism was relatively low, as they were drawn as generalizations of certain structures of the natural prey. This possible low realism might have been the reason for the lack of the effect observed for the leg movement and the vertical motion in the detail-less images. Previous experiments with Hypoblemum albovittatum (Dolev & Nelson 2016) found that low levels of realism in the images presented to jumping spiders may affect their identification and predatory decisions. The prey identification mechanism observed in Y. arenarius is also likely to be widespread among other jumping spiders. This assumption is supported by the fact that both stalk and frontal approach exist within the routine predatory repertoires of many jumping spiders (Forster 1977(Forster , 1982Freed 1984;Jackson 1988a;Richman & Jackson 1992;Edwards & Jackson 1993, 1994Li et al. 1996;Bear & Hasson 1997Bartos 2002;Nelson et al. 2005Nelson et al. , 2007. Therefore, it is possible that similar prey characteristics employed by Y. arenarius are also used by other jumping spiders when capturing similar prey. In fact, the observations of jumping spider predatory behaviour support this hypothesis. Stalk was observed in a number of jumping spiders capturing short-bodied, non-crawling prey; this group includes various members of both the salticoid genera: Aelurillus, Euryattus, Evarcha, Hypoblemum, Figure 4. The frequency of frontal approach in the experiments with horizontally-moving prey. The number of spiders performing frontal approach, the number of spiders that did not perform frontal approach and total number of spiders are given above each bar. Our findings indicate the presence of a preprogrammed mechanism of prey categorization that enables inexperienced spiderlings to identify different prey groups based solely on the body proportions and the mode of prey motion. The mechanism enables the spider to identify groups of prey animals based on simple, universal and easily visible cues, thus increasing predatory success, as well as decreasing the risk of injury or becoming a meal of a would-be prey. The mechanism may play a significant role throughout its lifetime, as two-year-old and three-year-old spiders use similar prey-specific predatory behaviour against similar prey categories ( Bartos & Szczepko 2012). This, however, seems to be especially important for the freshly-emerged spiderlings possessing no prior experience with prey, because it simply enables them to use a prey-specific predatory technique from the first predatory attempt. Predatory behaviour may, however, change during the life cycle, as it has been shown for Phidippus regius (Edwards & Jackson 1994) and Y. arenarius (Bartos & Szczepko 2012). Adult E. culicivora even lose an innate predatory strategy, which is specifically used by juveniles against Anopheles mosquitoes, the preferred prey of all age groups . Although these changes do not seem to be accompanied by any alterations in the identification and categorization mechanisms used by E. culicivora, this does not seem to be the case for E. culicivora, a predatory specialist the feeds throughout its life on blood-fed Anopheles mosquitos. Similarly Y. arenarius continues to use similar preyspecific predatory tactics against different prey throughout its life cycle (Bartos & Szczepko 2012); the fact that this long-lived salticid (Bartos 2004) changes its diet during its lifespan (Bartos 2011) attests to the versatility of this mechanism: spiders from three different cohorts coexisting simultaneously in the field (freshly hatched spiderlings, one-year-old and two-year-olds) capture different prey taxa categorised on the basis of similar cues. Shape and mode of motion are used by many visual predators for distinguishing potential prey from non-prey objects (Wachowitz & Ewert 1996;Ewert 2004;Kral & Prete 2004;Cronin 2005). This seems obvious, as these cues characterize the majority of non-sedentary invertebrate prey, all moving along their long axis, crawling or noncrawling. Studies on insects and amphibians visually distinguishing their prey from non-prey (Ewert 2004;Kral & Prete 2004;Cronin 2005) suggest that the methods used by Y. arenarius may also be shared by different taxa from distant groups, such as mantises (Prete 1992a;b, 1993;Prete & Mahaffey 1993;Prete & McLean 1996 and toads (Wachowitz & Ewert 1996;Ewert 2004). It has been proposed that mantises categorise their prey based on the concept of a perceptual envelope, which encompasses all of the various combinations of certain original key parameters characteristic for prey items (Kral & Prete 2004). This concept was also used as a starting point by Dolev and Nelson (2016) to describe the perceptual categories of generalist and specialist jumping spiders. They propose that the evolutionary spectrum of jumping spider predatory specialisations includes extreme generalists such as P. audax, which possess some very crude neural representations of prey characteristics (Bednarski et al. 2012) and possibly capture a very wide spectrum of prey, and salticid generalists with narrower perceptual envelopes, such as Y. arenarius, which capture various prey but with prey-specific predatory techniques (Bartos 2002(Bartos , 2007(Bartos , 2008(Bartos , 2012(Bartos , 2013(Bartos , 2016. In addition, the spectrum encompasses extreme specialists, such as E. culicivora, which focus on a specific type of prey (Nelson & Jackson 2006Dolev & Nelson 2014. Our present findings revealing the perceptual mechanisms of Y. arenarius used in the categorization of different prey groups appear to be in line with Dolev and Nelson (2016).
/** * Given an iterator, prints it as a comma-delimited list * (actually a comma-and-space delimited list). E.g. If the * iterator contains the strings { "my", "dog", "has fleas" } it * will print "my, dog, has fleas". * * @param out the stream to write to * @param i an iterator containing printable (toString) objects, e.g. strings **/ public static void printCommaList(PrintWriter out, Iterator i) { boolean first = true; while (i.hasNext()) { if (first) first = false; else out.print(", "); out.print(i.next()); } }
#ifndef PARTICLE_MANAGER_H #define PARTICLE_MANAGER_H // @todo move this macro to engine variable #define MAX_PARTICLES 3000 #include "particle.h" #include "game.h" class ParticleManager { public: Particle* getFreeParticle(); void updateAndDraw(sf::RenderTarget& target); void freeAllParticles(); static ParticleManager* instance(); private: static ParticleManager* _instance; Game* game {Game::instance()}; const int MAX_PARTICLE_COUNT {MAX_PARTICLES}; Particle particles[MAX_PARTICLES]; ParticleManager() {} #ifdef DEBUG int activeParticles {0}; #endif }; #endif
arr = input().split() n=int(arr[0]) m=int(arr[1]) a=int(arr[2]) if n % a != 0: n = n//a+1 else: n = n//a if m % a != 0: m = m//a+1 else: m = m//a print(m*n) #в первой строке
// AskForServerSelection prompts user to select a server from the list of available servers if it was not selected beforehand func AskForServerSelection(server string) string { server = strings.TrimSpace(server) cfg := commons.GetCachedApplicationConfig() serverNames := cfg.GetServerNames() if len(server) <= 0 || !commons.Contains(serverNames, server) { prompt := &survey.Select{ Message: "Please choose a server that you wish to act upon:", Options: serverNames, PageSize: 20, } err := survey.AskOne(prompt, &server, nil) commons.AbortIfError(err) } return strings.TrimSpace(server) }
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: <NAME> <<EMAIL>> * * 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 */ use std::error; use std::fmt; /// Enumeration of YACA error values returned from the C library /// /// - All of the API functions return [`Result`] with an `Error` /// embedded. /// - If `Result::Err` is returned it will contain one of those /// values. /// - They are passed directly from the C YACA implementation. /// - Some of the occurrences where YACA would return an error are /// mitigated by Rust's type safety. /// - Some of the occurrences where YACA would return `DataMismatch` /// are converted to return `bool` in `Result:Ok`. /// /// [`Result`]: type.Result.html #[derive(Debug, PartialEq)] pub enum Error { /// Invalid function parameter InvalidParameter, /// Out of memory OutOfMemory, /// Internal error Internal, /// Data mismatch DataMismatch, /// Invalid password InvalidPassword, /// Unknown error, should not happen Unknown(i32), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::InvalidParameter => write!(f, "InvalidParameter"), Error::OutOfMemory => write!(f, "OutOfMemory"), Error::Internal => write!(f, "Internal"), Error::DataMismatch => write!(f, "DataMismatch"), Error::InvalidPassword => write!(f, "InvalidPassword"), Error::Unknown(e) => write!(f, "Unknown: {}", e), } } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(self) } }
Yahoo has announced plans to permanently axe the public chat rooms feature of its messaging tool. It said in a blog post it would replace the tool, along with other services being removed, with new features. The chat-rooms tool came under fire in 2005, with advertisers pulling ads after reports of illegal under-age sex-themed rooms. Yahoo said the feature was closing because it was not "adding enough value" for users. Along with public chat rooms, Pingbox and Windows Live Messenger interoperability are all scheduled to be removed on 14 December, and some other features will disappear at the end of January. "Sometimes… we have to make tough decisions," Yahoo said. "This helps us spend more energy on creating experiences that make Yahoo the most fun way to spend your time." Image caption Habbo Hotel suspended its chat function in June, after claims of under-age sex-themed chat rooms The company said it would now focus on modernising its "core Yahoo products experiences". 'Teen girls' Yahoo Messenger is one of the earliest online messaging tools, launched in 1998. In 2005, Yahoo closed a number of chat rooms, including "girls 13 & up for much older men," "teen girls for older fat men" and "8-12 yo [year-old] girls for older men". Many of these rooms were in the "Schools and education" and "Teen" chat categories. The company then announced it would restrict the service to users aged 18 and older. Sex chats Other websites that provide online chat services have also been involved in under-age sex scandals. In June this year, Habbo Hotel, a popular social network for children, temporarily suspended the chat function on its service, following claims paedophiles were using the virtual hotel to groom youngsters for sex. A two-month Channel 4 investigation revealed explicit sex chats were common within minutes of logging on to the service. A spokesman for children's charity Childnet told the BBC: "The message from us is that children need to know how to stay safe."
def updateParameterNodeFromGUI(self, caller=None, event=None): if self._parameterNode is None or self._updatingGUIFromParameterNode: return wasModified = self._parameterNode.StartModify() self._parameterNode.SetNodeReferenceID("OutputTransform", self.ui.outputSelector.currentNodeID) self._parameterNode.SetParameter("ArcAngle", str(self.ui.arcAngleSliderWidget.value)) self._parameterNode.SetParameter("RingAngle", str(self.ui.ringAngleSliderWidget.value)) self._parameterNode.SetParameter("HeadringCoordinates", self.ui.headringCoordinatesWidget.coordinates) self._parameterNode.SetParameter("Mounting", self.ui.mountingComboBox.currentText) self._parameterNode.SetParameter("AutoUpdate", str(int(self.ui.autoUpdateCheckBox.checked))) self._parameterNode.EndModify(wasModified) if int(self._parameterNode.GetParameter("AutoUpdate")): self.onApplyButton()
It has been a punishing period for the former head of Liberty, after her report on antisemitism in Labour was called a ‘whitewash’. Was it mistake to follow this by accepting a peerage from Corbyn? Shami Chakrabarti seems smaller than I remember. We have met a couple of times in the past, but I had never noticed until now how petite she is. The barrister was just 34 when she took charge of the human rights organisation Liberty, and, 14 years on, still looks like a thirtysomething, but the bombastic stature she used to project has gone. Having joined the Labour party last May, the shadow attorney general looks almost fragile. “I’m not a natural combatant,” Chakrabarti acknowledges softly. “I’m actually not a very fighty person.” On her career as a human rights campaigner, she reflects: “Even if you’re controversial, you’re not party political, and that brings a certain protection in British liberal democracy. Then the question, I suppose, is why would you chose to give up that protection at one of the bitterest moments in British politics, during that odious referendum campaign, when some really nasty stuff started bubbling to the surface? I don’t go around trying to pick fights with people. But sometimes somebody else picks the fight, and you have to pick a side. And I picked a side. I don’t think I could have lived with myself if I didn’t try to do my bit in one of the most bitter and divisive moments.” To describe last year as uncomfortable for Chakrabarti would be an understatement. Her investigation into allegations of antisemitism within Labour ended with a report condemned by many as a whitewash. Her appointment by Jeremy Corbyn to the House of Lords weeks later compromised its author’s integrity even further in the eyes of many more. The revelation that she sends her son to Dulwich College, an exclusive private school, led the New Statesman to conclude: “It’s difficult to recall a time when a liberal icon has fallen so far, so fast.” Now she has written Of Women, an analysis of global gender inequality so irreproachably blameless that I half wondered whether that was its chief appeal for Chakrabarti. After the bruising legacy of last year’s rows, who could blame her for choosing a subject that offered a safe return to liberal terra firma? But she says no, a book about feminism “was coming for some time”. Chakrabarti almost shudders at the word memoir – “That wouldn’t be for me, it’s not in my DNA” – and Of Women is instead a careful, fact-based appraisal of enduring gender inequalities. “This is not a memoir, but I think if you’re asking me personally why – what my 15-year-old son has charmingly called ‘my crappy feminist book’ – why now, I think it’s partly middle age. And I think it’s partly the loss of my mother [in 2011]. There wasn’t ever the time for me to say thank you properly to her, or for me to really acknowledge not just on a personal level, but in a bigger political way, what she had been up against.” Solidly researched and well-furnished with statistics, Of Women is a defiant reassertion of evidence in a post-truth age. “I think evidence and argument do change people’s minds. I don’t think it’s all post-fact now. I think we are creatures of logic and emotion, and some of the facts are pretty devastating. And I would challenge somebody not to be moved emotionally as well as logically. It’s symptomatic of us being bottom of the pile. This affects rich women, poor women, black women, white women, women in the first world, women in the developing world. I call it an apartheid – and I do not use the term lightly.” She grew up in suburban north London, and, recalling being the daughter of working-class Bengali immigrants and studying law at the London School of Economics, says: “I think I was unaware to a large extent of my race and sex. You have to get a little bit older to get a little bit of perspective.” As an in-house lawyer at the Home Office in her 20s, she began to notice the way older female colleagues were spoken of and treated. “And I think it would be naive to say that I haven’t had some stick for being a woman. And being a black, political woman is a triple whammy.” Nothing in Theresa May’s race report this week surprised her. “That doesn’t mean to say it wasn’t a good thing to do. However, instincts and good intentions are just not enough. This is why I’ve written my book at this time, when society is so unequal. You can’t just tackle inequality by all just agreeing not to actively discriminate; you have to go further than just publishing the information.” What did she make of a letter to the Times from several high-profile BAME names, warning against the “misuse” of statistics to falsely cast minorities as “victims of racism”? She sighs, wearily. “We can tell ourselves that everything is fine if it makes us feel better. But it doesn’t make the world better. It’s like these old white guys in the Labour party saying: ‘I’ve never seen bad behaviour in the Labour party in 150 years.’ Well, of course you haven’t, mate. But that’s just what you see or don’t see. That’s the evidence of your sense, not mine.” Chakrabarti has seen enough misogynistic abuse online to no longer look at social media until it has been filtered by her assistant, and she wants to see action taken. “People would not get away with this kind of harassment and abuse on the public street. Why are they getting away with it online? So, proposition No 1: let’s resource the sensible policing of the online world.” If anything, she goes on, social media platforms are less like a public street than a bar, “where standards should be even higher. So I also think there’s an opportunity for consumer action to say: ‘We don’t want to use your bar if your bar is not a safe place to be. We’ll go to a different bar that’s opening up down the road that is a more convivial environment.’” Facebook Twitter Pinterest With Jeremy Corbyn at this year’s Labour party conference. Photograph: A Davidson/SHM/REX/Shutterstock Some of the worst online misogyny, I point out, has come from voices on the left. She pauses carefully before answering. “I think that, actually, in recent times, less so. Jeremy Corbyn himself is a very gentle human being and treats women with a great deal of respect, and so I don’t think he’s leading a macho culture … I think it is everywhere, but I think we’re understandably more upset by any hypocrisy coming from people who are supposed to be for the cause of equality. And there’s always the danger of, ‘I’m on the side of right, therefore I don’t have to self-criticise.’ I think we all need to be self-critical.” Is it just a coincidence that Labour hasn’t produced a female leader, let alone a prime minister, while the Tories have given us two? “I don’t know. Look, it’s not a source of great pride, and it’s too late to be coy about this. As far as I’m concerned, next time it’s a woman. My very strong preference is that the Labour party should say to itself, ‘It’s time we had a woman after Corbyn.’” But when I ask by what mechanism that would be achieved, she quickly qualifies the comment. She doesn’t mean the party should allow only female leadership candidates next time, nor legislate to alternate the gender of its leader. She would, however, consider a constitutional rule change whereby the deputy could not be the same gender as the leader. “Or the party could have two deputies, one of either sex. There are different ways of doing it.” Chakrabarti can be surprisingly reluctant to commit to an opinion, and often sounds more like the Home Office civil servant she once was than the firebrand human rights activist we came to know at Liberty. Although deeply unhappy about privately run prisons, she won’t say if she would like a Labour government to take them into public ownership. “It’s not for me to unilaterally make a policy in an interview with you, but I think it’s certainly something to be looked at.” In Of Women, she sounds very enthusiastic about a universal basic income, and tells me: “I think it’s something we need to look at.” But when I ask if she has so much as discussed the idea with Corbyn or cabinet colleagues, she immediately closes down. “If I had, I wouldn’t tell you.” She isn’t entirely noncommittal. The Sun once branded her “the most dangerous woman in Britain”, and when asked last February to name the most dangerous person in the country, she nominated David Cameron. So who now? “Well, goodness me, so many potential candidates,” she laughs. “But today? Maybe Boris Johnson. I’m not just sending sisterly solidarity to Theresa May in her difficult moment. He allegedly represents Britain on a world stage, and the world is quite dangerous right now, so to think that the advocate for world peace from Britain on the world stage – the person who we might ask to intercede on our behalf with Donald Trump and North Korea – would be Johnson is a pretty terrifying prospect.” I am curious to know how it felt to go from being the lifelong darling of the liberal left last year to finding herself suddenly accused of … “Horrible things,” she completes my sentence. “Corruption and antisemitism. But proposition No 1, I don’t believe I was such a darling. The whole hero-to-zero narrative is a very good trick, so I think we need to be a little bit careful. I can remember at the height of the ‘war on terror’ going to lovely little leftwing dinner parties, and friends saying, ‘Stop having a pop. What do you want? The Tories back in power?’” Membership Event: The fight against gender injustice with Shami Chakrabarti But even when at odds with Labour policy, she had always occupied what was widely regarded as the moral high ground. When she accepted a peerage weeks after delivering a hugely helpful report to Corbyn, what dismayed so many of her longstanding admirers was the impression that she had vacated it. What was the experience of this sudden opprobrium like for her? “I treat those two impostors just the same.” But her eyes are becoming glassy and her expression suggests otherwise. “That doesn’t mean,” she adds quietly, a moment later, “I’m not human, or that it’s not horrible to have people say horrible things about you. Everyone’s got feelings.” Had she not foreseen how her appointment to the Lords would look? She hesitates. “I think that if you drive into a war zone, you’re going to get shot at, even if you think you’re driving an ambulance.” Of Women by Shami Chakrabarti is published by Allen Lane (£20). To order a copy for £14.60 go to bookshop.theguardian.com or call 0330 333 6846. Free UK p&p over £10, online orders only. Phone orders min p&p of £1.99
//TOOD: ref OSS package once we publish public final class TestUtils { private static final Random r = new Random(); private TestUtils(){ } public static String uniqueString(){ return UUID.randomUUID().toString(); } public static int randomInt(){ return r.nextInt(); }; public static int randomInt(int upperBoundExclusive){ return r.nextInt(upperBoundExclusive); }; }
<gh_stars>0 import * as THREE from 'three'; export class Dome { readonly obj: THREE.Object3D; readonly material: THREE.MeshBasicMaterial; readonly mixer: THREE.AnimationMixer; constructor(domeRadius: number) { const sphereGeometry = new THREE.SphereBufferGeometry( domeRadius, 20, 20, 0, undefined, Math.PI / 2 ); sphereGeometry.rotateX(Math.PI); this.material = new THREE.MeshBasicMaterial({ color: 0x111111, wireframe: true, transparent: true, }); const dome = new THREE.Mesh(sphereGeometry, this.material); this.obj = dome; this.mixer = new THREE.AnimationMixer(dome); } }
Featuring Steven Weber, University of California-Berkeley; Director, Bridging the Gap; Matt Kroenig, Associate Professor, Department of Government and School of Foreign Service, Georgetown University; Ryan Evans, Founder and Editor-in-Chief, War on the Rocks; Mira Rapp Hooper, Senior Fellow, Asia-Pacific Security Program, Center for a New American Security; Sameer Lalwani, Senior Associate and Deputy Director for Stimson’s South Asia Program, Stimson Center; moderated by Emma Ashford, Research Fellow, Cato Institute. The 2016 presidential campaign represented a break from the past in many ways, perhaps nowhere more so than in foreign policy. Donald Trump’s insurgent campaign did not draw advisers from the established foreign policy community — the voices that Barack Obama once disparagingly referred to as “the Blob” — and the candidate himself often seemed willing to challenge foreign policy orthodoxy, from NATO spending to U.S. Middle East interventionism. As such, the Trump administration offers a unique opportunity for voices outside the traditional Washington foreign policy community. Thus far, the incoming administration has engaged leaders in the business world and recruited from the military and the corporate sector for key posts. Yet foreign policy and international relations researchers at universities around the country form another untapped pool of expert knowledge on foreign affairs. From grand strategy to cybersecurity, and nuclear posture to democratic stability, political scientists study the key questions animating today’s most important political debates. Join the Bridging the Gap Initiative and the Cato Institute for a discussion of the ways in which international relations scholars and academics can influence policy during the Trump administration. Our panelists will highlight key foreign policy issues facing the new administration and explore how political science research can help to shape the course of the next four years. Join the conversation on Twitter using #CatoFP. Follow @CatoEvents on Twitter to get future event updates, live streams, and videos from the Cato Institute.
<reponame>xumanbu/BaseFramework /** * @Title: DispersedCachClient.java * @Package oao_framwork.oao_common.tools.cache * @Description: TODO * Copyright: Copyright (c) 2015 * Company:上海追月信息科技有限公司 * * @author oaoCoder-束文奇 * @date 2015-4-14 上午11:51:18 * @version V1.0 */ package com.cxypub.baseframework.sdk.cache; /** * @ClassName: DistributedCacheClient * @Description: 缓存接口 * @author 徐飞 * @date 2016年1月26日 上午11:41:27 * */ public interface SimpleCache { /** * @Title: add * @Description: 添加一个缓冲数据 * @param key 字符串的缓存key * @param value 缓冲的缓存数据 * @return * @author 徐飞 */ boolean add(String key, Object value); /** * @Title: add * @Description: 缓存一个数据,并指定缓存过期时间 * @param key * @param value * @param seconds * @return * @author 徐飞 */ boolean add(String key, Object value, int seconds); /** * @Title: get * @Description: 根据key获取到一直值 * @param key 字符串的缓存key * @return * @author 徐飞 */ Object get(String key); /** * @Title: delete * @Description: 删除一个数据问题 * @param key 字符串的缓存key * @return * @author 徐飞 */ long delete(String key); /** * @Title: exists * @Description: 判断指定key是否在缓存中已经存在 * @param key 字符串的缓存key * @return * @author 徐飞 */ boolean exists(String key); }
#include <QTest> #include <QFile> #include <QPointF> #include <QImage> #include <QDebug> namespace workspace { void run() { QFile file{ "file.bin" }; // write binary data to a file if (not file.open(QIODevice::WriteOnly)) return; QDataStream streamToWrite{ &file }; streamToWrite.setVersion(QDataStream::Qt_5_3); streamToWrite << QPointF{ 42, 17 } << QImage{ ":/img" }; file.close(); if (QDataStream::Ok != streamToWrite.status()) qDebug() << "error on writing"; // read binary data from a file if (not file.open(QIODevice::ReadOnly)) return; QPointF pt{}; QImage img{}; QDataStream streamToRead{ &file }; streamToRead.setVersion(QDataStream::Qt_5_3); streamToRead >> pt >> img; if (QDataStream::Ok != streamToRead.status()) qDebug() << "error on reading"; file.close(); // assert QCOMPARE(42, pt.x()); QCOMPARE(17, pt.y()); QCOMPARE(QImage{ ":/img" }.size(), img.size()); // clear if (file.exists()) file.remove(); } } // example_01 #include <QTest> class TestClass : public QObject { Q_OBJECT private slots: void run() { workspace::run(); } }; QTEST_MAIN(TestClass) #include "main.moc"
package services import ( "context" "errors" "github.com/mrzack99s/netcoco/ent" "github.com/mrzack99s/netcoco/ent/administrator" "github.com/mrzack99s/netcoco/pkgs/security" ) type ChangeAdminPassword struct { Username string `json:"username"` OldPassword string `json:"old_password"` NewPassword string `json:"new_password"` } func GetAllAdministrator(client *ent.Client) (response []*ent.Administrator, err error) { response, err = client.Administrator.Query().All(context.Background()) return } func CreateAdministrator(client *ent.Client, obj ent.Administrator) (response *ent.Administrator, err error) { response, err = client.Administrator.Create(). SetUsername(obj.Username). SetPassword(security.Encrypt(obj.Password)). Save(context.Background()) return } func ChangePasswordAdministrator(client *ent.Client, obj ChangeAdminPassword) (response *ent.Administrator, e error) { usr, err := client.Administrator. Query().Where(administrator.UsernameEQ(obj.Username)). Only(context.Background()) if err != nil { response = nil e = errors.New("not found username" + obj.Username) return } else { if obj.OldPassword != security.Decrypt([]byte(usr.Password)) { response = nil e = errors.New("password not match") return } else { newPasswdEncrypt := security.Encrypt(obj.NewPassword) _, e = client.Administrator.UpdateOneID(usr.ID). SetUsername(usr.Username). SetPassword(<PASSWORD>PasswdEncrypt). Save(context.Background()) if e != nil { response = nil return } usr.Password = <PASSWORD> response = usr return } } } func CheckNilAdministrator(client *ent.Client) (status bool) { count, _ := client.Administrator.Query().Count(context.Background()) status = true if count > 0 { status = false } return }
def prepare_updated_dataset(self, include_generated_points = True): self.my_dataloader = {} self.for_distance_analysis = {} for phase in ["train", "val", "test"]: self.accumulate(phase=phase) feat_all = [] labs_all = [] if self.config["pg"]["tukey"]: for i in self.labs.keys(): self.feat[i] = self.tukey_transform(self.feat[i], lam=self.config["pg"]["tukey_value"]) for i in self.labs.keys(): feat_all.append(self.feat[i]) labs_all.append(self.labs[i]) feat_all = torch.vstack(feat_all) labs_all = torch.hstack(labs_all).cuda() if include_generated_points and phase == "train": generated_points = torch.load(self.config["training_opt"]["log_generate"] + "/generated_points.pt") for i in generated_points.keys(): feat_all = torch.cat((feat_all, generated_points[i].cuda())) labs_all = torch.cat((labs_all, torch.full((generated_points[i].size()[0],), int(i)).cuda())) my_dataset = TensorDataset(F.normalize(feat_all, dim=1), labs_all, labs_all) self.my_dataloader[phase] = DataLoader(my_dataset, batch_size=self.config["training_opt"]["batch_size"], shuffle=True)
/* * Add a key to watch in configd, and a callback to call when we * get a notification of change. */ void watch_add_key(CFStringRef key, void (*callback)(void)) { CFDictionarySetValue(watch_dict, key, callback); watch_dict_changed(); }
/** * Compressed image data requested by the <code>startScreencast</code>. */ public static class ScreencastFrame { /** * Base64-encoded compressed image. */ public String data; /** * Screencast frame metadata. */ public ScreencastFrameMetadata metadata; /** * Frame number. */ public Integer sessionId; public String toString() { return "ScreencastFrame{data=" + data + ", metadata=" + metadata + ", sessionId=" + sessionId + "}"; } }
<filename>src/xrGame/ui/MMSound.h<gh_stars>1-10 #pragma once class CUIXml; class CMMSound { public: CMMSound(); ~CMMSound(); void Init(CUIXml& xml_doc, LPCSTR path); void whell_Play(); void whell_Stop(); void whell_Click(); void whell_UpdateMoving(float frequency); void music_Play(); void music_Stop(); void music_Update(); void all_Stop(); protected: IC bool check_file(LPCSTR fname); static constexpr size_t channels_count = 2; xr_array<ref_sound, channels_count> m_music; ref_sound m_whell; ref_sound m_whell_click; bool m_bRandom; xr_vector<xr_string> m_play_list; };
// startCheckmarks prepares for the checkmarks phase. // // The world must be stopped. func startCheckmarks() { for _, ai := range mheap_.allArenas { arena := mheap_.arenas[ai.l1()][ai.l2()] bitmap := arena.checkmarks if bitmap == nil { bitmap = (*checkmarksMap)(persistentalloc(unsafe.Sizeof(*bitmap), 0, &memstats.gcMiscSys)) if bitmap == nil { throw("out of memory allocating checkmarks bitmap") } arena.checkmarks = bitmap } else { for i := range bitmap { bitmap[i] = 0 } } } useCheckmark = true }
<reponame>EmilGedda/Advent-of-Code-2020<filename>src/Solutions/Y2020/D02.hs {-# LANGUAGE OverloadedStrings #-} module Solutions.Y2020.D02 (day02) where import Prelude hiding (drop) import Advent.Problem import Data.Attoparsec.ByteString.Char8 (Parser, decimal, char, anyChar, many', parseOnly) data Policy = Policy Int Int Char String deriving (Generic, NFData) policy :: Parser Policy policy = Policy <$> decimal <*> (char '-' *> decimal) <*> (char ' ' *> anyChar) <*> (": " *> many' anyChar) instance Parseable Policy where parseInput = fromRight . parseOnly policy day02 :: Day 2 day02 = day (length . filter valid1) (length . filter valid2) valid1 :: Policy -> Bool valid1 (Policy lower upper char password) = lower <= count && count <= upper where count = length . filter (char ==) $ password valid2 :: Policy -> Bool valid2 (Policy lower upper char password) = equal lower /= equal upper where equal at = (password !! (at - 1)) == char
def do_cleanup(self): date = datetime.now() offset = timedelta(days=-30) date = date + offset try: self.cleanup_old_informs(date) self.cleanup_old_tickets(date) self.cleanup_django_admin_logs(date) self.cleanup_soft_deleted_objects() self.cleanup_empty_tags() self.cleanup_old_praises() self.cleanup_old_sessions(date) except Exception as err: traceback.print_exc() print("Error in cleanup: %s" % err) inform_staff("Database cleanup completed.")
/** * Extracts the tar.gz file given by {@code tarGzFilePath}. * Input {@link Path} MUST be to a gzipped tar file. * @param tarGzFilePath {@link Path} to a gzipped tar file for extraction. * @param destDir {@link Path} to the directory where the contents of {@code tarGzFilePath} will be extracted. * @param overwriteExistingFiles If {@code true}, will enable overwriting of existing files. If {@code false}, will cause an exception to be thrown if files exist already. */ public static void extractTarGz(final Path tarGzFilePath, final Path destDir, final boolean overwriteExistingFiles) { logger.info("Extracting data from archive: " + tarGzFilePath.toUri()); try ( final InputStream fi = Files.newInputStream(tarGzFilePath); final InputStream bi = new BufferedInputStream(fi); final InputStream gzi = new GzipCompressorInputStream(bi); final TarArchiveInputStream archiveStream = new TarArchiveInputStream(gzi)) { extractFilesFromArchiveStream(archiveStream, tarGzFilePath, destDir, overwriteExistingFiles); } catch (final IOException ex) { throw new UserException("Could not extract data from: " + tarGzFilePath.toUri(), ex); } }
<filename>src/vm/jvm/runtime/org/perl6/nqp/io/ServerSocketHandle.java package org.perl6.nqp.io; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import org.perl6.nqp.runtime.ExceptionHandling; import org.perl6.nqp.runtime.ThreadContext; public class ServerSocketHandle implements IIOBindable, IIOClosable { ServerSocketChannel listenChan; public int listenPort; public ServerSocketHandle(ThreadContext tc) { try { listenChan = ServerSocketChannel.open(); } catch (IOException e) { ExceptionHandling.dieInternal(tc, e); } } public void bind(ThreadContext tc, String host, int port, int backlog) { try { InetSocketAddress addr = new InetSocketAddress(host, port); listenChan.bind(addr, backlog); listenPort = listenChan.socket().getLocalPort(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public SocketHandle accept(ThreadContext tc) { try { SocketChannel chan = listenChan.accept(); return chan == null ? null : new SocketHandle(tc, chan); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void close(ThreadContext tc) { try { listenChan.close(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } }
<gh_stars>0 import * as serverSecretJson from "./serverSecret.json"; export class ServerSetting { public static readonly serverProtocol = serverSecretJson.serverProtocol; public static readonly dbProtocol = serverSecretJson.dbProtocol; public static readonly frontendDomain = serverSecretJson.frontendDomain; public static readonly backendDomain = serverSecretJson.backendDomain; public static readonly databaseDomain = serverSecretJson.databaseDomain; public static readonly ngPort = serverSecretJson.ngPort; public static readonly nestPort = serverSecretJson.nestPort; public static readonly dbPort = serverSecretJson.dbPort; public static readonly dbName = serverSecretJson.dbName; public static readonly dbAccount = serverSecretJson.dbAccount; public static readonly ngUrl = ServerSetting.serverProtocol + ServerSetting.frontendDomain + ServerSetting.ngPort; public static readonly dbUrl = ServerSetting.dbProtocol + ServerSetting.dbAccount + "@" + ServerSetting.databaseDomain + ServerSetting.dbPort + ServerSetting.dbName; public static readonly nestUrl = ServerSetting.serverProtocol + ServerSetting.backendDomain + ServerSetting.nestPort; public static readonly googleCallbackURL = ServerSetting.nestUrl + "/auth/google/callback"; public static readonly discordClientId = serverSecretJson.discordBot_clientId; public static readonly discordToken = serverSecretJson.discordBot_token; public static readonly discordBotName = serverSecretJson.discordBot_name; public static readonly ngRoutes = { "loginSuccess" : ServerSetting.ngUrl + "/login/success/", "loginFailure" : ServerSetting.ngUrl + "/login/failure" }; public static readonly timerStepList:Array<number> = [ 10 * 60 * 1000, 30 * 60 * 1000, 60 * 60 * 1000, 2 * 60 * 60 * 1000, 4 * 60 * 60 * 1000, 6 * 60 * 60 * 1000, 12 * 60 * 60 * 1000, 24 * 60 * 60 * 1000, 2 * 24 * 60 * 60 * 1000, 3 * 24 * 60 * 60 * 1000, ]; }
def latin_sampler(locator, num_samples, variables, region): variable_groups = ('ENVELOPE', 'INDOOR_COMFORT', 'INTERNAL_LOADS','SYSTEMS') database = pd.concat([pd.read_excel(locator.get_uncertainty_db(region), group, axis=1) for group in variable_groups]) pdf_list = database[database['name'].isin(variables)].set_index('name') num_vars = pdf_list.shape[0] samples = latin_hypercube.lhs(num_vars, samples=num_samples, criterion='maximin') for i, variable in enumerate(variables): distribution = pdf_list.loc[variable, 'distribution'] min = pdf_list.loc[variable, 'min'] max = pdf_list.loc[variable, 'max'] mu = pdf_list.loc[variable, 'mu'] stdv = pdf_list.loc[variable, 'stdv'] if distribution == 'triangular': loc = min scale = max - min c = (mu - min) / (max - min) samples[:, i] = triang(loc=loc, c=c, scale=scale).ppf(samples[:, i]) elif distribution == 'normal': samples[:, i] = norm(loc=mu, scale=stdv).ppf(samples[:, i]) elif distribution == 'boolean': samples[:, i] = ma.make_mask(np.rint(uniform(loc=min, scale=max).ppf(samples[:, i]))) else: samples[:, i] = uniform(loc=min, scale=max).ppf(samples[:, i]) min_max_scaler = preprocessing.MinMaxScaler(copy=True, feature_range=(0, 1)) samples_norm = min_max_scaler.fit_transform(samples) return samples, samples_norm, pdf_list
<filename>vendor/github.com/prometheus/tsdb/cmd/tsdb/main.go package main import ( "flag" "fmt" "io" "io/ioutil" "net/http" _ "net/http/pprof" "os" "path/filepath" "runtime" "runtime/pprof" "sync" "time" "unsafe" promlabels "github.com/prometheus/prometheus/pkg/labels" "github.com/prometheus/prometheus/pkg/textparse" "github.com/prometheus/tsdb" "github.com/prometheus/tsdb/labels" "github.com/spf13/cobra" ) func main() { // Start HTTP server for pprof endpoint. go http.ListenAndServe(":9999", nil) root := &cobra.Command{ Use: "tsdb", Short: "CLI tool for tsdb", } root.AddCommand( NewBenchCommand(), ) flag.CommandLine.Set("log.level", "debug") root.Execute() } func NewBenchCommand() *cobra.Command { c := &cobra.Command{ Use: "bench", Short: "run benchmarks", } c.AddCommand(NewBenchWriteCommand()) return c } type writeBenchmark struct { outPath string cleanup bool numMetrics int storage *tsdb.DB cpuprof *os.File memprof *os.File blockprof *os.File } func NewBenchWriteCommand() *cobra.Command { var wb writeBenchmark c := &cobra.Command{ Use: "write <file>", Short: "run a write performance benchmark", Run: wb.run, } c.PersistentFlags().StringVar(&wb.outPath, "out", "benchout/", "set the output path") c.PersistentFlags().IntVar(&wb.numMetrics, "metrics", 10000, "number of metrics to read") return c } func (b *writeBenchmark) run(cmd *cobra.Command, args []string) { if len(args) != 1 { exitWithError(fmt.Errorf("missing file argument")) } if b.outPath == "" { dir, err := ioutil.TempDir("", "tsdb_bench") if err != nil { exitWithError(err) } b.outPath = dir b.cleanup = true } if err := os.RemoveAll(b.outPath); err != nil { exitWithError(err) } if err := os.MkdirAll(b.outPath, 0777); err != nil { exitWithError(err) } dir := filepath.Join(b.outPath, "storage") st, err := tsdb.Open(dir, nil, nil, &tsdb.Options{ WALFlushInterval: 200 * time.Millisecond, RetentionDuration: 2 * 24 * 60 * 60 * 1000, // 1 days in milliseconds MinBlockDuration: 3 * 60 * 60 * 1000, // 2 hours in milliseconds MaxBlockDuration: 27 * 60 * 60 * 1000, // 1 days in milliseconds AppendableBlocks: 2, }) if err != nil { exitWithError(err) } b.storage = st var metrics []labels.Labels measureTime("readData", func() { f, err := os.Open(args[0]) if err != nil { exitWithError(err) } defer f.Close() metrics, err = readPrometheusLabels(f, b.numMetrics) if err != nil { exitWithError(err) } }) var total uint64 dur := measureTime("ingestScrapes", func() { b.startProfiling() total, err = b.ingestScrapes(metrics, 3000) if err != nil { exitWithError(err) } }) fmt.Println(" > total samples:", total) fmt.Println(" > samples/sec:", float64(total)/dur.Seconds()) measureTime("stopStorage", func() { if err := b.storage.Close(); err != nil { exitWithError(err) } b.stopProfiling() }) } func (b *writeBenchmark) ingestScrapes(lbls []labels.Labels, scrapeCount int) (uint64, error) { var mu sync.Mutex var total uint64 for i := 0; i < scrapeCount; i += 100 { var wg sync.WaitGroup lbls := lbls for len(lbls) > 0 { l := 1000 if len(lbls) < 1000 { l = len(lbls) } batch := lbls[:l] lbls = lbls[l:] wg.Add(1) go func() { n, err := b.ingestScrapesShard(batch, 100, int64(30000*i)) if err != nil { // exitWithError(err) fmt.Println(" err", err) } mu.Lock() total += n mu.Unlock() wg.Done() }() } wg.Wait() } return total, nil } func (b *writeBenchmark) ingestScrapesShard(metrics []labels.Labels, scrapeCount int, baset int64) (uint64, error) { ts := baset type sample struct { labels labels.Labels value int64 ref *uint64 } scrape := make([]*sample, 0, len(metrics)) for _, m := range metrics { scrape = append(scrape, &sample{ labels: m, value: 123456789, }) } total := uint64(0) for i := 0; i < scrapeCount; i++ { app := b.storage.Appender() ts += int64(30000) for _, s := range scrape { s.value += 1000 if s.ref == nil { ref, err := app.Add(s.labels, ts, float64(s.value)) if err != nil { panic(err) } s.ref = &ref } else if err := app.AddFast(*s.ref, ts, float64(s.value)); err != nil { if err.Error() != "not found" { panic(err) } ref, err := app.Add(s.labels, ts, float64(s.value)) if err != nil { panic(err) } s.ref = &ref } total++ } if err := app.Commit(); err != nil { return total, err } } return total, nil } func (b *writeBenchmark) startProfiling() { var err error // Start CPU profiling. b.cpuprof, err = os.Create(filepath.Join(b.outPath, "cpu.prof")) if err != nil { exitWithError(fmt.Errorf("bench: could not create cpu profile: %v", err)) } pprof.StartCPUProfile(b.cpuprof) // Start memory profiling. b.memprof, err = os.Create(filepath.Join(b.outPath, "mem.prof")) if err != nil { exitWithError(fmt.Errorf("bench: could not create memory profile: %v", err)) } runtime.MemProfileRate = 4096 // Start fatal profiling. b.blockprof, err = os.Create(filepath.Join(b.outPath, "block.prof")) if err != nil { exitWithError(fmt.Errorf("bench: could not create block profile: %v", err)) } runtime.SetBlockProfileRate(1) } func (b *writeBenchmark) stopProfiling() { if b.cpuprof != nil { pprof.StopCPUProfile() b.cpuprof.Close() b.cpuprof = nil } if b.memprof != nil { pprof.Lookup("heap").WriteTo(b.memprof, 0) b.memprof.Close() b.memprof = nil } if b.blockprof != nil { pprof.Lookup("block").WriteTo(b.blockprof, 0) b.blockprof.Close() b.blockprof = nil runtime.SetBlockProfileRate(0) } } func measureTime(stage string, f func()) time.Duration { fmt.Printf(">> start stage=%s\n", stage) start := time.Now() f() fmt.Printf(">> completed stage=%s duration=%s\n", stage, time.Since(start)) return time.Since(start) } func readPrometheusLabels(r io.Reader, n int) ([]labels.Labels, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, err } p := textparse.New(b) i := 0 var mets []labels.Labels hashes := map[uint64]struct{}{} for p.Next() && i < n { m := make(labels.Labels, 0, 10) p.Metric((*promlabels.Labels)(unsafe.Pointer(&m))) h := m.Hash() if _, ok := hashes[h]; ok { continue } mets = append(mets, m) hashes[h] = struct{}{} i++ } return mets, p.Err() } func exitWithError(err error) { fmt.Fprintln(os.Stderr, err) os.Exit(1) }
/** * Command implementation of Reset method */ public class OthelloResetCommand implements OthelloCommand { private Othello othello; private OthelloApplication othelloApplication; private OthelloApplication newGame; public OthelloResetCommand(OthelloApplication othelloApplication) { this.othelloApplication = othelloApplication; this.newGame = new OthelloApplication(); } /** * Resetting the stack by clearing the moveStack and setting both player 1 and 2 to human * @return */ @Override public void execute() throws Exception { OthelloApplication.currentStage.close(); OthelloApplication.cheat = false; OthelloApplication.player1 = "Human"; OthelloApplication.player2 = "Human"; this.newGame.start(new Stage()); } }
// NewKernelNotifLevelSanitizer creates a new instance of KernelNotifLevelSanitizer. func NewScopeSanitizer(sanitizedScope *model.Category) *ScopeSanitizer { *sanitizedScope = model.CategoryGlobal return &ScopeSanitizer{ scope: sanitizedScope, } }
// Link returns a link to the space func (s *Space) Link() *Link { return &Link{ LinkData: &LinkData{ Type: LinkType, LinkType: "Space", ID: s.ID, }, } }
# -*- coding: UTF-8 -*- # # copyright: 2020-2021, <NAME> # author: <NAME> <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Tests for the Options module.""" import sys import pytest from discogs2xlsx.options import Options def test_options_fail_default(): """test_options_fail_default Test if without any arguments given the 'required arguments' error is triggered. """ with pytest.raises(SystemExit) as error: _ = Options() assert error.type == SystemExit assert error.value.code == 2 def test_options_fail_debug_quiet(mocker): """test_options_fail_debug_quiet Test if with the '--debug' and the '--quiet' arguments given the 'not allowed' arguments error is triggered. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--debug', '--quiet'] mocker.patch.object(sys, 'argv', testargs) with pytest.raises(SystemExit) as wrapped_e: _ = Options() assert wrapped_e.type == SystemExit assert wrapped_e.value.code == 2 def test_options_fail_redefine_variable(mocker): """test_options_fail_redefine_variable Test if it is possible to assign a value to a 'read only' property from an Options instance. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--apikey', 'dummy'] mocker.patch.object(sys, 'argv', testargs) with pytest.raises(SyntaxError) as error: o = Options() o.apikey = 'SyntaxError' print(error) assert error.type == SyntaxError assert error.value.msg == 'cannot assign to operator' def test_options_fail_unrecognized(mocker): """test_options_fail_unrecognized Test if with an invalid argument given the 'unrecognized arguments' arguments error is triggered. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--apikey', 'dummy', '--fake'] mocker.patch.object(sys, 'argv', testargs) with pytest.raises(SystemExit) as error: _ = Options() assert error.type == SystemExit assert error.value.code == 2 def test_options_ok_default(mocker): """test_options_ok_default Test the default set of arguments. '--apikey' is provided to avoid validation errors. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--apikey', 'dummy'] mocker.patch.object(sys, 'argv', testargs) o = Options() default = { 'apikey': 'dummy', 'currency': 'EUR', 'debug': False, 'details': False, 'file': 'discogs-collection.xlsx', 'prices': False, 'quiet': False, 'wantlist': False} assert o.all == default def test_options_ok_duplicated_wantlistaction(mocker): """test_options_ok_duplicated_wantlistaction Test the usage of duplicated '--wantlist' argument and the custom 'Action' assign to it. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = ['prog', '--apikey', 'dummy', '--wantlist', '--wantlist'] mocker.patch.object(sys, 'argv', testargs) o = Options() assert o.all['wantlist'] def test_options_ok_custom(mocker): """test_options_ok_custom Test changing the default set of arguments. '--apikey' is provided to avoid validation errors. Args: mocker (pytest_mock.plugin.MockerFixture): Mocker. """ testargs = [ 'prog', '--apikey', 'dummy', '--currency', 'USD', '--debug', '--details', '--file', 'custom.xlsx', '--prices', '--wantlist'] mocker.patch.object(sys, 'argv', testargs) o = Options() custom = { 'apikey': 'dummy', 'currency': 'USD', 'debug': True, 'details': True, 'file': 'custom.xlsx', 'prices': True, 'quiet': False, 'wantlist': True} assert o.all == custom
<reponame>aav789/pengyifan-leetcode package com.pengyifan.leetcode; /** * Given a m x n grid filled with non-negative numbers, find a path from top * left to bottom right which minimizes the sum of all numbers along its path. */ public class MinimumPathSum { public int minPathSum(int[][] grid) { if (grid == null) { return 0; } int row = grid.length; int col = grid[row - 1].length; int[][] minVal = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (i == 0 && j == 0) { minVal[i][j] = grid[i][j]; } else if (i == 0) { minVal[i][j] = minVal[i][j - 1] + grid[i][j]; } else if (j == 0) { minVal[i][j] = minVal[i - 1][j] + grid[i][j]; } else { minVal[i][j] = Math.min(minVal[i - 1][j], minVal[i][j - 1]) + grid[i][j]; } } } return minVal[row - 1][col - 1]; } }
/** * Tests notifications for updated rows. */ @Test public void testRowsUpdated() { handler.rowsUpdated(START_IDX, END_IDX); getModel().checkNotification(METH_UPDATED, START_IDX, END_IDX); }
def fix_daily_bar_date(date, timespan): if timespan == 'day': date = dateutil.parser.parse(date) today = datetime.datetime.utcnow().date() if today != date.date(): date = date + datetime.timedelta(days=1) date = date.date().isoformat() return date
/** * Checks if two commands are the same, assuming that they are both constructed using an existing event. * * @param other Command to compare against. * @return Boolean value denoting whether they are the same. */ private boolean sameCommandWithToAddEvent(AddEventCommand other) { boolean sameToAdd = toAdd != null && other.toAdd != null && toAdd.equals(other.toAdd); boolean sameRepeatEndDate = (endRepeatDate == null && other.endRepeatDate == null) || (endRepeatDate != null && other.endRepeatDate != null && endRepeatDate.equals(other.endRepeatDate)); boolean sameIsRepeated = isRepeated == other.isRepeated; boolean sameFrequency = frequency.equals(other.frequency); boolean sameSuffix = (suffix == null && other.suffix == null) || (suffix != null && other.suffix != null && suffix.equals(other.suffix)); return sameToAdd && sameRepeatEndDate && sameIsRepeated && sameFrequency && sameSuffix; }
// TryColumns tries some sqlx stuff. func (p *MmmcDB) TryColumns(tableName string) { var e error var rows *sqlx.Rows var cols []interface{} rows, e = p.DB.Queryx("SELECT * FROM " + tableName + " LIMIT 1") if e != nil { L.L.Error("TryColumns-1 failed: %v", e) return } n := 0 for rows.Next() { n++ cols, e = rows.SliceScan() if e != nil { panic(e) } else { fmt.Printf(" COLUMNS as SLICE: %+v \n", cols) } } rows, e = p.DB.Queryx("SELECT * FROM " + tableName + " LIMIT 1") if e != nil { L.L.Error("CheckColumns-2 failed: %v", e) return } n = 0 for rows.Next() { n++ results := make(map[string]interface{}) e = rows.MapScan(results) if e != nil { panic(e) } else { fmt.Printf(" COLUMNS as MAP: %+v \n", results) } } }
import os import uuid import random import unittest import pprint from google.protobuf.json_format import MessageToDict from spaceone.core import utils, pygrpc from spaceone.core.unittest.runner import RichTestRunner def random_string(): return uuid.uuid4().hex class TestAuthorization(unittest.TestCase): config = utils.load_yaml_from_file( os.environ.get('SPACEONE_TEST_CONFIG_FILE', './config.yml')) pp = pprint.PrettyPrinter(indent=4) identity_v1 = None domain = None domain_owner = None owner_id = None owner_pw = None token = None @classmethod def setUpClass(cls) -> None: super(TestAuthorization, cls).setUpClass() endpoints = cls.config.get('ENDPOINTS', {}) cls.identity_v1 = pygrpc.client(endpoint=endpoints.get('identity', {}).get('v1'), version='v1') cls._create_domain() cls._create_domain_owner() cls._issue_owner_token() @classmethod def tearDownClass(cls) -> None: super(TestAuthorization, cls).tearDownClass() cls.identity_v1.DomainOwner.delete({ 'domain_id': cls.domain.domain_id, 'owner_id': cls.owner_id }) print(f'>> delete domain owner: {cls.owner_id}') if cls.domain: cls.identity_v1.Domain.delete({'domain_id': cls.domain.domain_id}) print(f'>> delete domain: {cls.domain.name} ({cls.domain.domain_id})') @classmethod def _create_domain(cls): name = utils.random_string() params = { 'name': name, 'config': { 'config_key': 'config_value' } } cls.domain = cls.identity_v1.Domain.create(params) @classmethod def _create_domain_owner(cls): cls.owner_id = utils.random_string()[0:10] cls.owner_pw = '<PASSWORD>' owner = cls.identity_v1.DomainOwner.create({ 'owner_id': cls.owner_id, 'password': <PASSWORD>, 'domain_id': cls.domain.domain_id }) cls.domain_owner = owner print(f'owner_id: {cls.owner_id}') print(f'owner_pw: {cls.owner_pw}') @classmethod def _issue_owner_token(cls): token_params = { 'credentials': { 'user_type': 'DOMAIN_OWNER', 'user_id': cls.owner_id, 'password': <PASSWORD> }, 'domain_id': cls.domain.domain_id } issue_token = cls.identity_v1.Token.issue(token_params) cls.token = issue_token.access_token print(f'token: {cls.token}') def setUp(self) -> None: self.user = None self.users = [] self.policy = None self.policies = [] self.role = None self.roles = [] def tearDown(self) -> None: print() for user in self.users: print(f'[tearDown] Delete User. {user.user_id}') self.identity_v1.User.delete( {'user_id': user.user_id, 'domain_id': self.domain.domain_id}, metadata=(('token', self.token),) ) for role in self.roles: print(f'[tearDown] Delete Role. {role.role_id}') self.identity_v1.Role.delete( {'role_id': role.role_id, 'domain_id': self.domain.domain_id}, metadata=(('token', self.token),) ) for policy in self.policies: print(f'[tearDown] Delete Policy. {policy.policy_id}') self.identity_v1.Policy.delete( {'policy_id': policy.policy_id, 'domain_id': self.domain.domain_id}, metadata=(('token', self.token),) ) def _print_data(self, message, description=None): print() if description: print(f'[ {description} ]') self.pp.pprint(MessageToDict(message, preserving_proto_field_name=True)) def _test_create_policy(self, permissions): params = { 'name': 'Policy-' + random_string()[0:5], 'permissions': permissions, 'domain_id': self.domain.domain_id } self.policy = self.identity_v1.Policy.create( params, metadata=(('token', self.token),) ) self.policies.append(self.policy) def _test_create_role(self, policies, role_type='PROJECT'): params = { 'name': 'Role-' + random_string()[0:5], 'role_type': role_type, 'policies': policies, 'domain_id': self.domain.domain_id } self.role = self.identity_v1.Role.create( params, metadata=(('token', self.token),)) self.roles.append(self.role) def _test_create_user(self, user_id=None): if user_id is None: user_id = utils.random_string()[0:10] params = { 'user_id': user_id, 'password': '<PASSWORD>', 'name': utils.random_string()[0:5], 'domain_id': self.domain.domain_id } user = self.identity_v1.User.create( params, metadata=(('token', self.token),) ) self.user = user self.users.append(user) self.assertEqual(self.user.name, params['name']) def _test_update_domain_role(self): self._test_create_policy([ 'identity.Domain.get', 'identity.Domain.list', 'identity.Project.*', 'identity.ProjectGroup.*', 'identity.User.get', 'identity.User.update', ]) self._test_create_role([{ 'policy_type': 'CUSTOM', 'policy_id': self.policy.policy_id}], 'DOMAIN') params = { 'user_id': self.user.user_id, 'domain_id': self.domain.domain_id, 'roles': list(map(lambda role: role.role_id, self.roles)) } self.user = self.identity_v1.User.update_role( params, metadata=(('token', self.token),) ) self._print_data(self.user, 'test_update_domain_role') def _test_issue_user_token(self): token_params = { 'credentials': { 'user_type': 'USER', 'user_id': self.user.user_id, 'password': '<PASSWORD>' }, 'domain_id': self.domain.domain_id } response = self.identity_v1.Token.issue(token_params) self.user_token = response.access_token def test_check_domain_owner_permissions(self): """ Check Domain Owner Permissions """ self._test_create_user() user = self.identity_v1.User.get( { 'user_id': self.user.user_id, 'domain_id': self.domain.domain_id }, metadata=(('token', self.token),) ) self.assertEqual(user.user_id, self.user.user_id) def test_authorization_verify_domain_role(self): """ Verify Authorization """ self._test_create_user('domain_user') self._test_update_domain_role() self._test_issue_user_token() params = { 'service': 'identity', 'api_class': 'User', 'method': 'get', 'parameter': { 'domain_id': self.domain.domain_id, 'test': 1, 'test2': 2.0 } } response = self.identity_v1.Authorization.verify( params, metadata=(('token', self.user_token),)) print(response) self._print_data(response, 'test_authorization_verify') if __name__ == "__main__": unittest.main(testRunner=RichTestRunner)
Apoptosis resistance in chronic myelogenous leukemia The chronic myeloid leukemia (CML) is the three-phase myeloproliferative disorder, dependent on the expression of the oncoprotein Bcr-Abl, which is the product of the reciprocal translocation between chromosomes 9 and 22, resulting in the Philadelphia chromosome (Ph). Bcr-Abl protein is the constitutively activated tyrosine kinase responsible for changes in intracellular biochemical cascades, culminating into hematopoieticic stem cell malignant transformation. CML leukemic cells present abnormal adhesion to medullar stroma, altered proliferation and an amazing resistance to apoptosis induced by classical chemotherapeutic drugs. Another therapy used in CML patients is imatinib mesylate (Gleevecâ), which has shown remarkable clinical activity in these patients. However, this drug does not completely eradicate BCRABL-expressing cells from the body, and recently some patients showed resistance to imatinib. The observation that production of Bcr-Abl is the initiating event in CML drew attention to the survival signals triggered by this oncogene. The number of altered signal transducers and transcription factors has been associated with the anti-apoptotic phenotype of CML cells, and some of them lead to the expression and/or activation of apoptosis modulators from Bcl-2 family, such as Bcl-x L , Bcl-2, Bax and Bad. In this article we review some recent data on the understanding of Bcr-Abl oncoprotein expression effect in the apoptosis machinery in CML.
Monte Carlo simulation of resonance effects of electron transport in a spatially modulated electric field in Ar, N2 and their mixtures The relaxation of the distribution function of the electrons drifting under the influence of a homogeneous electric field in noble gases is known to take place over an extended spatial domain at ‘intermediate’ values of the reduced electric field, E/N. We investigate the transport of electrons in Ar and N2 gases, as well as in their mixtures at such E/N values (∼10–40 Td). After discussing briefly the basic scenario of relaxation in a homogeneous electric field, the major part of work concentrates on the properties of transport in an electric field that is spatially modulated within a finite region that obeys periodic boundaries. The spatial distribution of the mean velocity, the mean energy, and the density of the electrons, the importance of the excitation channels, as well as the electron energy distribution function are obtained from Monte Carlo simulations for various lengths of the computational domain, at different mean values and degrees of modulation of the reduced electric field. At low modulations, the spatial profiles of the mean velocity and mean energy are nearly harmonic, however their phases with respect to the electric field perturbation exhibit a complex behaviour as a function of the parameters. With increasing modulation, an increasing higher harmonic content of these profiles is observed and at high modulations where an electric field reversal occurs, we observe trapping of a significant population of the electrons. The effect of mixing a molecular gas, N2, to Ar on the transport characteristics is also examined. Transition to local transport at high N2 admixture concentrations and long spatial domains is observed. Introduction Under hydrodynamic conditions, the velocity distribution function (VDF) of electrons subjected to a homogeneous and stationary electric field is a unique function of the reduced electric field, E/N. Up to moderate values of E/N (typically up to few hundred Townsends, 1 Td = 10 −21 V m 2 ) the VDF of electrons in noble gases generally exhibits only a small anisotropy, i.e. it can be well approximated by an isotropic part and small anisotropic part. This behaviour, which is the basis of the two-term approximation, stems from the effect of frequent elastic collisions of the electrons with the gas atoms that randomize the directions of velocities and thus their characteristic thermal velocity strongly exceeds the average (directed) velocity. In the hydrodynamic regime, the energy gain and loss of the electrons compensate each other exactly, however, in different ways depending on the strength of the reduced electric field . Considering noble gases, at very low E/N (≲10 Td) the energy loss of electrons is mostly due to elastic collisions. In such events, a fraction of their energy proportional to the electron/atom mass ratio (m/M) is lost. For an electron energy of 1 eV, e.g. such a collision results in a loss of ≈ 10 −5 eV, in the case of argon gas. At somewhat higher E/N values (∼tens of Td-s), where the energy of the electrons reaches the threshold for inelastic processes (∼10 eV), the main channels of the energy loss become the excitation processes. At such conditions the lowest excited levels can be reached first. With increasing E/N, the number of these channels increases and at some point ionization becomes possible, too. Above ∼100 Td, the latter process is usually appreciable. The scenario described above for noble gases changes notably in the case of molecular gases. There, due to the various (rotational and vibrational) excitation processes having low threshold energies the energy dissipation frequency at low energies is much higher as compared to the case of noble gases. The spatial evolution of the electron VDF in nonhydrodynamic regimes is also remarkably different for the E/N rages distinguished above . Non-hydrodynamic transport establishes under various conditions: (a) when the electric field varies over a characteristic length that is short compared to the mean free path of the electrons, (b) when the temporal change of the field is quicker than the mean time between electron-neutral collisions, (c) in the presence of sources/sinks of electrons and/or (d) in the presence of boundaries. In the latter case, even in the presence of a homogeneous and stationary electric field, the VDF and the transport parameters (mean velocity, mean energy, etc) of the electrons vary in space. A classical example of this scenario is an electrode that emits electrons with a certain initial velocity distribution that is defined by the emission process (e.g. photoemission). This VDF is clearly different from that acquired by the electrons under hydrodynamic conditions for the given E/N that is present in the volume considered. This implies that a transition region ('equilibration region') must exist within which the VDF transforms from its initial shape to the equilibrium shape, see e.g . The fundamental experiment of Franck and Hertz , which provided evidence for the existence of quantised energy levels of the atoms, actually utilised this effect. Specifically, this experiment focused on the early phase of the equilibration, where a prominent periodic structure in the mean energy of the electrons was present. The experiment was operated in the 'window' of E/N values where such behaviour prevails. The electron kinetics in this experiment has been investigated in a number of works, e.g. . We note that both at low and high E/N values no, or less prominent periodic structures can be observed, respectively, due to the smooth transition mediated by elastic collisions, and due to the rapid randomisation of the electron energy in the presence of a high number of inelastic energy loss channels and the possibility of ionization that creates additional particles. The extended spatial structures formed at intermediate E/N values have attracted much attention . The equilibration of an electron swarm in argon gas at E/N values at few tens of Td-s was as well observed experimentally recently in a scanning drift tube apparatus that makes it possible to follow the spatio-temporal development of electron swarms. Under the conditions, where the electric field is spatially modulated a strong modulation of the electron transport characteristics appears at some E/N values as revealed in studies based on the solution of the Boltzmann equation by Golubovsky et al . In the presence of appreciable charge density, the spatial variation of the transport characteristics can itself give rise to a perturbation of the electric field. As this interplay may be self-amplifying, stationary or moving spatial structures can show up in discharge plasmas. Such structures, often termed as 'striations' have thoroughly been investigated for several decades, see, e.g. the review by Kolobov . The early studies of striations based on analytic approaches have later been replaced by kinetic treatment of the electrons . Striations, caused by different mechanisms, are present in a variety of plasma sources, like dc glow discharges , plasma display panels , and inductively coupled radiofrequency discharges . Despite the extensive work done in this field , the complex dynamics of striations is still subject of intensive current research, e.g. . Most of the investigations of the electron kinetics have been based on the solution of the Boltzmann equation , particle based simulations were used only in a fewer number of cases. As examples for the latter, studies of striations in inductively coupled and capacitively coupled electronegative plasmas, and in ionization waves in barrier discharges , as well as the most recent studies of the spatial relaxation of the mean electron energy in inert gases and their mixtures in a uniform electric field may be mentioned. Due to the rapid development of computing hardware such particle based methods became equally suited as the numerical solutions of the Boltzmann equation, for studies of particle transport in spatially varying fields due to their ability to capture fully the nonlocal kinetic effects appearing in various settings. In this paper, we use Monte Carlo simulation (see e.g. ) to investigate certain aspects of the transport of electrons in spatially varying electric fields. The simulation method is discussed in section 2. In section 3, we briefly introduce some important physical quantities, the characteristic momentum and energy relaxation frequencies and lengths, that help understanding the relaxation and resonance effects to be discussed later on. The presentation of the results in section 4 starts with illustrating the spatial relaxation of electron swarms in Ar and in Ar-N 2 mixtures in a homogeneous electric field. These findings aid choosing the proper parameter range of the reduced electric field for which the studies of the transport in a periodically modulated electric field are conducted. The results of these simulations for Ar are presented in section 4.2. We analyse the spatial profiles of the mean electron energy, velocity and density for various values of the average E/N and illustrate the effect of the modulation of E/N on these profiles. Additionally, we investigate the spatial distribution of the electron energy distribution function and the distribution of the excitation channels (reaction rates). Fourier analysis of the profiles of the mean velocity and energy (a) reveals the phase between them and the modulated field (at low modulation) and (b) shows how their harmonic content increases at high modulation. In section 4.3 the effect of an N 2 admixture on the electron transport characteristics is addressed. A brief summary is given in section 5. Simulation method Our studies are based on the Monte Carlo (MC) description of the motion of electrons in (a) homogeneous and (b) spatially modulated electric field E(x). We use the well-established MC algorithm for charged particle transport (e.g. ) and solve the discretised version of the equation of the motion of the electrons, using the Velocity-Verlet method, with constant time steps of ∆t = 1 ps. Here, m and q are the mass and the charge of the electrons. The probability of a collision to occur during the ∆t time step is: where the total cross section σ tot is the sum of the cross sections of all possible collision processes. Whenever a collision occurs, its type is chosen randomly, taking into account the values of all cross sections at the actual velocity of the colliding electron. The electron-Ar atom cross section set is based on , includes the elastic momentum transfer cross section, excitation to 25 distinct Ar levels, and the ionisation cross section. The cross section set for electron-N 2 molecule collisions are taken from . The set includes the elastic momentum transfer cross section, excitation to several vibrational and electronic states of N 2 , as well as the ionisation cross section. As calculations are performed for E/N ≫ 1 Td, the cross sections for rotational excitations are not included in the present study. Ionisation is treated here as a number conserving process, i.e. just like an excitation event, to ensure that the number of electrons does not grow in the simulations. This approach is justified at the E/N values considered here, where ionisation has a very small rate (which is confirmed by the results). This simplification could easily be omitted when necessary, e.g. at higher E/N values. All collisions are assumed to result in isotropic scattering, the thermal motion of the background gas atoms is disregarded (i.e. the 'cold gas approximation' is adopted). Collisions are described in the centre-of-mass coordinate In the case of a modulated electric field, the electrons' motion is followed in a simulation box having a width L, with periodic boundaries. The system is exposed to a sinusoidally spatially modulated electric field as shown in (b) for the case of an average reduced electric field of (E/N) 0 = 20 Td (indicated by the dashed horizontal line) and a modulation depth M = 0.1. frame. The velocity of this frame (w) and the relative velocity of the collision partners (g) are calculated. As known from the classical kinematic treatment of the two-body interaction, elastic collisions change only direction of the relative velocity, while in inelastic collisions its magnitude is decreased as well by an amount that is defined by the excitation energy. The value of the relative velocity vector obtained this way, together with the velocity of the centre-of-mass allows computation of the post-collision velocity of the electrons. The electrons do not interact with each other, i.e. we study classical swarm conditions at low charged particle density. The simulations are conducted at a pressure of p = 100 Pa and at the ambient temperature of T g = 300 K, i.e. at a neutral density of N ∼ = 2.42 × 10 16 cm −3 . Except for the study of swarm relaxation in a homogeneous electric field, the particles are restricted to move within a simulation domain that obeys periodic boundary conditions, as shown in figure 1(a). Particles leaving this domain in the ±x directions are re-injected into the domain at the opposite sides. The periodic boundaries emulate an infinite system with spatially periodic modulation of E/N. The electric field points in the −x direction, consequently, the electrons drift in the +x direction. In the following, we omit the negative sign of E. In the case of a modulated electric field, the form is adopted, where E 0 is spatial average of the electric field, M ⩾ 0 is the modulation depth, and k = 2π/L, with L being the length of the spatial period of modulation (see figure 1 At a given (E/N) 0 this relation connects the length of the computational domain and the voltage drop over this domain. We primarily examine the range of the parameters (E/N) 0 and L, where the energy corresponding to the voltage drop over the simulation domain, q U, is in the order of the excitation levels of Ar, the lowest being 11.55 eV. We present results for the spatial profiles of the mean electron velocity v(x), the mean energy ε(x), the electron density n(x), the electron energy distribution function (EEDF) f (x, ε). These characteristics are studied as a function of the reduced electric field and the length of the computation cell (that equals the wavelength of the modulation of E(x).) They are 'measured' within 200 slabs with equal width, covering the simulation domain of length L. A lower spatial resolution is used for the analysis of the excitation rates and of the spatial distribution of the EEDF, to ensure a better statistics. At low values of modulation, the system is expected to give a linear response for the space-dependent scalar quantities, i.e. the latter are foreseen to exhibit a harmonic spatial profile. With increasing perturbation, a non-linear response is expected to establish. Taking as an example the mean velocity v(x), the harmonic content as well as the phase shift of the individual harmonics contributing the spatial profile can be obtained via Fourier analysis, which allows to construct where v s and φ s are, respectively, the amplitude and the phase delay of the sth harmonic. This analysis helps, e.g. identifying the conditions when local transport is approached: in the case of low modulation (as long as v and ε are monotonically increasing functions of E/N) we expect v s → 0, ∀s > 1 and φ 1 → 0, as E(x) contains only a dc component and one (perturbing) harmonic with s = 1. Any deviation from this behaviour is the signature of the non-local character of the transport and the non-linear response of the system to the electric field perturbation. We note that this analysis of the phase shifts of the 'macroscopic quantities', like v(x) and ε(x) with respect to E(x) does not offer an explanation for the resonance effects, as these are kinetic by nature. We also need to notice that the dependence of v on E/N is not necessarily monotonic, this scenario is called Negative Differential Conductivity (NDC) , which typically occurs in gas mixtures, including Ar-N 2 mixtures that are also studied here . For the case of homogeneous electric field, the EEDF resulting from our simulation code has been cross checked with that obtained from the Bolsig+ Boltzmann solver . Relaxation frequencies and lengths Before presenting our results it is useful to illustrate the behaviour of few important quantities that have major influence on the relaxation and resonance effects to be discussed. These are the momentum and energy dissipation frequencies, ν m and ν e , respectively, as well as the mean free path λ m and the energy relaxation length λ e . We have computed these quantities according to the expressions given in and display them in figure 2. Panel (a) shows the energy dissipation frequency (ν e ) and the momentum dissipation frequency (ν e ) for both Ar and N 2 . We find ν m to be significantly higher than ν e over the whole range of energies considered. ν e is especially low for Ar below the threshold energy for inelastic loss channels, as in elastic collisions the fractional energy loss of the electrons is in the order of the electron/atom mass ratio, as already mentioned in section 1. Rapid changes of ν e with ε can be observed for both gases. Whenever the energy distribution of the electrons spans a range that includes such a change, parts of the electron population with different energies will behave dissimilar in terms of energy relaxation, as explained in . The momentum relaxation frequency does not exhibit abrupt changes as a function of the energy, except for Ar at low energies, due to the Ramsauer-Townsend minimum in the elastic collision cross section. Regarding the relaxation lengths in pure gases, figure 2(b) reveals that the energy relaxation length (λ e ) exceeds considerably the mean free path (λ m ). Below the inelastic excitation threshold in Ar, e.g. their ratio amounts about two orders of magnitude. Under such conditions the relaxation of the energy in a swarm is expected to take place over an extended spatial scale, where a high number of collisions is required for equilibration. The difference between λ e and λ m for Ar decreases as the energy is increased, at 20 eV the ratio between them drops to a factor of two. As around this energy the sum of inelastic cross sections approaches the value of the elastic momentum transfer cross section energy relaxation becomes efficient. As to N 2 , λ e and λ m are relatively close to each other, meaning that energy relaxation takes place over a few free flight lengths of the electrons, except at low energies (below 2 eV) and within the 3 eV ⩽ ε ⩽ 8 eV interval, where the collision cross sections are low. Due to the large disparity of the relaxation frequencies and lengths in Ar vs. in N 2 , even a small amount of the latter causes a significant change of these parameters, as illustrated in figure 2(c) for the case of λ e . With respect to the case of pure Ar the strongest decrease of λ e occurs in the 2 eV ⩽ ε ⩽ 3 eV and 8 eV ⩽ ε ⩽ 11 eV domains of the electron energy as a result of the addition of N 2 to Ar. This is caused by, respectively, the vibrational and electronic excitation of N 2 molecules. In the first domain, even 1% of N 2 decreases λ e by a factor of 10 as it can be seen in figure 2(c). At electron energies above ≈ 15 eV the effect of N 2 on λ e becomes negligible due to the availability of a high number of inelastic loss channels. Homogeneous electric field To illustrate the equilibration of electron swarms in a homogeneous electric field, in figure 3 we depict the mean velocity and the mean energy of the electrons for a steady state scenario when electrons are continuously emitted from an electrode at x = 0 and drift in the gas. In this simulation, the electrons are emitted with an initial energy of 1 eV and an initial velocity directed towards the x direction. Such an initial velocity distribution is very clearly far from the equilibrium distribution that is expected to be nearly isotropic with a small drift component. Figures 3(a) and (b) show the case of pure Ar. Here, the ensemble of the electrons requires rather significant 'flight' lengths to acquire a steady-state mean velocity, for the whole range of E/N covered. The periodic structures seen during this equilibration phase originate from repetitive energy gain-energy loss cycles of the electrons: gain occurs due to acceleration in the electric field, loss occurs primarily due to inelastic collisions. This is especially well seen in the graph of ε(x) for the 20 Td case, for which the x scale is 10× zoomed (red dashed line): here saw-tooth like patterns appear, expressing the slow energy gain and rapid energy loss. While the peaks of this function appear nearly at the same position as those of v(x), the functional forms appear to be significantly different. The oscillations of the mean velocity persist for the longest spatial domain for the 20 Td case, both at lower and higher fields we observe equilibration on a shorter length scale. Figures 3(c) and (d) illustrate the behaviour of the swarm in Ar-N 2 mixtures, as a function of the N 2 concentration, at fixed E/N = 20 Td. The equilibration of the transport takes place on a much shorter length scale, as compared to that in pure Ar. Already 1% of N 2 shrinks the equilibration domain by a factor of ∼10. At higher admixture concentrations equilibrium becomes close to monotonic. This behaviour originates from the wide range of energies (due to processes with low threshold energies, e.g. vibrational channels) of inelastic loss channels in N 2 as compared to Ar. We can note that an increasing N 2 concentration results in a remarkable increase of the steadystate mean velocity and a remarkable decrease of the steadystate mean energy. Whenever pronounced structures in transport coefficients are seen, it is expected that in a spatially modulated electric field resonances may appear at certain conditions, as it has been recognised in several earlier studies, e.g. . This is indeed the foreseen behaviour in pure Ar, while N 2 is expected to have a converse influence on this effect. The data presented above help setting the proper range of E/N for the studies of the transport in spatially modulated fields and the timing of the data collection in the simulations (see below). Transport in periodically modulated electric field in argon Below, we present the results for the transport properties in spatially modulated electric field for pure Ar gas. The simulations are initialized by placing N = 2000-20 000 electrons (depending on the type of the 'measurement') at random positions within the simulation box (of length L) with a velocity v 0 = 0. First, the electrons are traced for ∆T 1 = 900 µs, and subsequently for an additional ∆T 2 = 100 µs, during which the transport data are collected (unless stated otherwise). This timing ensures the decay of the initial transients: at 20 Td, e.g. the relaxation length seen in figure 3 is ∼1 m and the mean stationary velocity is about v 0 ≈ 1. The characteristics of the spatial profile of the quantities shown in figures 4(a)-(c) (i.e. the amplitude and shape of the curves as well as the positions of their extrema) vary in a complicated manner with L. As regards to v, in the limit of small L values we observe a weak modulation around the equilibrium value of v 0 ≈ 1.8 × 10 4 m s −1 , with a peak close to the edge of the cell. A notable increase of the amplitude and a shift of the maximum to higher x/L appear at L = 2.6 cm, while the highest modulation is observed at L = 2.7 cm, which is, however, accompanied by a 'backward' shift of the profile. At L > 2.7 cm we observe a decreasing amplitude of the profile, with maxima approaching x/L = 0. For the given strength of modulation, M = 0.2, the higher harmonic content of the profiles is limited. Therefore the strength of the 'response' of v to the perturbing electric field variation is characterized by the amplitude and the phase of the first Fourier component, v 1 and φ 1 , in figure 4(d). This figure confirms the visual observation of a resonance at L = 2.7 cm (corresponding to U = 13.07 V), where v 1 exhibits a sharp peak. The phase of the profile is near −80 • both at low and high L and shows a peak at φ 1 ≈ 0 • at L = 2.6 cm. As there are no sources and losses in the system, nv = const. holds due to flux conservation (∇ · (nv) = 0). Therefore, the electron density obtained from the simulation (and shown in figure 4(b) is directly related to the mean velocity. The dependence of the spatial profile of the mean electron energy, ε(x) as a function of L is similar to that of the mean velocity, as it can be seen in figure 4(c). The phases of the v(x) and the ε(x) profiles are, however, quite different as revealed quantitatively in figure 4(d). The phase of the latter exhibits a monotonic decrease with the increase of L and passes through 0 • at L = 2.6 cm, near the resonance. The Electron Energy Distribution Function (EEDF) exhibits marked changes as a function of the position when M > 0. An example of this is shown in figure 5 for (E/N) 0 = 20 Td and M = 0.2, at L = 2.7 cm, i.e. for the resonant case. It is remarkable that the strongest high-energy tail of the EEDF develops at the spatial position of x/L = 0.4, where, actually the mean energy has a minimum (see figure 4(b)). This is not a contradiction as low-energy part of the EEDF at this position is also highly populated. On the other hand, this observation points out the importance of the whole EEDF in determining the characteristics of the transport. Revoking figure 2(b) we can note that the EEDF-s are populated at energies both below and above the energy where a sudden drop in the energy relaxation length occurs. Therefore, as pointed out in the low-and high-energy parts of the electron population behave in a quite different ways at this resonance. Below the inelastic excitation threshold of Ar (11.55 eV) λ e is in the order of several cm-s while this drops to several mm-s when the energy is higher than this threshold. The long λ e at low ε assists the electrons to gain energy from the field, without dissipating it. The short λ e at ε > 11.55 eV, on the other hand, allows the electrons to dissipate their energy quickly. Actually, at ε = 11.55 eV, λ e =2.79 cm. The energy accumulation for the resonant case (L = 2.7 cm) is clearly indicated by the slanted structure in panel (b) of figure 6 that shows the complete spatial evolution of the EEDF. Remains of this structure are also seen in figures 6(a) and (c), however, these are far less pronounced. The velocity distribution function of the electrons , as a function of the axial and radial components of the velocity, f(v x , v r ), is plotted in figure 7 at four distinct locations within the simulation cell, for the conditions L = 2.7 cm, M = 0.2, and (E/N) 0 = 20 Td. The VDF at x/L = 0 (and at the equivalent position of x/L = 1) exhibits a high population of particles with velocities between 1.5 × 10 6 and 1.8 × 10 6 m s −1 , a small additional peak at low velocities shows that some electrons already suffered a significant energy loss around these positions. At x/L = 0.25 ( figure 7(b)) most of the electrons have velocities below ≈ 1 × 10 6 m s −1 , following their inelastic collisions. At the higher x/L values we observe an expanding ring in the velocity distribution, which is caused by the fact that electrons re-gain energy from the electric field (see (figures 7(c) and (d))). Generally, only a quite small anisotropy can be observed at any position, confirming the expected behaviour that at low E/N the drift velocity of the electrons is much smaller compared to their random (thermal) speed. The presence of the modulation of the electric field obviously does not change this general behaviour. The effect of the modulation depth, M, on the spatial variation of the mean velocity is depicted in figure 8(a). At the lower values of L, the v(x) curves are nearly harmonic, an increasing anharmonicity can be observed with increasing modulation. Figure 8 Counting the number of the different electron-Ar atom reactions spatially resolved allows construction of a matrix that shows the collision frequencies associated with the various collision processes. The computational results are shown in figure 9 for the case of (E/N) 0 = 20 Td and L = 2.7 cm, obtained at M = 0.0 (panel a) and M = 0.2 (panel b). In these plots, excitation processes are identified by numbers 1…25, ionisation is process 26. The number of elastic collisions is orders of magnitude higher, thus this (process 0) is omitted from the plots. The highest excitation rates are observed (in both cases) for the four lowest excited levels of Ar, for processes 1-4, corresponding to excitation to the 1s 5 , 1s 4 , 1s 3 , and 1s 2 levels (Paschen notation), respectively. The energy of these levels is between 11.55 and 11.83 eV. At M = 0, significant rates are also observed for the whole domain for processes 5 and 6 (2p 10 and 2p 9 levels), 8-10 (2p 7,6,5,4 levels), and 13-15 (2p 1 , 3d 5,6 and 3d 3 levels). The excitation threshold of the latter is 13.90 eV. Ionisation (process 26) is not present with an appreciable rate, justifying our approach of treating this process as a number conserving one, for the rare events of occurrence. At M = 0.0 ( figure 9(a)) the spatial distribution of the excitation events is homogeneous, as expected. At M = 0.2, however, the modulation of the electric field causes a major perturbation to the excitations . We find that (i) the majority of excitation events is concentrated within the 0.25 ⩽ x/L ⩽ 0.6 spatial domain with a pronounced maximum near x/L = 0.4, where the most notable high energy tail for the EEDF was found for the same conditions (see figure 5) and (ii) the acceleration of the electrons in the modulated field also opens excitation channels with higher thresholds: in figure 9(b) we observe processes with appreciable rates up to #18, which corresponds to levels 3d ′ ′ 1 and 2s 5 , with a threshold energy of 14.06 eV . The further increase of the modulation depth, e.g. to M = 0.5, results in a slightly increased spatial confinement of the excitation events. While new higher-threshold levels get populated as compared to lower M, it is remarkable that a depletion of the excitation rates of the lowestthreshold 1s 2,3,4,5 levels (processes 1. . . 4) is also observed in the 0.75 ⩽ x/L ⩽ 1 domain because of the prominent energy deposition of the electrons in the 0.25 ⩽ x/L ⩽ 0.6 domain. While in the cases described before, the modulation was kept at moderate levels, here we briefly examine the case of higher modulation, when the electric field changes sign within a certain domain (at M > 1). As the presence of a region with a reversed electric field gives rise to a potential well, electrons can accumulate within these regions. For (E/N) 0 = 20 Td, L = 2.7 cm, and M = 1.1, e.g. the depth of this potential well is ≈ 0.1 V. As electrons may undergo such collisions in these regions when their remaining kinetic energy is less than 0.1 eV, such electrons will be trapped as their energy cannot increase anymore to overcome the barrier. Consequently, after a sufficiently long time all electrons are expected to be trapped in our simulation. While the presence of the reversed field bears some similarity with the case of the negative glow region of dc glow discharges , in that setting fast electrons arriving from the sheath can interact with the trapped population and can eventually increase the energy of some of the electrons, enabling them this way to get released from the trap. This effect is the result of Coulomb collisions, which are however, not included in the present simulation. Nonetheless, our simulations can follow the time dependence of the trapping phenomenon. This is illustrated in figures 10(a)-(c), where the results (for the mean velocity, mean energy and normalised density) are shown as a function of time. The data were collected in 100 µs wide time windows at different start times, as indicated. The graphs indeed exhibit pronounced structures around x/L = 0.75, where the reversed electric field peaks. They show that a slow change follows after an initial high rate of trapping. From this it follows that the spatial modulation of E actually slows down the trapping process by 'moving' most of the inelastic collisions from a random distribution to spatial positions that exclude the domain of reversed field, as shown in figure 9. In accordance with this it is also interesting to note that the least significant trapping for otherwise same conditions is observed for the resonant case of L = 2.7 cm, as revealed in figure 10(d). For other values of L, we observe a much more significant collection of the electrons within the region of the field reversal and more significant depletion of the density outside this domain. As electrons are less likely to undergo inelastic collisions in the regions with reversed electric field, complete trapping takes place on a time scale much longer than accessible by our simulations. Inclusion of the Coulomb collisions and/or thermal contribution of the background gas are clearly necessary to model correctly the stationary state of our system at such high modulations. component v 1 , changes however, in the same way as it was found previously for 20 Td. This is presented in figure 12, where φ 1 is shown as a function of the voltage drop U (in order to make the data obtained at different (E/N) 0 values comparable). The maximum of the phase occurs at a higher voltage drop (higher L) compared to the higher fields. At (E/N) 0 = 40 Td, the behaviour of the phase is very similar to that at 20 Td (a strong peak at ≈ 12.5 V). The inspection of the amplitude of v(x) in figure 11(b) does not show a strong resonance unlike in the case of 20 Td. This may be explained by the higher number of inelastic loss channels at an expanded energy range of the electrons at the higher accelerating field. Note, that at E/N = 40 Td a faster spatial relaxation was found also in the homogeneous field, as compared to 20 Td, see section 4.1. Transport in periodically modulated electric field in Ar-N 2 mixtures and in N 2 As discussed above, the pronounced response of the electron transport parameters on the spatial modulation of the accelerating electric field in argon gas is due to the fact that the number of energy loss channels is limited (excitation predominantly occurs to a few excited states as confirmed by the results presented in the previous section). As in a molecular gas, like N 2 the possible values of the energy loss in a collision span a much wider domain as compared to atomic gases, the response of the system to the modulated electric field is expected to diminish when even small amounts of molecular gases are added to Ar. Figure 13(a) shows v(x)/v 0 for various percentages of N 2 between 0% and 100%, for (E/N) 0 = 20 Td, M = 0.2, and L = 2.7 cm. The data are normalised by the equilibrium velocity v 0 , which varies (as shown in figure 13(c)) as a function of the N 2 content in the gas mixture. (In the case of 0% N 2 the data are the same as shown in figure 4). With an increasing N 2 percentage the phase of the first harmonic of v(x) first slightly decreases at low nitrogen content, and then increases rapidly to φ 1 ≈ −20 • above 5% N 2 (see figure 13(d)). The velocity profiles practically overlap at ⩾ 40% N 2 content indicating that excitation of Ar is strongly suppressed at these molecular gas concentrations. Some of the data points belong to the parameter range where Negative Differential Conductivity in the Ar-N 2 mixture is present. As revealed from figure 4 of , NDC at E/N = 20 Td occurs between N 2 concentrations of approx. 5% and 15%. This effect may have an influence on the behaviour of φ 1 , clarification of this is, however, left for future work that needs to consider a broader domain of the parameters especially the spatial wavelength of the modulation. The addition of N 2 efficiently cools the electrons, as the profiles of the mean energy, shown in figure 13(b) confirm. Besides the value of ε the modulation of its spatial profile decreases as well and the phase of the profile changes also significantly as shown in figure 13(d). The presence of N 2 in the mixture has a dramatic effects on the EEDF as well, as shown in figure 14. Already at 1% N 2 content, the marked spatial modulation of the EEDF observed in pure Ar (see figure 6(b)) vanishes almost completely. With the addition of more N 2 , the low energy part of the EDDF gets gradually more populated as a result of the low-thresholdenergy processes in N 2 . Finally we present results for the case of pure N 2 . Figures 15(a) and (b) display spatial profiles of the mean electron velocity as a function of L, while panel (c) of the At large L (i.e. at L >2 cm), both the v(x) and ε(x) profiles approximate the spatial dependence of the electric field. For these conditions, the phases of the first harmonic of both of these profiles approaches zero, as it is revealed from figure 15(d). These are signatures of the local character of the transport. For large L, we indeed find a very slight spatial modulation of the EEDF as well, as it can be seen in figure 16(c) for L = 4 cm. The only observable signature there is a small modulation of the high energy cutoff with x/L, around ε ≈ 2.5 eV. The vast majority of the electrons have energies less than 2 eV. For such energies, as figure 2(b) reveals, the energy relaxation length is in the order of λ e ≈ 1-2 cm. For any L exceeding this value we expect that the swarm properties reflect the local value of the electric field, as it is actually confirmed in figure 15(a). Summary In this work, we have investigated via Monte Carlo simulation the characteristics of electron transport in a stationary, spatially modulated electric field. The computations have been executed for Ar and N 2 gases and their mixtures at (spatially averaged) reduced electric fields in the 10-40 Td range. Particles have been traced in a finite spatial region subjected to periodic boundary conditions. Within the range of the reduced electric field considered, a strong response of the transport parameters to the electric field modulation was observed. At low modulation depths, the spatial profiles of the mean electron velocity and energy exhibited a harmonic shape. The phase angle between the electric field and the above quantities, as well as the harmonic content of the latter at higher modulation depths were revealed by Fourier analysis. All the quantities analysed showed highly nonlocal transport, except for the case of pure N 2 at long modulation wavelength, where signatures of local electron transport were observed. At conditions, where the high modulation depth of E/N resulted in the appearance of a region where the direction of the electric field is reversed, we observed trapping of the electrons. The stationary case, where all electrons are supposed to be trapped was not reached due to the slow accumulation of the electrons. The latter was found to be caused by the fact that the modulation of the electric field favours inelastic collisions (that represent high energy loss) outside the domain of the reversed field. For a realistic description of any experimental setting the inclusion of either Coulomb or thermal collisions is necessary. Understanding the transport characteristics requires the analysis of the spatial variation of the electron energy distribution function (EEDF). We have computed this function for various parameter combinations and have found pronounced structures at the resonance condition where the potential drop over the simulation box is ≈ 13 V in pure Ar. The strongest resonance was found for (E/N) 0 = 20 Td. At lower reduced electric field, elastic collisions play a more prominent role in the electron energy balance, while at higher field more excitation channels are open due to the higher electron energy, and this adversely affects the synchronisation of the kinetics of individual electrons. The analysis of the rates of the inelastic collision processes at 20 Td showed that for these conditions only few levels of the Ar atom are preferentially excited. Even small amounts of N 2 admixtures were found to lead to the vanishing of the structures in the EEDF due to the wider range of excitation energies of the N 2 molecule. Further directions of the present study include (a) the clarification of the combined effects of the modulated electric field and the Negative Differential Conductivity on the transport characteristics in the case of Ar-N 2 mixtures, (b) investigations of the transport properties in the presence of non-sinusoidal perturbation of the electric field strength, (c) inclusion of Coulomb collisions for an accurate prediction of the properties of the trapped part of the electron population in regions with reversed electric field, (d) the introduction of the self-consistent computation of the electric field distribution from the perturbed densities of the electrons via the Poisson equation in order to predict the range of existence of standing striations, and (e) extending the range of E/N to higher values, to observe the effects of appreciable ionisation on the characteristics of the electron transport.
package mysqlflags import ( "bufio" "bytes" "database/sql" "fmt" "io" "log" "os" "os/exec" "reflect" "regexp" "strings" "time" "github.com/kazeburo/mapstructure" "github.com/vaughan0/go-ini" ) // MyOpts mysql connection related flags used with go-flags type MyOpts struct { MySQLDefaultsExtraFile string `long:"defaults-extra-file" description:"path to defaults-extra-file"` MySQLSocket string `long:"mysql-socket" description:"path to mysql listen sock"` MySQLHost string `short:"H" long:"host" default:"localhost" description:"Hostname"` MySQLPort string `short:"p" long:"port" default:"3306" description:"Port"` MySQLUser string `short:"u" long:"user" default:"root" description:"Username"` MySQLPass *string `short:"P" long:"password" description:"Password"` MySQLDBName string `long:"database" default:"" description:"database name connect to"` MySQLDSNParams map[string]string } type dsn struct { Username string Password string Hostname string Port string Socket string DefaultDB string Params map[string]string } func newDSN() dsn { dsn := dsn{} dsn.Params = map[string]string{} return dsn } func (dsn *dsn) String() string { dsnString := "" if dsn.Socket != "" { dsnString = fmt.Sprintf("%s:%s@unix(%s)", dsn.Username, dsn.Password, dsn.Socket, ) } else { if dsn.Hostname == "" { dsn.Hostname = "localhost" } if dsn.Port == "" { dsn.Port = "3306" } dsnString = fmt.Sprintf("%s:%s@tcp(%s:%s)", dsn.Username, dsn.Password, dsn.Hostname, dsn.Port, ) } dsnString += "/" + dsn.DefaultDB p := []string{} for k, v := range dsn.Params { p = append(p, fmt.Sprintf("%s=%s", k, v)) } params := strings.Join(p, "&") if params != "" { dsnString += "?" + params } return dsnString } var defautlsRegexp = regexp.MustCompile("^--(.+?)=(.*)") func parseMySQLDefaults(r io.Reader) dsn { dsn := newDSN() scanner := bufio.NewScanner(r) for scanner.Scan() { b := scanner.Bytes() res := defautlsRegexp.FindAllSubmatch(b, -1) if res != nil { key := string(res[0][1]) val := string(res[0][2]) switch key { case "user": dsn.Username = val case "password": dsn.Password = <PASSWORD> case "socket": dsn.Socket = val case "host": dsn.Hostname = val case "port": dsn.Port = val } } } if dsn.Socket != "" { dsn.Port = "" dsn.Hostname = "" } if dsn.Hostname == "" && dsn.Socket == "" { dsn.Hostname = "localhost" } return dsn } func defaults() dsn { params := [][]string{ {"-s", "client"}, {"client"}, } for _, param := range params { outout, err := exec.Command("my_print_defaults", param...).Output() if err != nil { continue } return parseMySQLDefaults(bytes.NewReader(outout)) } return newDSN() } // CreateDSN creates DSN from Opts. omit timeout parameter when timeout is 0 func CreateDSN(opts MyOpts, timeout time.Duration, debug bool) (string, error) { dsn := defaults() if opts.MySQLDefaultsExtraFile != "" { i, err := ini.LoadFile(opts.MySQLDefaultsExtraFile) if err != nil { return "", err } section := i.Section("client") user, ok := section["user"] if ok { dsn.Username = user } password, ok := section["password"] if ok { dsn.Password = password } socket, ok := section["socket"] if ok { dsn.Socket = socket } host, ok := section["host"] if ok { dsn.Hostname = host } port, ok := section["port"] if ok { dsn.Port = port } } if opts.MySQLHost != "" { dsn.Hostname = opts.MySQLHost } if opts.MySQLPort != "" { dsn.Port = opts.MySQLPort } if opts.MySQLUser != "" { dsn.Username = opts.MySQLUser } if opts.MySQLPass != nil { dsn.Password = *opts.MySQLPass } if opts.MySQLSocket != "" { dsn.Socket = opts.MySQLSocket } if dsn.Username == "" { dsn.Username = os.Getenv("USER") } dsn.DefaultDB = opts.MySQLDBName if timeout > 0 { dsn.Params["timeout"] = timeout.String() } if opts.MySQLDSNParams != nil { for k, v := range opts.MySQLDSNParams { dsn.Params[k] = v } } dsnString := dsn.String() if debug { dsn.Password = "<PASSWORD>" log.Printf("DSN: %s", dsn.String()) } return dsnString, nil } // OpenDB opens MySQL connections from Opts func OpenDB(opts MyOpts, timeout time.Duration, debug bool) (*sql.DB, error) { dsn, err := CreateDSN(opts, timeout, debug) if err != nil { return nil, err } db, err := sql.Open("mysql", dsn) if err != nil { return nil, err } return db, nil } // Bool mysql variables boolean type Bool struct { original string } // True true when the original string func (b Bool) String() string { return b.original } // Yes return true when the original is Yes or yes or YES func (b Bool) Yes() bool { switch b.original { case "Yes", "yes", "YES", "On", "ON", "on": return true default: return false } } // QueryMap has rows map and error type QueryMap struct { err error result []map[string]string } // Scan converts rows to Struct func (qm *QueryMap) Scan(dest interface{}) error { if qm.err != nil { return qm.err } destRv := reflect.ValueOf(dest) if destRv.Kind() != reflect.Ptr { return fmt.Errorf("not a pointer: %v", dest) } destRv = destRv.Elem() var input interface{} if destRv.Kind() != reflect.Slice { if len(qm.result) == 0 { return fmt.Errorf("no sql result") } input = qm.result[0] } else { input = qm.result } decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) { if f.Kind() == reflect.String && t.Kind() == reflect.Bool { if typed, ok := v.(string); ok { switch typed { case "Yes", "yes", "YES", "On", "ON", "on": return "True", nil default: return "False", nil } } } else if f.Kind() == reflect.String && t.String() == "mysqlflags.Bool" { if typed, ok := v.(string); ok { return Bool{typed}, nil } } return v, nil } config := &mapstructure.DecoderConfig{ WeaklyTypedInput: true, ErrorUnsetFields: true, Result: dest, TagName: "mysqlvar", DecodeHook: decodeHook, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } err = decoder.Decode(input) if err != nil { return err } return nil } // Query does exec show statement and return QueryMap for Scan func Query(db *sql.DB, query string, args ...interface{}) *QueryMap { rows, err := db.Query(query, args...) if err != nil { return &QueryMap{err: err} } defer rows.Close() cols, err := rows.Columns() if err != nil { return &QueryMap{err: err} } c := make([]string, len(cols)) for i, v := range cols { c[i] = v } if len(cols) == 2 && c[0] == "Variable_name" && c[1] == "Value" { // show status | show variables return queryCol(c, rows) } return queryRow(c, rows) } func queryCol(c []string, rows *sql.Rows) *QueryMap { r := map[string]string{} for rows.Next() { var n string var v string err := rows.Scan(&n, &v) if err != nil { return &QueryMap{err: err} } r[n] = v } if err := rows.Err(); err != nil { return &QueryMap{err: err} } result := []map[string]string{} result = append(result, r) return &QueryMap{result: result, err: nil} } func queryRow(c []string, rows *sql.Rows) *QueryMap { result := []map[string]string{} for rows.Next() { vals := make([]interface{}, len(c)) for index := range vals { vals[index] = new(sql.RawBytes) } err := rows.Scan(vals...) if err != nil { return &QueryMap{err: err} } r := map[string]string{} for i := range vals { r[c[i]] = string(*vals[i].(*sql.RawBytes)) } result = append(result, r) } if err := rows.Err(); err != nil { return &QueryMap{err: err} } return &QueryMap{result: result, err: nil} }
Corporate Governance in China type="main"> Since the death of Mao Tse Tung in 1976, China has achieved unprecedented economic growth. Per capita GDP has increased from one of the lowest in the world to a level that is firmly in the middle of the international ranks. But can China continue on the growth path of the last four decades? The question arises because of the tendency of developing economies, having achieved periods of “catch-up” growth, to become mired in a “middle-income trap” that appears to stem from a variety of factors, including the tendency for elites and oligarchs to protect their own interests by blocking competition. China's success to date has come without many of the key institutions—notably, private property rights, shareholder-centered corporate governance, and a well-functioning impartial legal system—that most Western economists believe essential to long-term success. China's description of its system as “market socialism with Chinese characteristics” is an accurate one. Markets, not decrees, set most prices, while the state, in the form of the Communist Party, continues to control the careers of SOEs' senior executives, regulators, and government officials, and retains “options” to intervene in a large variety of financial and corporate affairs as well as judicial processes and decisions. Chinese history underpins the system in the sense that the Party is, at least in some respects, a genuine meritocracy reminiscent of the imperial civil service of past eras. And the authors raise the possibility that the Party's Leading Role has actually contributed to China's extraordinary growth not only by fostering such a meritocracy, but by initiating and presiding over what development economists describe as a “Big Push,” a coordinated simultaneous development of many firms in multiple industries that was necessary to transform a subsistence agricultural economy into a modern industrial one. But for all the effectiveness of China's “Big Push,” the authors close by expressing doubt that China can continue to rise into the world's economic upper ranks until it adopts the substance as well as the form of those missing institutions that, they argue, are the only well-marked path to high-income status.
Phosphatidylinositol 4-kinase IIIβ (PI4KB) forms highly flexible heterocomplexes that include ACBD3, 14-3-3, and Rab11 proteins Phosphatidylinositol 4-kinase IIIβ (PI4KB) is a key enzyme of the Golgi system because it produces its lipid hallmark - the phosphatidylinositol 4-phosphate (PI4P). It is recruited to Golgi by the Golgi resident ACBD3 protein, regulated by 14-3-3 proteins and it also serves as an adaptor because it recruits the small GTPase Rab11. Here, we analyzed the protein complexes formed by PI4KB in vitro using small angle x-ray scattering (SAXS) and we discovered that these protein complexes are highly flexible. The 14-3-3:PI4KB:Rab11 protein complex has 2:1:1 stoichiometry and its different conformations are rather compact, however, the ACBD3:PI4KB protein complex has both, very compact and very extended conformations. Furthermore, in vitro reconstitution revealed that the membrane is necessary for the formation of ACBD3:PI4KB:Rab11 protein complex at physiological (nanomolar) concentrations. SCientifiC REPORts | (2019) 9:567 | DOI: 10.1038/s41598-018-37158-6 domains) connected by long intrinsically disordered linkers (Fig. 1A). The GOLD domain anchors ACBD3 to the Golgi via its interaction with giantin 35 while the Q domain serves to bind the very N-terminal helix of PI4KB bringing it to close vicinity of the membrane and thus activating it 7 . Notably, viral 3A proteins bind the GOLD domain and literally pin it down to target membrane 36 in order to recruit PI4KB to viral replication sites . Rab11 is a small GTPase that is membrane-localized because its C-terminus is geranylgeranylated, which is typical for this family of small GTPases 40,41 . Its interaction with PI4KB was structurally characterized and revealed that PI4KB does not affect neither switch I nor switch II region of Rab11 17 and most like just serves to recruit Rab11 and its effectors to proper (Golgi) membrane 11 . Here we aimed to gain deeper structural understanding of complexes formed by PI4KB. These complexes are too large for NMR studies and also not suitable for characterization by protein crystallography because PI4KB itself and some of its interacting partners contain large intrinsically disordered regions. The lack of symmetry and conformational heterogeneity impedes also the cryoEM analysis. Because of these constrains we chose small angle X-ray scattering (SAXS) in combination with molecular simulations as a method suitable for large flexible protein complexes 42 . Results and Discussion Stoichiometry of PI4KB complexes. To correctly interpret SAXS data using molecular simulation based methods, the knowledge of stoichiometry of protein complexes is absolutely essential. Actually, even the interpretation of simple molecular envelopes (that can be very useful for rigid protein complexes) is also difficult without the knowledge of the exact stoichiometry. We have previously established that PI4KB and ACBD3 form a 1:1 complex 7 and that 14-3-3 and PI4KB preferentially form 2:2 complex 32 . Previous crystallographic studies suggest that PI4KB:Rab11 form a 1:1 complex 17 and the stoichiometry of 14-3-3:PI4KB:Rab11 protein complex was never experimentally tackled although based on the known stoichiometries of PI4KB:Rab11 (1:1) and 14-3-3:PI4KB (2:2) protein complexes we expected a 2:2:2 14-3-3:PI4KB:Rab11 complex to be formed. We used analytical ultracentrifugation (AUC) to experimentally establish stoichiomentries of the aforementioned PI4KB complexes in solution. AUC revealed that PI4KB:Rab11 form a 1:1 complex as expected. PI4KB at the 20 µM concentration forms a dimer that disappears when Rab11 is added (Fig. 1B) probably because Rab11 sterically obstructs the dimerization although we cannot rule out other mechanisms because the dimerization interface is not known. SAXS and modeling of the 14-3-3:PI4KB:Rab11 complex in solution. We collected SAXS data on the 14-3-3:PI4KB:Rab11 ternary complex at protein concentrations of 2.7 and 4.0 mg/ml, which correspond to molar concentrations much larger than the dissociation constants of the 14-3-3:PI4KB and PI4KB:Rab11 protein complexes. The two datasets overlay after rescaling, indicating no protein aggregation in the samples ( Fig. 2A). The Guinier plot (inset in Fig. 2A) shows that the radius of gyration of the 14-3-3:PI4KB:Rab11 protein complex is 43 Å suggesting a rather compact conformation. (A) Experimental SAXS intensity obtained at protein concentrations c = 2.7 mg/ml (blue) and c = 4.0 mg/ ml (red). The logarithmic scale is used on the vertical axis. Inset: Guinier plot, i.e., log(I(q)/I(0)) vs. q 2 . The region qR g < 1.3 where the Guinier approximation is valid for a globular protein is shaded gray. The dashed line indicates the best fit of the Guinier approximation, which leads to R g = 43 Å. (B) Experimental (red) and theoretical (model 1 -black, model 2 -green, model 3 -blue) scattering data shown as I(q) vs. q (top) and q 2 I(q) vs. q (Kratky plot; bottom). Any of the three models fits the experimental SAXS data with χ 2 = 1.2. (C) Three representative models of the 14-3-3:PI4KB:Rab11 complex (14-3-3 in green, PI4KB in blue, Rab11 in magenta) that fit the experimental SAXS data. Their scattering intensity profiles are shown in panel B in black, green and blue, respectively. The active site in PI4KB is indicated by arrows and highlighted in red. SCientifiC REPORts | (2019) 9:567 | DOI:10.1038/s41598-018-37158-6 Next, we used molecular simulations to structurally interpret the SAXS data and, hence, to identify conformations of the 14-3-3:PI4KB:Rab11 protein complex in solution. To this end, we simulated the 14-3-3:PI4KB:Rab11 complex in 2:1:1 stoichiometry, and identified a representative group of simulated structures consistent with the SAXS data (Fig. 2B). Similarly as in the case of the 14-3-3:PI4KB protein complex 32 , the 14-3-3:PI4KB:Rab11 protein complex appears to be rather compact (Fig. 2C), despite the long disordered region in PI4KB. The position of PI4KB in reference to the 14-3-3 dimer is different in 14-3-3:PI4KB:Rab11 than in 14-3-3:PI4KB but the active site of PI4KB is exposed in either case. The C-terminal tail of Rab11 is disordered. It attains extended conformations and never makes direct contacts with protein 14-3-3 in the ternary complex, which suggests that 14-3-3 should not interfere with the attachment of Rab11 to the membrane via its geranylgeranylated C-termini. SAXS and modeling of the ACBD3:PI4KB complex in solution. We performed SAXS measurements on the ACBD3:PI4KB protein complex at protein concentrations 3.0 and 4.5 mg/ml, which is about two orders of magnitude larger than the dissociation constant of the ACBD3:PI4KB complex (concentration of each protein ~10 µM and K d ~ 300 nM). These two datasets overlay after rescaling, indicating no protein aggregation in the samples (Fig. 3A). The Guinier plot (inset in Fig. 3A) shows that the radius of gyration of the ACBD3:PI4KB protein complex is about 80 Å, suggesting that ACBD3:PI4KB can attain extended conformations in solution. We next performed molecular simulations of the ACBD3:PI4KB protein complex and quantitatively compared the simulated SAXS curves to the experimental SAXS data. In contrast to the case of the 14-3-3:PI4KB:Rab11 complex, here we could not account for the ACBD3:PI4KB SAXS data with a single structure obtained from the simulations. However, we found that two structures together -an extended one and a more compact one -produced a scattering curve that was fully consistent with the SAXS data (Fig. 3B). These two structures (Fig. 3C) constitute thus a minimal representation of the ensemble of ACBD3:PI4KB conformations that fits the SAXS data. In each of the two structures, the inter-domain linker peptides are seen to be in extended conformations. However, in the compact structure, the ACBD domain, the Q domain and the CAR domain of ACBD3 are in proximity of the kinase domain of PI4KB. In contrast, in the extended structure, these domains are positioned far apart one another. In both of these two structures, the active site of PI4KB is exposed to solution, which explains why ACBD3 binding has no inhibitory effect on PI4KB 7 . i.e., log(I(q)/I(0)) vs. q 2 . The region qR g < 1.3 where the Guinier approximation is valid for a globular protein is shaded gray. The dashed line indicates the best fit of the Guinier approximation, which leads to R g = 80 Å. (B) Experimental (red) and theoretical (black) scattering data shown as I(q) vs. q (top) and q 2 I(q) vs. q (Kratky plot; bottom). The theoretical curve corresponds to a minimal conformational ensemble that best fits the experimental SAXS data. (C) Two structural models of the ACBD3:PI4KB complex (ACBD3 in red, PI4KB in blue) that constitute the minimal conformational ensemble and jointly fit the experimental SAXS data with χ 2 = 1.3. The protein domains of ACBD3 and PI4KB are indicated. The active site in PI4KB is highlighted by a modeled inhibitor (red) and indicated by arrows. Since the full-length ACBD3:PI4KB protein complex contains several flexible loops and disordered linkers, it can attain multiple conformations, ranging from extended to compact ones. The two structures identified in our SAXS analysis (Fig. 3C) cannot faithfully represent the actual ensemble of possible conformations of the ACBD3:PI4KB protein complex in solution. However, the vast differences between the two structures provide a glimpse of the conformational heterogeneity of this flexible protein complex. Simulations of the full-length ACBD3:PI4KB:Rab11 complex at a lipid membrane. We also performed simulations of the ACBD3:PI4KB:Rab11 ternary complex at a lipid membrane. In these simulations, Rab11 was anchored to the lipid membrane by two geranylgeranylated Cys residues at its C-terminus. Moreover, ACBD3 was held at the membrane at two sites -one site was on the ACBD domain (which binds acyl-CoA) and the other one was on the GOLD domain -see Materials and Methods for details. In addition to these three sites at which ACBD3:PI4KB:Rab11 was anchored to the membrane, our simulations revealed several other protein sites interacting transiently with the lipid membrane. Among these sites were positively charged segments of the disordered region between Met223 and Asn314 in PI4KB. (We note that this long region is missing in crystal structures of PI4KB). We speculate that these segments, which are enriched in Arg and Lys residues, may help to position PI4KB on the membrane and could explain why the full length PI4KB is about 30% more active compared to the loop deletion mutant 43 . In our simulations, the maximum extension D max of the ACBD3:PI4KB:Rab11 ternary complex at the membrane was found to vary approximately between 220 Å and 340 Å with the average of about 275 Å (Fig. 4). This observation indicates that ACBD3:PI4KB:Rab11 exhibits large conformational fluctuations while being bound to the membrane. This finding explains why membrane curvature dependent activity of PI4KB was never reported when it was reported for other lipid kinases 44 . Membrane assembly of PI4KB complexes. Next, we aimed to verify our structural prediction that PI4KB recruited to the membrane by ACBD3 would be able to recruit Rab11. We decided to work at the physiologically relevant nanomolar concentrations because at these protein concentrations PI4KB complexes assemble in cells. First we used the GUV biomimetic system where ACBD3 was tethered to the GUV membrane and was able to recruit PI4KB as previously reported by us and others 7,33,36 . However, when Rab11 was added (at the 50 nM concentration) we did not observe any Rab11 recruitment to the membrane surface (SI Fig. 2A). This is perhaps not surprising because the published K d of Rab11 and PI4KB is between 4 to 20 µM depending whether Rab11 is GTP or GDP bound 17 . However, PI4KB was reported to recruit Rab11 in cells 11 . Rab11 is stably associated with membranes in cells via its geranylgeranylated C-termini. We hypothesized that membrane association of Rab11 is essential for the formation of ACBD3:PI4KB:Rab11 protein complex at physiologically relevant protein concentrations. To test this hypothesis, we could not use the simple colocalization assay because membrane tethered Rab11 will be always localized on the surface of the membrane (SI Fig. 2B). Instead we used cross-correlation spectroscopy to directly observe correlation between fluorescence signals of Atto488 labeled PI4KB and mCherry-Rab11. The cross-correlating signal refers on the joint motion of the two proteins and thus directly reports on their interaction (Fig. 5A). We observed the formation of the ACBD3:PI4KB:Rab11 complex when membrane tethered Rab11 was used (Fig. 5B). The amplitude of the cross-correlation function was relatively low (especially when compared to the ideal case as in Fig. 5A) suggesting that only ~10% of Rab11 was localized in the complex, however, the effect was specific -when we used Y159A PI4KB mutant that does not bind Rab11 17 we did not observe any ACBD3:PI4KB:Rab11 complex (Fig. 5C) which is manifested by the flat cross-correlation curve that only oscillates around the ground level as a result of noise. We could not increase the protein concentration because of the single-molecule nature of the FCCS experiment. Despite the low protein concentrations used the difference between wild type and Y159A mutant PI4KB are statistically significant at the 95% level of probability (SI Table 2). We also didn't observe any ACBD3:PI4KB:Rab11 complex formation when soluble Rab11 was used (Fig. 5D) just as previously in the GUV recruitment assay (SI Fig. 2). These results indicate that the membrane plays an important role and is in fact indispensable for the formation of ACBD3:PI4KB:Rab11 protein complex and thus for the recruitment of Rab11 and its effectors. Concluding Remarks Crystallographic and SAXS analysis coupled to molecular simulations shed some light on the behavior of large flexible complexes in solution and even provided snapshots of their actions on the membrane . Here we described the conformations of several PI4KB complexes in solution. We used molecular simulations to gain insights into the conformational flexibility on the membrane surface. Our analysis revealed that ACBD3:PI4KB:Rab11 protein complex is extremely flexible and that the membrane is important for its formation. The observed effect is probably due to high local concentration. When membrane tethered proteins are used their local concentration on the membrane surface (or 2D concentration) can be high despite the average concentration (or 3D concentration) being in the nanomolar range. We believe that the cellular Golgi membrane acts in a similar manner when the Golgi localized ACBD3 recruits the PI4KB to the Golgi facilitating high local concentration of PI4KB that is subsequently responsible for the recruitment of Rab11 and its effectors to the Golgi. Materials and Methods Protein expression and purification. All recombinant proteins were expressed in E. coli strain BL21 NiCo in an auto induction media 16 h in 18 °C using our standard protocols 50,51 . Briefly, cells expressing the proteins were centrifuged, lysed in 50 mM Tris pH 8, 20 mM Imidazole, 300 mM NaCl, 10% glycerol, and 3 mM β-mercaptoethanol (βME) using EmulsiFlex-C3 homogenizer, lysate was centrifuged at 30,000 × g for 20 min at 4 °C and the supernatant was further used for purification of the proteins. 14-3-3 was expressed as a fusion protein with N-terminal 6xHis tag followed by TEV protease site. Protein was purified from the lysate using affinity chromatography on Ni-NTA resin (Macherey-Nagel) and the His tag was then cleaved off by TEV protease. Size-exclusion chromatography (SEC) on Superdex 75 HiLoad 16/60 column (GE Healthcare) in 30 mM Tris pH 8, 200 mM NaCl, and 3 mM βME was used as the next purification step. Purified protein was concentrated to 20 mg/ml and flash-frozen in liquid nitrogen. Rab11 was also expressed as a fusion protein with N-terminal 6xHis tag followed by TEV cleavage site and purified using affinity chromatography and TEV cleavage. Next, Rab11 was dialyzed against 30 mM Tris pH 8, 200 mM NaCl, 3 mM βME, and 5 mM EDTA (to dissociate GDP), and further purified by SEC on Superdex 75 HiLoad 16/60 column in 30 mM Tris pH 8, 200 mM NaCl, and 3 mM βME. Finally, Rab11 was concentrated to 20 mg/ml and flash-frozen in liquid nitrogen. Rab11 used for membrane assembly experiments was expressed as fusion protein with N-terminal 6xHis tag followed by TEV cleavage site and mCherry on its N-terminus and four amino acid linker (SGTG) followed by 8xHis tag on its C-terminus. This protein was further purified the same way as Rab11 used for SAXS experiments. (After cleavage of the N-terminal 6xHis tag by TEV protease the purified protein still contained mCherry and C-terminal 8xHis tag). PI4KB must be phosphorylated at S294 in order to interact with 14-3-3 protein. We used the same approach as previously 32 . Briefly, construct of PI4KB residues 128-799 with internal deletion of a disordered loop (residues 423-522) 17 to facilitate bacterial expression and protein stability and single point mutation T292R was used to faciliate in vitro phosphorylation by protein kinase A. The protein was expressed as a fusion protein with 8xHis-SUMO solubility tag and purified using affinity chromatography followed by the SUMO tag cleavage (by the Ulp1 enzyme from S. cerevisiae). Next, we performed SEC on Superdex 200 HiLoad 16/60 column in 30 mM Tris pH 8, 200 mM NaCl, and 3 mM βME. Purified PI4KB was then phosphorylated by PKA (4 μg of PKA per 1 mg of PI4KB were incubated in 20 mM Tris pH 7.4, 150 mM NaCl, 2 mM DTT, 300 μM ATP, and 10 mM MgCl 2 for 2 h at 25 °C and subsequently for 4 h at 4 °C). Phosphorylated PI4KB was further purified by anion-exchange chromatography on Mono Q 5/50GL (GE Healthcare) and by SEC on Superdex 200 HiLoad 16/60 column in 20 mM Tris pH 8, 200 mM NaCl, and 3 mM βME. Finally, it was concentrated to 12 mg/ml and flash-frozen in liquid nitrogen. PI4KB must contain its intact N-terminus in order to interact with the ACBD3 protein, therefore we used a construct described previously that contains only the internal deletion and has a 6xHis-GB1 solubility tag followed by TEV protease site that is further on referred to as pseudo-wt PI4KB 7 . Pseudo-wt PI4KB was also purified by affinity chromatography followed by TEV protease cleavage and SEC (Superdex 200 HiLoad 16/60 column in 30 mM Tris pH8, 200 mM NaCl, and 3 mM βME) and by anion exchange on Mono Q 5/50GL. Purified protein was dialyzed against 20 mM Tris pH 8, 200 mM NaCl, 2 mM TCEP, and 1% glycerol, concentrated to 5 mg/ml and flash-frozen in liquid nitrogen. Pseudo-wt PI4KB used for membrane assembly experiments was labeled with Atto488 maleimide (Sigma-Aldrich) according to the manufacturer's protocol. The labeled protein was purified from unbound dye on HiTrap Desalting column (GE Healthcare) in 20 mM Tris pH 8, 200 mM NaCl, 3 mM βME, and concentrated to 1 mg/ml. Pseudo-wt PI4KB Y159A (mutation Y159A prevents pseudo-wt PI4KB from binding Rab11 17 ) used as negative control in membrane assembly experiments was purified and labeled in the same way. ACBD3 with N-terminal 6xHis-GB1 solubility tag was purified by affinity chromatography followed by TEV cleavage (except for protein for GUV reconstitution assays) and by SEC (Superdex 200 HiLoad 16/60 column in 20 mM Tris pH 8, 200 mM NaCl, and 3 mM βME). Purified ACBD3 was concentrated to 6 mg/ml and flash-frozen in liquid nitrogen. Analytical ultracentrifugation analysis (AUC). AUC experiments were performed in the sedimentation velocity mode using the ProteomeLab XL-I Beckman Coulter analytical ultracentrifuge. All measurements were conducted at several loading concentrations and molar ratios as indicated in the corresponding figures in charcoal-filled Epon centerpieces with 12-mm optical path length in the size-exclusion chromatography buffer at 20 °C and 42 000 rpm. The buffer density, viscosity, and partial specific volume of all proteins were estimated using the program SEDNTERP (http://sed-nterp.unh.edu/). All data were collected with interference and/or Small angle X-ray scattering (SAXS) measurements. Sample of the ACBD3:PI4KB complex was prepared by mixing the recombinant proteins ACBD3 and pseudo-wt PI4KB in 1:1 molar ratio, then dialyzed against 20 mM Tris pH 8, 200 mM NaCl, 2 mM TCEP, and 1% glycerol. The complex was then concentrated to 3 and 4.5 mg/ml and flash-frozen in liquid nitrogen. Sample of the complex 14-3-3:PI4KB:Rab11 was prepared by mixing 14-3-3, phosphorylated pseudo-wt PI4KB, and Rab11 in molar ratio 1:1:1 and further purified on Superdex 200 10/300GL in 20 mM Tris pH 8, 150 mM NaCl, 1 mM TCEP, and 1% glycerol. Then the complex was concentrated to 2.7 and 4 mg/ml and flash-frozen in liquid nitrogen. The SAXS data were collected using beamlines BioSAXS Beamline BM29 (ESRF Grenoble) and EMBL SAXS beamline P12 (Petra III DESY, Hamburg) that are both equipped with the 2 M Pilatus detector (Dectris). Modeling and simulations of the full-length 14-3-3:PI4KB:Rab11 complex in solution. To efficiently sample conformations of the full-length 14-3-3:PI4KB:Rab11 ternary complex in solution, we used coarse-grained simulations in which the crystallized portions of proteins were treated as rigid bodies whereas the flexible loops and disordered segments were simulated as chains of amino-acid beads with appropriate bending, stretching and torsional potentials 53 . Here, the crystallized portion of the PI4KB:Rab11 complex with the PDB code 4D0L 17 was taken as one rigid body. The structure of the 14-3-3 dimer in complex with the PI4KB-derived phosphopeptide (PDB code: 5NAS) 54 was used as another rigid body, as in our previous computational study of the 14-3-3:PI4KB protein complex 32 . Within this approach, two independent Monte Carlo (MC) simulation runs of the 14-3-3:PI4KB:Rab11 complex in the 2:1:1 stoichiometry were performed. To enhance sampling and generate a pool of diverse structures for SAXS analysis, the replica exchange (RE) method was adopted with replicas at 16 different temperatures ranging from 300 to 500 K. The two REMC simulation runs were started from different conformations of the protein complex. Each of the simulations involved 5·10 6 MC sweeps. The simulation structures were saved every 1000 MC sweeps. In this way, we obtained 2·16 = 32 trajectories, with 5000 simulation structures recorded in each. The resulting pool of structures was very diverse. The simulation structures had the radius of gyration, R g , ranging from 37 to 59 Å. Their maximum extension, D max , was found to vary between 110 and 205 Å. The scattering intensity profile was computed for each of the simulation structures individually using the algorithm co-developed with the EROS method 55 . The discrepancy between the experimental SAXS data, I exp (q), and the scattering intensity profile of the k-th simulation structure, I k (q), was quantified according to equation 1: Here, the index k labels the simulation structures, N q is the number of SAXS data points, σ(q) is the statistical error of the measured SAXS intensity, I exp (q), whereas the parameter a sets the intensity scale and is obtained from the condition ∂χ 2 /∂a = 0. Out of the pool of 32·5000 = 160,000 simulation structures, we selected 100 structures with the smallest values of χ 2 , which were found to be within the range from 1.1 to 1.2. The top 100 structures have the radius of gyration in the range between 42.2 and 44.2 Å with the average at about 43 Å. Their maximum extension is spread in the range between about 145 and 190 Å with the average at 162 Å. In terms of their characteristic sizes, R g and D max , these models are quite typical within the pool of the simulation structures. We sorted the top 100 structures according to their similarity in the position of the crystallized portion of the PI4KB:Rab11 complex relative to the 14-3-3 dimer. We used the QT-clustering method with DRMS as metric 56 . We obtained one major cluster and three or four minor clusters, depending on the cutoff on DRMS. For example, for the DRMS cutoff of 5 Å, the major cluster contains 52 structures, and the two minor clusters contain 18 and 17 structures. The simulation structures representing these three clusters are shown in Fig. 2C. Modeling and simulations of the full-length ACBD3:PI4KB complex in solution. We performed analogous REMC simulations of the ACBD3:PI4KB protein complex. The simulation model of ACBD3:PI4KB was composed of five rigid domains: (i) the crystallized portion of PI4KB with the PDB code 4WAE 20 , which contains amino-acid residues with numbers ranging from 130 to 423 and from 522 to 816; (ii) a homology model of the ACBD domain (residue numbers from 82 to 179) based on the PDB entry 3FLV (29% sequence identity, 96% sequence coverage); (iii) the ACBD3 charged amino-acid region (CAR, residue numbers from 180 to 240) represented by a single alpha-helix, as proposed by Suveges et al. 57 ; (iv) the ACBD3 glutamine-rich domain (Q domain, residue numbers from 241 to 308) in complex with a N-terminal α-helix of PI4KB (residue numbers from 40 to 63), as given by the NMR structure with the PDB code 2N73 7 ; and (v) the crystallized portion of the ACBD3 Golgi dynamics domain (GOLD domain) with the PDB code 5LZ1 (residue numbers ranging from 128 to 422 and from 523 to 799) 36 . All of the missing loops, disordered linkers and terminal segments were modeled using ModLoop 58 and simulated as chains of amino-acid beads with appropriate bending, stretching and torsional potentials. The REMC simulations provided a very diverse pool of 80,000 structures with R g varying from 40 to 110 Å and D max in the range between 130 and 360 Å. Curiously, none of the simulation structures from this pool could be fit to the experimental SAXS data with χ 2 < 1.8. Since the full-length ACBD3:PI4KB complex contains numerous flexible loops and disordered linkers, we expected it to exhibit conformational diversity and flexibility in solution. Therefore, we applied a minimum-ensemble method 59 to gain structural interpretation of the SAXS data. The minimum ensemble consistent with the SAXS data was found to be represented by two simulation structures, i.e., one SCientifiC REPORts | (2019) 9:567 | DOI:10.1038/s41598-018-37158-6 'extended' with R g = 95 Å and D max = 300 Å, and one 'compact' with R g = 64 Å and D max = 200 Å (Fig. 3C). These two structures taken together with equal statistical weights fit the experimental SAXS data with χ 2 = 1.3 (Fig. 3B). Modeling and simulations of the full-length ACBD3:PI4KB:Rab11 ternary complex at a lipid membrane. To sample conformations of the ACBD3:PI4KB:Rab11 ternary complex at a bilayer membrane, we used the same coarse-grained simulation package as for the simulations of ACBD3:PI4KB and 14-3-3:PI4KB:Rab11 in solution. In the framework of this model, the interactions of the residue beads with the membrane are described by statistical amino-acid dependent potentials and Debye-Hückel-type electrostatics. A detailed description of this approach can be found in Kim et al. 53 . Rab11 is geranylgeranylated at two Cys residues in its C-terminus. We simulated this lipid modification in an analogous way as the palmitoylation of four Cys residues in PI4K IIα in our earlier computational studies 18 . Namely, to mimic the anchoring of the two geranylgeranylated Cys residues in the lipid membrane, we imposed soft harmonic potentials on the z-coordinates of these Cys residue beads relative to the membrane surface located at z = 2 nm. ACBD3 is held at the membrane at two sites that are located on two separate domains. Namely, the ACBD domain binds acyl-CoA whereas the GOLD domain has a membrane binding site that has been identified in our earlier studies on the GOLD:3 A complex 36 . In our simulations, ACBD3 was thus restrained to the membrane surface, positioned at z = 2 nm, by soft harmonic potentials acting on the z-coordinates of these two sites in the ACBD and GOLD domains. We performed 20 independent REMC simulations of ACBD3:PI4KB:Rab11 restrained to the flat membrane as described above. Each of the simulations was started from a different ACBD3:PI4KB:Rab11 conformation and with a different seed for the random number generator. Each of the simulations involved replicas at 8 different temperatures and 2.5·10 6 MC sweeps. The simulation structures were saved every 1000 MC sweeps at room temperature only. In this way, we obtained an ensemble of 20·2500 = 50,000 coarse-grained structures for further analysis. For each of the recorded ACBD3:PI4KB:Rab11 conformations we identified residue beads with the z-coordinate below a threshold z = z 0 . We investigated the values of z 0 in the range between 2 and 2.5 nm. In this way, we estimated the probabilities of contacts between individual residue beads and the flat membrane. We also analyzed the maximum extension D max of the ACBD3:PI4KB:Rab11 protein complex at the membrane. Giant unilamellar vesicles (GUVs) preparation and imaging. GUVs were prepared as before 60 , briefly, chloroform lipid mixture containing 55 mol % of POPC, 10 mol % POPS, 10 mol % PI, 20 mol % cholesterol, and 5 mol % DGS-NTA(Ni) (all Avanti Polar Lipids) was prepared at overall lipid concentration 5 µg/µL. 10 µL of the lipid mixture was spread on two ITO coated glass electrodes each. The electrodes were dried under vacuum overnight and then parallel assembled into a home made teflon chamber containing 5 mL of 600 mM sucrose solution. For the electroformation, 10 Hz, harmonically oscillating voltage of 1 V peak value was applied to the electrodes for 1 hour at 60 °C. For imaging, BSA-coated 4-chamber glass bottom dish (In Vitro Scientific) were used. 100 µL of GUVs mixed with 100 µL isosmotic buffer (25 mM Tris pH 8, 10 mM MgCl 2 , 20 mM Imidazole, 261.5 mM NaCl, 2 mM βME) containing proteins of interest, so that the final concentrations of the proteins (ACBD3, PI4KB, mCherry-Rab11) were approximately 50 nM. For fluorescence correlation spectroscopy (FCS) experiments the LSM 780 was equipped with external tau-SPAD detectors and time-correlated single photon counting (TCSPC) electronics (Hydraharp, Picoquant, Berlin, Germany). For the Atto488 excitation, 490 nm line of the Intune laser (Ziess) pulsing at 40 MHz repetition frequency was used. mCherry was excited continuously at 561 nm. The excitation light was focused by 40x/1.2 W objective (Zeiss) into the solution. Fluorescence intensity, collected by the same objective lens, was re-focused on the pinhole (1 airy unit) and the re-collimated light behind the pinhole was split on the external tau-SPADs in front of which emission band pass filters 525/45 and 600/52 for Atto488 and mCherry signal, respectively, were placed. The collected data were correlated by home-written script in Matlab (Mathworks, Natick, MA) according to the previously described algorithm 61 . To avoid detector crosstalk, the red channel fluorescence signal was split according to its TCSPC pattern (exponential for the signal generated by the pulsed Intune laser and flat for the 561 nm continuous wave laser) into two contributions and only the signal assigned to the flat TCSPC profile was correlated as described in detail previously 62 .
// S3 configuration for location to store rejections from magnetic store writes func (o MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesOutput) S3Configuration() MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesPtrOutput { return o.ApplyT(func(v MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationProperties) *MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationProperties { return v.S3Configuration }).(MagneticStoreWritePropertiesPropertiesMagneticStoreRejectedDataLocationPropertiesS3ConfigurationPropertiesPtrOutput) }
use rand::Rng; use rand_pcg::Pcg64; use rand::prelude::*; pub fn random_key_value_pairs<V: Clone>(key_length: usize, size: usize, seed: u64, values: &[V]) -> Vec<(String, V)> { let mut rng = Pcg64::seed_from_u64(seed); (0..size).map(|_| { (random_key(key_length, &mut rng), random_value(&mut rng, values)) }).collect() } pub fn random_key(key_length: usize, rng: &mut rand_pcg::Pcg64) -> String { const CHARSET: &[u8] = b"ABCDEF<KEY>"; (0..key_length) .map(|_| { let idx = rng.gen_range(0..CHARSET.len()); CHARSET[idx] as char }) .collect() } fn random_value<V: Clone>(rng: &mut rand_pcg::Pcg64, values: &[V]) -> V { values.choose(rng).unwrap().clone() }
<reponame>sean5470/panda3d<gh_stars>0 /** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file virtualFileMountMultifile.cxx * @author drose * @date 2002-08-03 */ #include "virtualFileMountMultifile.h" #include "virtualFileSystem.h" TypeHandle VirtualFileMountMultifile::_type_handle; /** * */ VirtualFileMountMultifile:: ~VirtualFileMountMultifile() { } /** * Returns true if the indicated file exists within the mount system. */ bool VirtualFileMountMultifile:: has_file(const Filename &file) const { return (file.empty() || _multifile->find_subfile(file) >= 0 || _multifile->has_directory(file)); } /** * Returns true if the indicated file exists within the mount system and is a * directory. */ bool VirtualFileMountMultifile:: is_directory(const Filename &file) const { return (file.empty() || _multifile->has_directory(file)); } /** * Returns true if the indicated file exists within the mount system and is a * regular file. */ bool VirtualFileMountMultifile:: is_regular_file(const Filename &file) const { return (_multifile->find_subfile(file) >= 0); } /** * Fills up the indicated pvector with the contents of the file, if it is a * regular file. Returns true on success, false otherwise. */ bool VirtualFileMountMultifile:: read_file(const Filename &file, bool do_uncompress, pvector<unsigned char> &result) const { if (do_uncompress) { // If the file is to be decompressed, we'd better just use the higher- // level implementation, which includes support for on-the-fly // decompression. return VirtualFileMount::read_file(file, do_uncompress, result); } // But if we're just reading a straight file, let the Multifile do the // reading, which avoids a few levels of buffer copies. int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { express_cat.info() << "Unable to read " << file << "\n"; return false; } return _multifile->read_subfile(subfile_index, result); } /** * Opens the file for reading, if it exists. Returns a newly allocated * istream on success (which you should eventually delete when you are done * reading). Returns NULL on failure. */ istream *VirtualFileMountMultifile:: open_read_file(const Filename &file) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return NULL; } // The caller will eventually pass this pointer to // VirtualFileSystem::close_read_file(), not to // Multifile::close_read_subfile(). Fortunately, these two methods do the // same thing, so that doesn't matter. return _multifile->open_read_subfile(subfile_index); } /** * Returns the current size on disk (or wherever it is) of the already-open * file. Pass in the stream that was returned by open_read_file(); some * implementations may require this stream to determine the size. */ streamsize VirtualFileMountMultifile:: get_file_size(const Filename &file, istream *) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return 0; } return _multifile->get_subfile_length(subfile_index); } /** * Returns the current size on disk (or wherever it is) of the file before it * has been opened. */ streamsize VirtualFileMountMultifile:: get_file_size(const Filename &file) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return 0; } return _multifile->get_subfile_length(subfile_index); } /** * Returns a time_t value that represents the time the file was last modified, * to within whatever precision the operating system records this information * (on a Windows95 system, for instance, this may only be accurate to within 2 * seconds). * * If the timestamp cannot be determined, either because it is not supported * by the operating system or because there is some error (such as file not * found), returns 0. */ time_t VirtualFileMountMultifile:: get_timestamp(const Filename &file) const { int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return 0; } return _multifile->get_subfile_timestamp(subfile_index); } /** * Populates the SubfileInfo structure with the data representing where the * file actually resides on disk, if this is knowable. Returns true if the * file might reside on disk, and the info is populated, or false if it might * not (or it is not known where the file resides), in which case the info is * meaningless. */ bool VirtualFileMountMultifile:: get_system_info(const Filename &file, SubfileInfo &info) { Filename multifile_name = _multifile->get_multifile_name(); if (multifile_name.empty()) { return false; } int subfile_index = _multifile->find_subfile(file); if (subfile_index < 0) { return false; } if (_multifile->is_subfile_compressed(subfile_index) || _multifile->is_subfile_encrypted(subfile_index)) { return false; } streampos start = _multifile->get_subfile_internal_start(subfile_index); size_t length = _multifile->get_subfile_internal_length(subfile_index); info = SubfileInfo(multifile_name, start, length); return true; } /** * Fills the given vector up with the list of filenames that are local to this * directory, if the filename is a directory. Returns true if successful, or * false if the file is not a directory or cannot be read. */ bool VirtualFileMountMultifile:: scan_directory(vector_string &contents, const Filename &dir) const { return _multifile->scan_directory(contents, dir); } /** * */ void VirtualFileMountMultifile:: output(ostream &out) const { out << _multifile->get_multifile_name(); }
/** * @author websterchen * @version v1.1 * @since 2019/8/9 */ @Data public class TransactionInfo { /** * The payLoad */ private String payLoad; /** * blockNumber */ private Long blockNumber; /** * The error code. */ private int code; /** * The error message. */ private String message; }
def read_zero_terminated_string(data, index): if index is None: result = bytearray() for _ in xrange(STR_MAX_LEN): char = ord(data.read(1)) if char == 0: return guess_encoding(result), index result.append(char) raise ValueError('found no string-terminating zero-byte!') else: end_idx = data.index(b'\x00', index, index+STR_MAX_LEN) return guess_encoding(data[index:end_idx]), end_idx+1
Spread the love When giving gifts this holiday season, be strongly advised certain toys will upload your child’s unique voice and personal information — to the same military and law enforcement database which helps authorities identify criminals. Indeed, these toys — which could record any conversation occurring nearby, and also fish for specific information from unwitting children — constitute the latest in surveillance by home appliances and gadgets known collectively as the Internet of Things. And this insidious, extraneous spying has several watchdog groups sounding alarm bells in a complaint filed with the Federal Trade Commission. Genesis Toys’ My Friend Cayla doll and i-Que robot — Internet-connected toys using voice recognition technology to interact with children — can answer questions by converting speech to text and retrieving information from Google, Wikipedia, and Weather Underground, CNN reports. But what has the Electronic Privacy Information Center (EPIC), the Campaign for a Commercial Free Childhood, the Center for Digital Democracy, and the Consumers Union on edge is that the “toys subject young children to ongoing surveillance,” in violation of privacy and consumer protection laws — and, worse, the nature of the company Genesis Toys employs for that purpose. “Nuance Communications,” the aforementioned groups state in a complaint to the FTC, “represents itself as a leader in voice technology, including speech recognition software and voice biometric solutions that allow a search of the company’s 60 million enrolled voiceprints for a voice match from recorded conversations to be performed within minutes. Nuance markets its technology to private and public entities and delivers its voice biometric technology to military, intelligence, and law enforcement agencies.” “Both Genesis Toys and Nuance Communications unfairly and deceptively collect, use, and disclose audio files of children’s voices without providing adequate notice or obtaining verified parental consent,” the complaint continues. Cayla and i-Que have slightly differing companion applications, but Genesis collects users’ IP addresses and both require downloading and connection to the user’s mobile device via Bluetooth technology. As the complaint explains: “The companion application for My Friend Cayla requests permission to access the hardware, storage, microphone, Wi-Fi connections, and Bluetooth on users’ devices, but fails to disclose to the user the significance of obtaining this permission. The i-Que companion application also requests access to the device camera, which is not necessary to the toy’s functions and is not explained or justified.” That Richard Mack, Nuance vice president of corporate marketing and communications, reassured the public the uploaded information is not sold or used for advertising or marketing purposes should be of little comfort to consumers wary of the perfidious surveillance state. Even so, Cayla comes equipped with pro-Disney marketing propaganda in references to Disney movies and Disney theme parks — the doll says her favorite movie is Disney’s The Little Mermaid, for example — which children cannot distinguish as advertising. Perhaps most notably, not to mention nefariously, CNN reports, “The Cayla doll also has a mobile phone app that asks children to provide personal information, like their name and their parents’ names, their favorite TV show, their favorite meal, where they go to school, their favorite toy and where they live.” EPIC and the other watchdogs have requested an investigation into Genesis Toys and Nuance Communications by the FTC and to have Cayla and i-Que pulled from store shelves. “The FTC should issue a recall on the dolls and halt further sales pending the resolution of the privacy and safety risks identified in the complaint,” asserted Claire Gartland, director of EPIC’s Consumer Privacy Project. “This is already happening in the European Union, where Dutch stores have pulled the toys from their shelves.” EPIC also notes this complaint is one facet of a concerted effort to ban such privacy-invasive and surveillance-laden toys from the marketplace. Last year, Senator Edward Markey and Rep. Joe Barton were joined by Rep. Mark Kirk and Sen. Bobby Rush in introducing the Do Not Track Kids Act of 2015 (H.R. 2734) to update existing children’s online privacy law to include greater protections for kids. Markey penned letters to Genesis and Nuance demanding immediate compliance with strictures delineated in the Children’s Online Privacy Protection Act. The Internet of Things has long been a cause for concern for privacy advocates and delight for surveillance hawks, as predictions the surveillance state will be willingly welcomed into people’s homes through the convenience of interconnectedness prove true time and again. However, while it might be one thing for hapless adults to dismissively toss privacy concerns to the wayside, to have the voiceprints and information of children as young as three-years-old uploaded and likely stored by a company with military and law enforcement ties is a whole other animal.
package cmd import ( "fmt" "github.com/paddymorgan84/fpl/api" "github.com/paddymorgan84/fpl/helpers" "github.com/paddymorgan84/fpl/ui" "github.com/spf13/cobra" ) // BuildFixturesCommand returns the fixtures cobra command func BuildFixturesCommand(c api.FplAPI, config helpers.ConfigReader) *cobra.Command { var cmd = &cobra.Command{ Use: "fixtures", Short: "Get the fixtures for a specific gameweek", RunE: func(cmd *cobra.Command, args []string) error { return getFixtures(c, config) }, } return cmd } func getFixtures(c api.FplAPI, config helpers.ConfigReader) error { var bootstrap, err = c.GetBootstrapData() if err != nil { return err } gameweek, err := helpers.GetCurrentGameweek(bootstrap.Gameweeks, config) if err != nil { return err } fixtures, err := c.GetGameweekFixtures(gameweek) if err != nil { return err } ui.PrintHeader(fmt.Sprintf("Gameweek %d fixtures", gameweek)) ui.PrintGameweekFixtures(bootstrap, fixtures, gameweek) return err }
/** * Abstraction to drive a regulated encoder motor with the NXTMMX motor multiplexer. * The * NXTMMX motor multiplexer device allows you to connect two * additional motors to your robot using a sensor port. Multiple NXTMMXs can be chained together. * <p> * Use the <code>NXTMMX.getRegulatedMotor()</code> factory method to retrieve an instance of this class. * * @see NXTMMX * @author Kirk P. Thompson * */ public class MMXRegulatedMotor extends MMXMotor implements RegulatedMotor { static final int LISTENERSTATE_STOP = 0; static final int LISTENERSTATE_START = 1; private final int MOTOR_MAX_DPS=Math.round(mmx.getVoltage()*100); private Object lockObj = new Object(); RegulatedMotorListener listener; MMXRegulatedMotor(NXTMMX mmx, int channel) { super(mmx, channel); } public void addListener(@SuppressWarnings("hiding") RegulatedMotorListener listener) { this.listener = listener; } void doListenerState(int listenerState) { synchronized (lockObj) { if (this.listener == null) return; if (listenerState == LISTENERSTATE_STOP) { // wait for a complete stop before notifying // new Thread(new Runnable(){ // public void run() { // waitComplete(); // listener.rotationStopped(MMXRegulatedMotor.this, getTachoCount(), false, System.currentTimeMillis()); // }}).start(); listener.rotationStopped(MMXRegulatedMotor.this, getTachoCount(), false, System.currentTimeMillis()); } else { this.listener.rotationStarted(this, getTachoCount(), false, System.currentTimeMillis()); } } } public RegulatedMotorListener removeListener() { RegulatedMotorListener old = this.listener; this.listener = null; return old; } /** * Return the current rotational speed calculated from the encoder position every 100 ms. This will * likely differ from what was specified in <code>setSpeed</code>. * * @return The current rotational speed in deg/sec */ public int getRotationSpeed() { return Math.round(.01f * mmx.doCommand(NXTMMX.CMD_GETSPEED, 0, channel)); } public void stop(boolean immediateReturn) { super.stop(); if (!immediateReturn) waitComplete(); } public void flt(boolean immediateReturn) { super.flt(); if (!immediateReturn) waitComplete(); } public synchronized void waitComplete() { while (isMoving()) { Delay.msDelay(50); } } /** * Rotate by the requested number of degrees while blocking until completion. * * @param angle number of degrees to rotate relative to the current position. */ public void rotate(int angle) { rotate(angle, false); } /** * Rotate to the target angle while blocking until completion. * * @param limitAngle Angle [in degrees] to rotate to. */ public void rotateTo(int limitAngle) { rotateTo(limitAngle, false); } /** * Rotate by the requested number of degrees with option for wait until completion or immediate return where the motor * completes its rotation asynchronously. * * @param degrees number of degrees to rotate relative to the current position. * @param immediateReturn if <code>true</code>, do not wait for the move to complete. <code>false</code> will block * until the rotation completes. */ public void rotate(int degrees, boolean immediateReturn){ mmx.doCommand(NXTMMX.CMD_ROTATE, degrees, channel); if (!immediateReturn) mmx.waitRotateComplete(channel); } /** * Rotate to the target angle with option for wait until completion or immediate return where the motor * completes its rotation asynchronously. * * @param limitAngle Angle [in degrees] to rotate to. * @param immediateReturn if <code>true</code>, do not wait for the move to complete. <code>false</code> will block * until the rotation completes. */ public void rotateTo(int limitAngle, boolean immediateReturn){ mmx.doCommand(NXTMMX.CMD_ROTATE_TO, limitAngle, channel); if (!immediateReturn) mmx.waitRotateComplete(channel); } /** * Sets desired motor speed, in degrees per second. * <p> * The NXTMMX does not provide speed control per se (just power) so we approximate the power value used * based on the requested degress/sec (dps) passed in <code>speed</code>. This means if you request 400 dps, * the actual dps value * may not reflect that. Setting speed during a rotate method will have no effect on the running rotate * but will on the next rotate * method call. * <p> * experimental data gives: dps=8.1551*power+32.253 (unloaded @ 8.83V) * <p> * <b>Note:</b>The NXTMMX doesn't seem to want to drive the standard NXT motor below ~40 dps. * @param speed Motor speed in degrees per second * @see #getSpeed * @see #setPower */ public void setSpeed(int speed) { speed=Math.abs(speed); if (speed > MOTOR_MAX_DPS) speed=MOTOR_MAX_DPS; float power=(speed-32.253f)/8.1551f; if (power<0) power=0; super.setPower(Math.round(power)); } /** * Return the current target speed. * @return Motor speed in degrees per second. * @see #setSpeed * @see #getPower */ public int getSpeed() { return Math.round(8.1551f*super.getPower()+32.253f); } public float getMaxSpeed() { return MOTOR_MAX_DPS; } public boolean isStalled() { return NXTMMX.MOTPARAM_OP_TRUE==mmx.doCommand(NXTMMX.CMD_ISSTALLED, 0, channel); } /** * NOT IMPLEMENTED as the NXTMMX motor controller does not support this command. */ public void setStallThreshold(int error, int time) { // do nothing } /** * Sets speed ramping is enabled/disabled for this motor. The <code>RegulatedMotor</code> interface * specifies this in degrees/sec/sec * but the NXTMMX does not allow the rate to be changed, just if the motor uses smooth * acceleration or not so we use the <code>acceleration</code> * parameter to specify ramping state. <p>Default at instantiation is ramping enabled. * @param acceleration >0 means NXTMMX internal ramping is enabled otherwise disabled * @see MMXMotor#setRamping(boolean) */ public void setAcceleration(int acceleration){ super.setRamping(acceleration>0); } /** * Return the angle that this Motor is rotating to or last rotated to. * @return angle in degrees. 0 if no rotate method has been intiated. */ public int getLimitAngle() { return mmx.doCommand(NXTMMX.CMD_GETLIMITANGLE, 0, channel); } }
package org.spoofax.jsglr2.benchmark.jsglr2.datastructures; import org.spoofax.jsglr2.testset.TestSet; public class JSGLR2StateApplicableActionsBenchmarkJava8 extends JSGLR2StateApplicableActionsBenchmark { public JSGLR2StateApplicableActionsBenchmarkJava8() { super(TestSet.java8); } }
/** * Created by florian on 28.11.15. */ public class GameControllerTest { GameController controller; private Components components; private PlayerAdapter playerAdapter; private BoardsAdapter boardsAdapter; private EventsAdapter eventsAdapter; @Before public void setUp() throws Exception { components = new Components(); boardsAdapter = mock(BoardsAdapter.class); when(boardsAdapter.createBoard(any(Game.class))).thenReturn(true); when(boardsAdapter.addPlayer(any(Game.class), any(Player.class))).thenReturn(true); playerAdapter = mock(PlayerAdapter.class); eventsAdapter = mock(EventsAdapter.class); controller = new GameController("test-uri", playerAdapter, boardsAdapter, eventsAdapter); } @After public void tearDown() throws Exception { } @Test public void testGetAll() throws Exception { } @Test public void testCreateNewGame() throws Exception { Game game1 = controller.createNewGame(components); assertNotNull(game1); Game game2 = controller.createNewGame(components); assertNotNull(game2); assertNotEquals(game1, game2); assertNotEquals(game1.getGameid(), game2.getGameid()); assertNotNull(game1.getGameid()); assertNotNull(game1.getComponents()); assertNotNull(game1.getPlayers()); assertEquals(game1.getPlayers().getPlayers().size(), 0); assertNotNull(game1.getUri()); assertFalse(game1.isStarted()); } @Test public void testGetGame() throws Exception { Game game1 = controller.createNewGame(components); Game game2 = controller.getGame(game1.getGameid()); assertEquals(game1.getGameid(), game2.getGameid()); assertEquals(game1, game2); } @Test public void testPlayerLifeCycle() throws Exception { String playerURI = "test-uri"; String playerName = "Johnny Bravo"; String playerID = "42"; //Add Game game = controller.createNewGame(components); Boolean result = controller.addPlayerToGame(game.getGameid(), playerID, playerName, playerURI); assertTrue(result); //Get Player player = controller.getPlayerFromGame(game.getGameid(), playerID); assertNotNull(player); assertEquals(player.getUri(), playerURI); assertEquals(player.getName(), playerName); Player player1 = controller.getPlayerFromGame(game.getGameid(), "abc"); assertNull(player1); Player player2 = controller.getPlayerFromGame("test", playerID); assertNull(player2); //Remove controller.removePlayerFromGame(game.getGameid(), playerID); Player player3 = controller.getPlayerFromGame(game.getGameid(), playerID); assertNull(player3); } @Test public void testPlayerReady() throws Exception { String playerURI = "test-uri"; String playerName = "Johnny Bravo"; String playerID = "42"; //Add Player Game game = controller.createNewGame(components); Boolean result = controller.addPlayerToGame(game.getGameid(), playerID, playerName, playerURI); boolean ready1 = controller.isPlayerReady(game.getGameid(), playerID); assertFalse(ready1); controller.togglePlayerReady(game.getGameid(), playerID); boolean ready2 = controller.isPlayerReady(game.getGameid(), playerID); assertTrue(ready2); assertTrue(game.isStarted()); verify(eventsAdapter, times(1)).sendEvent(matches(game.getGameid()), any(), any()); assertNotEquals(ready1, ready2); assertEquals(game.getCurrentPlayer().getId(), playerID); } @Test public void testPlayerMutex() throws Exception { String playerURI = "test-uri"; String playerName = "Johnny Bravo"; String playerID = "42"; Player player = new Player(playerID, playerName, playerURI); Player player2 = new Player("43", playerName, playerURI); //Add Player Game game = controller.createNewGame(components); controller.addPlayerToGame(game.getGameid(), playerID, playerName, playerURI); MutexStatus mutexStatus = controller.setMutex(game.getGameid(), player); assertEquals(mutexStatus, MutexStatus.SUCCESS); mutexStatus = controller.setMutex(game.getGameid(), player); assertEquals(mutexStatus, MutexStatus.ALREADY_HOLDING); mutexStatus = controller.setMutex(game.getGameid(), player2); assertEquals(mutexStatus, MutexStatus.FAILED); } }
BOSTON -- Phoenix Suns guard Devin Booker became the sixth player in NBA history to score 70 points in a game, accomplishing the feat in Friday night's 130-120 loss to the Boston Celtics at TD Garden. Booker joined Wilt Chamberlain, David Robinson, David Thompson, Elgin Baylor and Kobe Bryant as players to have scored at least 70 points in one game. It was the 11th game in NBA history in which a single player scored 70 points or more, according to ESPN Stats & Information. Booker finished 21-of-40 shooting overall, including 4-of-11 on 3-pointers, and 24-of-26 from the free throw line. He added eight rebounds and six assists in 45 minutes. "This doesn't happen very often," an exhausted Booker said as he shuttled through postgame media duties. "Especially against a really good defensive team like the Boston Celtics. I knew I was going to have to come in, lock in mentally tonight -- playing at Boston isn't easy all the time. They made it tough for me in the first half, and I tried to get it going. I was ultra-aggressive. My teammates started finding me, they started setting really good screens for me, and the rest is history." Suns forward Jared Dudley tweeted a postgame photo of the team celebrating Booker's feat: Suns coach Earl Watson utilized multiple timeouts and intentionally fouled late in the fourth quarter, which aided Booker's quest for 70 points. While fans at TD Garden embraced his scoring outburst and cheered -- particularly with the Celtics out front by double digits -- Boston players seemed less than enthusiastic about the way the Suns ran up Booker's scoring total. The Suns called two timeouts in the final 44 seconds, both while trailing by double figures, and committed two fouls in that same span in order to generate extra shots for Booker, who scored five points during that stretch to push him to 70 points. Booker might have pushed his total even higher but missed two shots in the closing seconds. Watson was unapologetic about the way he approached the final minutes. "It's basketball," he said. "I'm not coming to any arena just happy to be there, trying to be liked. I don't care about being liked. I really don't care, to be honest with you. We're coming in here, we're trying to build something with this young group. If people don't like us, why we build it, so what? Do something about it. Simple as that. "It's about letting our kids be great. You got a problem with that? Do something. Simple as that." Suns guard Devin Booker went 21-of-40 from the field and 24-of-26 from the free throw line in posting just the 11th 70-point game in NBA history. Brian Babineau/Getty Images Booker noted how Watson was his player development coach before becoming the Suns' head coach and said he appreciated the way Watson tried to help him. Asked whether it was weird to celebrate a 70-point game despite losing, Booker offered a poised explanation. "It is [weird] because we've all been winners most of our life," he said. "But at the same time, the way our season's gone right now, we're kind of looking for something to celebrate. And that meant a lot to see my veterans happy. Tyson Chandler cheering me on. Jared Dudley had 10 assists tonight looking for me every time downcourt. It is [weird] sometimes, but you have to see the beauty in it. "At the end of the day, history was made, and I couldn't do it without my team, so they're gonna celebrate." The NBA posted Dudley's locker room snapshot of Suns players huddled around Booker with a "70" sign on its Instagram page. A comment posted from Celtics forward Jae Crowder's account (and later deleted) said, "Never seen so many guys happy after an 'L'." Asked about jawing with Crowder during the game, Booker said: "We were just messing around. Crowder's a really good player. He said, I think at the start of the fourth, he said, 'You're not going to get 50.' I said, 'I wish you were out here.' I think he was sitting at the time. We were just exchanging throughout the rest of the game. Like I said, I respect the Celtics, what they've done here, the storied franchise that they have. Best of luck to them in the playoffs." Celtics guard Isaiah Thomas looked unamused on the court. "It was weird what they were doing," Thomas said. "I've never seen nothing like that, chasing those numbers. But it is what it is. "I don't think anybody's ever seen that. To continue to call timeouts, continue to foul when we're up 15. But it was obvious what they were trying to do. They were trying to get him the most points possible. And hats off to him, though. He played a hell of a game." Booker topped Klay Thompson's 60-point effort from December for the highest-scoring game in the NBA this season. He had 51 second-half points, including 28 in the fourth quarter, when the Suns intentionally fouled and used their timeouts to help Booker run up his point total. According to ESPN Stats & Information, Booker, 20, is the youngest player to score 70, or even 60, points in a game. He had the highest-scoring game in the NBA since Bryant scored 81 in January 2006. It was the ninth game of 50 points or more in the NBA this season and the most points scored by an opponent against the Celtics, eclipsing the 64 points scored by Baylor with the Minneapolis Lakers in 1959. Despite Booker's offensive exploits, the Celtics never trailed during Friday's game and led by as much as 26.
def check(self, hash_info, check_hash=True): obj = self.get(hash_info) if self.is_protected(obj.path_info): logger.trace( "Assuming '%s' is unchanged since it is read-only", obj.path_info, ) return try: obj.check(self, check_hash=check_hash) except ObjectFormatError: logger.warning("corrupted cache file '%s'.", obj.path_info) self.fs.remove(obj.path_info) raise self.protect(obj.path_info)
<filename>rest_ocd_services/src/main/java/i5/las2peer/services/ocd/centrality/measures/NeighborhoodCoreness.java package i5.las2peer.services.ocd.centrality.measures; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import i5.las2peer.services.ocd.centrality.data.CentralityCreationLog; import i5.las2peer.services.ocd.centrality.data.CentralityCreationType; import i5.las2peer.services.ocd.centrality.data.CentralityMeasureType; import i5.las2peer.services.ocd.centrality.utils.CentralityAlgorithm; import i5.las2peer.services.ocd.centrality.data.CentralityMap; import i5.las2peer.services.ocd.graphs.CustomGraph; import i5.las2peer.services.ocd.graphs.GraphType; import y.base.Node; import y.base.NodeCursor; /** * Implementation of Neighborhood Coreness. * See: Bae, Joonhyun and <NAME>. 2014. Identifying and ranking influential spreaders in complex networks by neighborhood coreness. * @author Tobias * */ public class NeighborhoodCoreness implements CentralityAlgorithm { public CentralityMap getValues(CustomGraph graph) throws InterruptedException { CentralityMap res = new CentralityMap(graph); res.setCreationMethod(new CentralityCreationLog(CentralityMeasureType.NEIGHBORHOOD_CORENESS, CentralityCreationType.CENTRALITY_MEASURE, this.getParameters(), this.compatibleGraphTypes())); // Graph is copied because the coreness algorithm removes all the nodes CustomGraph graphCopy = new CustomGraph(graph); Coreness corenessAlgorithm = new Coreness(); CentralityMap corenessMap = corenessAlgorithm.getValues(graphCopy); Map<String, Double> nameCorenessMap = corenessMap.getMap(); NodeCursor nc = graph.nodes(); while(nc.ok()) { if(Thread.interrupted()) { throw new InterruptedException(); } Node node = nc.node(); double neighborCorenessSum = 0.0; NodeCursor neighbors = node.successors(); while(neighbors.ok()) { String nodeName = graph.getNodeName(neighbors.node()); neighborCorenessSum += nameCorenessMap.get(nodeName); neighbors.next(); } res.setNodeValue(node, neighborCorenessSum); nc.next(); } return res; } @Override public Set<GraphType> compatibleGraphTypes() { Set<GraphType> compatibleTypes = new HashSet<GraphType>(); compatibleTypes.add(GraphType.WEIGHTED); return compatibleTypes; } @Override public CentralityMeasureType getCentralityMeasureType() { return CentralityMeasureType.NEIGHBORHOOD_CORENESS; } @Override public HashMap<String, String> getParameters() { return new HashMap<String, String>(); } @Override public void setParameters(Map<String, String> parameters) throws IllegalArgumentException { if(parameters.size() > 0) { throw new IllegalArgumentException(); } } }
<filename>transactions/trs_test.go package transactions import ( "encoding/hex" "fmt" "github.com/hacash/core/account" "github.com/hacash/core/actions" "github.com/hacash/core/fields" "testing" "time" ) // 钻石借贷交易 func Test_diamond_lending(t *testing.T) { hash14, _ := hex.DecodeString("530dd68299cf6d2bd68299cf6d2b") // tx feeamt, _ := fields.NewAmountFromFinString("ㄜ1:246") mainaddr, _ := fields.CheckReadableAddress("1MzNY1oA3kfgYi75zquj3SRUPYztzXHzK9") tx, _ := NewEmptyTransaction_2_Simple(*mainaddr) tx.Fee = *feeamt tx.Timestamp = 1618839281 // 创建钻石 amt1 := fields.NewAmountSmall(16, 248) act1 := actions.Action_15_DiamondsSystemLendingCreate{ LendingID: hash14, MortgageDiamondList: fields.DiamondListMaxLen200{ Count: 2, Diamonds: []fields.DiamondName{[]byte("XXXYYY"), []byte("WWWMMM")}, }, LoanTotalAmount: *amt1, BorrowPeriod: 20, } tx.AppendAction(&act1) // 签名 feeacc := account.CreateAccountByPassword("<PASSWORD>") addrPrivateKeys := map[string][]byte{} addrPrivateKeys[string(feeacc.Address)] = feeacc.PrivateKey tx.FillNeedSigns(addrPrivateKeys, nil) // 序列化 txbody, _ := tx.Serialize() fmt.Println("tx body:", hex.EncodeToString(txbody)) } // 创建钻石交易 func Test_create_diamond(t *testing.T) { hash8, _ := hex.DecodeString("530dd68299cf6d2b") hash32, _ := hex.DecodeString("000000000e8ca4376218601120e12b6724a8c174087b9614530dd68299cf6d2b") // tx feeamt, _ := fields.NewAmountFromFinString("ㄜ1:246") mainaddr, _ := fields.CheckReadableAddress("1MzNY1oA3kfgYi75zquj3SRUPYztzXHzK9") tx, _ := NewEmptyTransaction_2_Simple(*mainaddr) tx.Fee = *feeamt tx.Timestamp = 1618839281 // 创建钻石 act1 := actions.Action_4_DiamondCreate{ Diamond: fields.DiamondName("WWWMMM"), Number: 3, PrevHash: hash32, Nonce: hash8, Address: *mainaddr, CustomMessage: hash32, } tx.AppendAction(&act1) // 签名 feeacc := account.CreateAccountByPassword("<PASSWORD>") addrPrivateKeys := map[string][]byte{} addrPrivateKeys[string(feeacc.Address)] = feeacc.PrivateKey tx.FillNeedSigns(addrPrivateKeys, nil) // 序列化 txbody, _ := tx.Serialize() fmt.Println("tx body:", hex.EncodeToString(txbody)) } func Test_alltx(t *testing.T) { // 全类别交易 测试 feeamt, _ := fields.NewAmountFromFinString("ㄜ1234:246") mainaddr, _ := fields.CheckReadableAddress("1MzNY1oA3kfgYi75zquj3SRUPYztzXHzK9") tx, _ := NewEmptyTransaction_2_Simple(*mainaddr) tx.Fee = *feeamt tx.Timestamp = 1618839281 // 1 普通转账 addr1, _ := fields.CheckReadableAddress("1AVRuFXNFi3rdMrPH4hdqSgFrEBnWisWaS") amt1, _ := fields.NewAmountFromFinString("ㄜ500:248") act1 := actions.NewAction_1_SimpleToTransfer(*addr1, amt1) tx.AppendAction(act1) // 2 开启通道 addr2_1, _ := fields.CheckReadableAddress("1EDUeK8NAjrgYhgDFv9NJecn8dNyJJsu3y") addr2_2, _ := fields.CheckReadableAddress("1MzNY1oA3kfgYi75zquj3SRUPYztzXHzK9") channelid, _ := hex.DecodeString("277095b321f3ffe7e80f3dd328e2f338") amt2_1, _ := fields.NewAmountFromFinString("ㄜ500:248") amt2_2, _ := fields.NewAmountFromFinString("ㄜ239:248") act2 := actions.Action_2_OpenPaymentChannel{ ChannelId: channelid, LeftAddress: *addr2_1, LeftAmount: *amt2_1, RightAddress: *addr2_2, RightAmount: *amt2_2, } tx.AppendAction(&act2) // 3 关闭通道 // 打印 fmt.Println("tx hash:", tx.Hash().ToHex()) fmt.Println("tx hash with fee:", tx.HashWithFee().ToHex()) txtime := time.Unix(int64(tx.Timestamp), 0) fmt.Println("tx timestamp:", tx.GetTimestamp(), txtime.Format("2006-01-02 15:04:05")) fmt.Println("--------") txbody, _ := tx.Serialize() fmt.Println("tx body:", hex.EncodeToString(txbody)) fmt.Println("--------") } func Test_coinbaseCopy(t *testing.T) { cbtrs := NewTransaction_0_CoinbaseV0() addr, _ := fields.CheckReadableAddress("1AVRuFXNFi3rdMrPH4hdqSgFrEBnWisWaS") cbtrs.Address = *addr reward := fields.NewAmountNumSmallCoin(1) cbtrs.Reward = *reward cbtrs.Message = "ABC123" fmt.Println(cbtrs.Serialize()) clonetrs := cbtrs.Copy() fmt.Println(clonetrs.Serialize()) }
/** * Update the town authority window after a town authority setting change. * @param p1 Unused. * @return Always true. */ static bool RedrawTownAuthority(int32 p1) { SetWindowClassesDirty(WC_TOWN_AUTHORITY); return true; }
<gh_stars>1-10 // RUN: clang -x c-header -o %t.pch %s // RUN: echo > %t.empty.c // RUN: clang -include %t -x c %t.empty.c -emit-llvm -S -o - // PR 4489: Crash with PCH // PR 4492: Crash with PCH (round two) // PR 4509: Crash with PCH (round three) typedef struct _IO_FILE FILE; extern int fprintf (struct _IO_FILE *__restrict __stream, __const char *__restrict __format, ...); int x(void) { switch (1) { case 2: ; int y = 0; } } void y(void) { extern char z; fprintf (0, "a"); } struct y0 { int i; } y0[1] = {}; void x0(void) { extern char z0; fprintf (0, "a"); } void x1(void) { fprintf (0, "asdf"); } void y1(void) { extern char e; fprintf (0, "asdf"); }
package types import "time" type TestInstance struct { ID string RefID string EnqueuedAt *time.Time DequeuedAt *time.Time StartedAt *time.Time FinishedAt *time.Time IsSuccess bool KurlYAML string KurlURL string Output string OSName string OSVersion string OSImage string }
Terraria SpeedRun Team I am looking for experienced players of terraria to do speed runs for top leaderboards for a website called http://www.speedrun.com/terraria The top 5 man team has been dominating and I would like to dominate the 4 man teams and possibly 5 man. I am really excited for this and I see this weekend as the perfect oportunity to dominate the leaderboards. Skype is not required but helps as it leads us to more communication and better performance. Less time typing means faster time overall. Thanks! :DYou can add me on steam or through my skype here: desecratedbeast.mineplayI hope to hear from you guys soon. I will pick up to three people out of everyone that applys using the format below. I already have 1 other person that is confirmed on the team.Format for application:How many hours do you have on Terraria (can be split between accounts):How often do you play?:Do you have past experience with speed runs like these?:Are you up for commiting to a Speed Run team? (We cant have slackers):Give me one paragraph on why we should accept you to join our Speed Run team:Thank you for your interest in joining our Speed Run team and we will get back to you as soon as we can! :D
/** * Try to decode from short empty byte[] and try to decode from byte[], shorter then UnitHeader */ @Test public void testDecodeFromInvalidBytes(){ try{ ITCHCodec codec = (ITCHCodec) getMessageHelper().getCodec(serviceContext); byte[] b = new byte[1]; IoBuffer toDecode = IoBuffer.wrap( b ); toDecode.order(ByteOrder.LITTLE_ENDIAN); toDecode.position(0); IoSession decodeSession = new DummySession(); MockProtocolDecoderOutput decoderOutput = new MockProtocolDecoderOutput(); codec.decode( decodeSession, toDecode, decoderOutput ); Assert.assertEquals("Empty byte[] can not be decode", 0, decoderOutput.getMessageQueue().size()); b = new byte[3]; b[0]=0x2E; b[1]=0x00; b[2]=0x01; toDecode = IoBuffer.wrap( b ); toDecode.order(ByteOrder.LITTLE_ENDIAN); toDecode.position(0); decodeSession = new DummySession(); decoderOutput = new MockProtocolDecoderOutput(); codec.decode( decodeSession, toDecode, decoderOutput ); Assert.assertEquals("Empty byte[] can not be decode", 0, decoderOutput.getMessageQueue().size()); }catch(Exception e){ logger.error(e.getMessage(),e); Assert.fail(e.getMessage()); } }
#include <iostream> using namespace std; // WA 1xth test? int main(){ string arr[12]; for (int i = 0; i < 12; i++) { cin>>arr[i]; } bool s1,s2,s3,s4; bool couted = false; for (int i = 0; i < 10; i++) { for (int j = i+1; j < 11; j++) { s1 = arr[i][0] == arr[j][0]; s2 = arr[i][1] == arr[j][1]; s3 = arr[i][2] == arr[j][2]; s4 = arr[i][3] == arr[j][3]; for (int k = j+1; k < 12; k++) { if( ((arr[i][0] == arr[k][0]) == s1 && (arr[j][0] == arr[k][0]) == s1) &&((arr[i][1] == arr[k][1]) == s2 && (arr[j][1] == arr[k][1]) == s2) &&((arr[i][2] == arr[k][2]) == s3 && (arr[j][2] == arr[k][2]) == s3) &&((arr[i][3] == arr[k][3]) == s4 && (arr[j][3] == arr[k][3]) == s4) ){ couted = true; cout<<i+1<<' '<<j+1<<' '<<k+1<<'\n';} } } } if(!couted){ cout<<"no sets"; } return 0; }
<filename>src/pages/Topic/PostItem/index.tsx<gh_stars>10-100 import React, { useState } from 'react' import muiStyled from '@/muiStyled' import { Paper, Divider } from '@material-ui/core' import Header from './Header' import Content from './Content' import Actions from './Actions' import Awards from './Awards' import { getSinglePost } from '@/services/post' import { IPost, IUser } from '@cc98/api' const Wrapper = muiStyled(Paper).attrs({ square: true, elevation: 0, })({ marginTop: 6, }) interface Props { /** * 帖子信息 */ postInfo: IPost /** * 用户信息 */ userInfo: IUser | undefined /** * 是否热帖 */ isHot?: boolean /** * 是否追踪 */ isTrace?: boolean } const DELETE_CONTENT = '该贴已被 my CC98, my home' export default ({ postInfo, userInfo, isHot, isTrace = false }: Props) => { const [currentPost, setCurrentPost] = useState<IPost>(postInfo) if (postInfo.isDeleted) { postInfo.content = DELETE_CONTENT } const refreshPost = async () => { const res = await getSinglePost(postInfo.topicId, postInfo.floor) res.fail().succeed(post => { if (post.isDeleted) { post.content = DELETE_CONTENT if (userInfo) { userInfo.portraitUrl = '' } } setCurrentPost(post) }) } return ( <Wrapper> <Header postInfo={currentPost} userInfo={userInfo} isHot={isHot} /> <Content postInfo={currentPost} /> <Actions postInfo={currentPost} userInfo={userInfo} isTrace={isTrace} refreshPost={refreshPost} /> <Awards key={currentPost.awards ? currentPost.awards.length : 0} awards={currentPost.awards} /> <Divider /> </Wrapper> ) }
A combination of pharmacophore modeling, atom-based 3D-QSAR, molecular docking and molecular dynamics simulation studies on PDE4 enzyme inhibitors Phosphodiesterases 4 enzyme is an attractive target for the design of anti-inflammatory and bronchodilator agents. In the present study, pharmacophore and atom-based 3D-QSAR studies were carried out for pyrazolopyridine and quinoline derivatives using Schrödinger suite 2014-3. A four-point pharmacophore model was developed using 74 molecules having pIC50 ranging from 10.1 to 4.5. The best four feature model consists of one hydrogen bond acceptor, two aromatic rings, and one hydrophobic group. The pharmacophore hypothesis yielded a statistically significant 3D-QSAR model, with a high correlation coefficient (R2 = .9949), cross validation coefficient (Q2 = .7291), and Pearson-r (.9107) at six component partial least square factor. The external validation indicated that our QSAR model possessed high predictive power with R2 value of .88. The generated model was further validated by enrichment studies using the decoy test. Molecular docking, free energy calculation, and molecular dynamics (MD) simulation studies have been performed to explore the putative binding modes of these ligands. A 10-ns MD simulation confirmed the docking results of both stability of the 1XMU–ligand complex and the presumed active conformation. Outcomes of the present study provide insight in designing novel molecules with better PDE4 inhibitory activity.
def extract(self, url): if 'websocket' in self._FEATURE_DEPENDENCY and not HAVE_WEBSOCKET: raise ExtractorError('Please install websockets or websocket_client package via pip, or websockat command', expected=True) try: if 'yaml' in self._FEATURE_DEPENDENCY: __import__('yaml') except ImportError: raise ExtractorError('Please install pyyaml package via pip.', expected=True) try: for _ in range(2): try: self.initialize() self.write_debug('Extracting URL: %s' % url) ie_result = self._real_extract(url) if ie_result is None: return None if self._x_forwarded_for_ip: ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip subtitles = ie_result.get('subtitles') if (subtitles and 'live_chat' in subtitles and 'no-live-chat' in self.get_param('compat_opts', [])): del subtitles['live_chat'] return ie_result except GeoRestrictedError as e: if self.__maybe_fake_ip_and_retry(e.countries): continue raise except UnsupportedError: raise except ExtractorError as e: kwargs = { 'video_id': e.video_id or self.get_temp_id(url), 'ie': self.IE_NAME, 'tb': e.traceback or sys.exc_info()[2], 'expected': e.expected, 'cause': e.cause } if hasattr(e, 'countries'): kwargs['countries'] = e.countries raise type(e)(e.msg, **kwargs) except compat_http_client.IncompleteRead as e: raise ExtractorError('A network error has occurred.', cause=e, expected=True, video_id=self.get_temp_id(url)) except (KeyError, StopIteration) as e: raise ExtractorError('An extractor error has occurred.', cause=e, video_id=self.get_temp_id(url))
# **El pecho** ### **Philip Roth** Traducción de Jordi Fibla www.megustaleerebooks.com Índice El pecho Notas Biografía Créditos Acerca de Random House Mondadori _A Elizabeth Ames, directora ejecutiva_ _de Yaddo entre 1924 y 1970_ , _y a la corporación de Yaddo, Saratoga Springs_ , _Nueva York, los mejores amigos_ _que podría tener un escritor_ Empezó de una manera rara. Pero ¿habría podido empezar de otra manera, al margen de cómo empezara? Se ha dicho, claro está, que todo cuanto existe bajo el sol empieza de una manera rara y acaba de una manera rara, y que es raro. Una rosa perfecta es «rara», lo mismo que una rosa imperfecta y la bella rosa de común color rosado que crece en el jardín del vecino. Conozco la perspectiva según la cual todo lo que existe parece formidable y misterioso. Reflexiona sobre la eternidad, considera, si tienes valor, el olvido, y todo se transforma en un prodigio. De todos modos te diría, con toda humildad, que ciertas cosas son más prodigiosas que otras, y que yo soy una de tales cosas. Empezó de una manera rara... una comezón suave y esporádica en la ingle. Durante aquella primera semana, iba varias veces al día al lavabo contiguo a mi despacho en el edificio de la facultad de letras para bajarme los pantalones, pero al examinarme, y por minuciosa que fuese la búsqueda, no veía nada fuera de lo corriente. Aunque sin entusiasmo, decidí hacer caso omiso del picor. Siempre he sido un hipocondríaco tan impenitente, he estado tan atento a cualquier cambio en la temperatura corporal y la regularidad orgánica, que al hombre razonable que también era le resultaba imposible tomarse en serio mis reveladores síntomas. Pese a las sombrías premoniciones de extinción o parálisis o sufrimiento insoportable que acompañaban a cada nuevo dolor o acceso de fiebre, a los treinta y ocho años era un hombre vigoroso y de buen apetito, de metro ochenta, con buena postura y un físico esbelto, casi todo el pelo y la totalidad de los dientes, y sin haber padecido ninguna enfermedad grave. Aunque podría precipitarme a identificar la comezón en la ingle con algún trastorno neurológico como el herpes –o algo peor–, al mismo tiempo comprendía que indudablemente, como siempre, no era nada. Me equivocaba. Era algo. Transcurrió otra semana antes de que distinguiera una coloración rosada apenas perceptible de la piel bajo el vello púbico, pero una mancha tan tenue que finalmente me obligué a no seguir mirando, diciéndome que no era más que una pequeña irritación y, desde luego, nada preocupante. Al cabo de otra semana –lo cual, por cierto, constituía un período de incubación de veintiún días– bajé la vista al entrar en la ducha y descubrí que durante la agotadora jornada, con las clases, las reuniones, los viajes de ida al trabajo y vuelta y las comidas fuera de casa, la piel en la base de mi pene había adquirido una tonalidad rojo pálido. De inmediato concluí que se trataba del tinte de mis calzoncillos. (Que los calzoncillos que me había bajado a los tobillos fuesen de color azul claro no significaba nada en aquel momento de incredulidad y pánico.) Parecía _manchado_ , como si me hubieran aplastado algo –algún tipo de baya– en el pubis y el jugo, tras deslizarse hasta el miembro, hubiera coloreado irregularmente la raíz. En la ducha me enjaboné y aclaré el pene y el vello púbico tres veces, y entonces me recubrí cuidadosamente desde los muslos al ombligo con una gruesa capa de burbujeante jabón, masajeándome mientras contaba hasta sesenta. Cuando me aclaré con agua caliente –esta vez tanto que quemaba– la mancha seguía allí. No un sarpullido ni una costra ni una magulladura ni una llaga, sino un intenso cambio de pigmentación que enseguida asocié con el cáncer. Eran las doce, la hora en que tradicionalmente se producen las transformaciones en los relatos de horror, y una hora en la que era difícil conseguir un médico en Nueva York. Sin embargo, telefoneé de inmediato a mi médico, el doctor Gordon, y, pese al esfuerzo por ocultar mi alarma, él percibió claramente el temor y se ofreció a vestirse y cruzar la ciudad para examinarme. Tal vez si Claire hubiera estado conmigo aquella noche, en lugar de haberse quedado en su piso preparando un informe para el comité sobre planes de estudio, el mismo terror me habría impulsado a pedirle al médico que viniera corriendo. Por supuesto, dada la naturaleza de mis síntomas a aquella hora, es improbable que el doctor Gordon me hubiera enviado sin dilación al hospital, y tampoco parece, por lo que ahora sabemos –o seguimos sin saber–, que en el hospital pudieran haber hecho cualquier cosa para impedir o detener lo que estaba en marcha. El sufrimiento de las cuatro horas siguientes que hube de pasar a solas tal vez podría haber sido aliviado con morfina, pero nada indica que cualquier procedimiento médico, aparte de la eutanasia, pudiera haber invertido el rumbo del desastre. Con Claire a mi lado podría haberme derrumbado por completo, pero, en mi soledad, de repente me avergonzaba perder el dominio de mí mismo; no habían pasado más de cinco minutos desde el descubrimiento de la mancha, y allí estaba yo, mojado y desnudo en el sofá de piel, tratando en vano de superar el trémolo de mi voz mientras bajaba los ojos y describía por teléfono lo que veía. «Tranquilízate», me dije, así que me tranquilicé, como puedo hacerlo cuando me lo propongo. Si era lo que me temía, podía esperar hasta el día siguiente, y si no lo era, también podía esperar. Le dije al doctor que me pondría bien. Exhausto tras una dura jornada de trabajo, me había... sobresaltado. Iría a su consultorio (pensé que esto era una prueba de valor por mi parte) hacia mediodía. Él me dijo que fuese a las nueve. Accedí y, tan serenamente como pude, le di las buenas noches. Hasta que hube colgado el aparato y volví a examinarme bajo una luz intensa, no recordé que había un tercer síntoma, aparte del picor en la ingle y la decoloración del pene, que no le había mencionado al doctor. Hasta aquel momento lo había tomado por una señal de salud más que de enfermedad. Se trataba de la intensidad de la sensación local que había experimentado al hacer el amor con Claire durante las tres semanas anteriores. Para mí había significado el resurgimiento del deseo que antes sentía por ella; ni siquiera me molestaba en preguntarme de dónde o por qué, tan encantado –y tan aliviado– me sentía por su retorno. Lo cierto era que la intensa lujuria que su belleza física había despertado en mí durante los dos primeros años de nuestra relación se había ido reduciendo desde hacía casi un año. Hasta fecha reciente, le hacía el amor no más de dos o tres veces al mes, y lo más frecuente era que fuese ella la incitadora. Mi enfriamiento –mi frialdad– era penoso para los dos, pero como ambos habíamos padecido no pocos trastornos emocionales (ella de niña con sus padres, yo de adulto con mi mujer), éramos igualmente reacios a dar cualquier paso hacia la ruptura de nuestra unión. Por descorazonador que fuese para una encantadora y voluptuosa joven de veinticinco años verse rechazada una noche tras otra, Claire no mostraba externamente ni un ápice de la suspicacia, la frustración o la cólera que incluso a mí me habrían parecido justificadas, el origen de su desdicha. Sí, ella paga un precio por su ecuanimidad (no es la mujer más expresiva que jamás he conocido, pese a su pasión sexual), pero he llegado a la etapa de la vida –es decir, había llegado– en la que el puerto sereno y sus plácidas aguas me gustaban más que el espumeante dramatismo de alta mar. Por supuesto, había ocasiones –cuando estábamos en compañía o a veces solos después de cenar– en que podría haber deseado que ella fuese más animada y más receptiva, pero estaba demasiado satisfecho de aquella sensatez suya en la que podía confiar para que me decepcionara su falta de viveza. Ya había tenido suficiente viveza con mi mujer. Lo cierto es que, a lo largo de tres años, Claire y yo habíamos encontrado una manera de vivir juntos (que en parte suponía vivir separados) que nos proporcionaba la calidez y la seguridad de nuestro mutuo afecto, sin la dependencia acompañante, ni el agotador aburrimiento, ni el ansia desenfrenada y descentrada, ni las estrategias, durante las veinticuatro horas del día, del engaño y el apaciguamiento que parecían haber amargado a todos menos unos pocos de los matrimonios que conocíamos. Un año atrás había puesto fin a cinco años de psicoanálisis convencido de que las heridas sufridas en el Gran Guiñol de mi matrimonio habían cicatrizado tan bien como era posible que lo hicieran, y en gran parte gracias a mi vida en común con Claire. Tal vez no fuese yo el hombre que había sido, pero tampoco era un soldado raso herido, lleno de vendajes y tocando el tambor de la compasión de sí mismo, procedente de ese campo de batalla conocido como Hogar. La vida se había vuelto ordenada y estable, la primera vez que podía decir tal cosa en más de una década. La verdad es que nos llevábamos bien con tal facilidad y tan pocas tensiones, nos gustábamos tanto el uno al otro que cuando, inesperadamente, dejé de experimentar por completo placer cuando hacíamos el amor, lo consideré un desastre (poco sabía entonces de desastres). Fue un acontecimiento deprimente y desconcertante, y, por mucho que me empeñara, parecía incapaz de alterarlo. Lo cierto es que tenía concertada una cita con mi ex analista para hablarle de cómo me estaba afectando aquella situación cuando, también inesperadamente, de repente era más apasionado con ella de lo que había sido jamás con cualquier otra. Pero «pasión» no es la palabra apropiada: un bebé en la cuna no siente pasión cuando le divierten haciéndole cosquillas bajo la barbilla. Me refiero a un placer del todo táctil: ni sexo en la cabeza ni en el corazón, sino, delicioso tormento, en la epidermis del pene, limitado a la superficie y generador de éxtasis. Era una clase de placer que me llevaba a contorsionarme y aferrar las sábanas, hacía que me retorciera y diese vueltas en la cama con un irreprimible abandono que anteriormente había considerado más propio de las mujeres que de los hombres y, en el caso de las mujeres, más imaginario que real. Durante la última semana de mi período de incubación, a punto estuve de llorar tan solo debido al tortuoso placer de la fricción. Al correrme, le lamía a Claire la oreja como un perro. Le lamía el pelo. Jadeante, me lamía mi propio hombro. ¡Me había salvado! ¡Mi vida en común con Claire no corría peligro! Tras haber yacido indiferente a su lado durante casi un año, tras haber empezado a temer lo peor acerca de nuestro futuro, de alguna manera –¡bendita y misteriosa manera!– había encontrado el camino hacia un terreno de pura y primitiva sensibilidad erótica, donde el vínculo entre nosotros solo podía reforzarse. –¿Es esto lo que se considera disipación? –le pregunté a mi feliz amiga, cuya pálida piel tenía las marcas de mis dientes–. Nunca había experimentado una cosa igual. Ella se limitó a sonreír y cerró los ojos para sentirse un poco más en el séptimo cielo. Tenía el cabello empapado en sudor, como el de una niña que hubiera jugado demasiado tiempo al aire libre un día muy caluroso. Claire satisfecha, donante de satisfacción. Afortunado David. No podríamos haber sido más felices. Por desgracia, lo que me ha sucedido es algo que nadie ha experimentado jamás, algo que se encuentra más allá de la comprensión, más allá de la solidaridad, más allá de la comedia. Desde luego, no faltan quienes afirman estar al borde de una explicación científica concluyente; los hay, mis fieles visitantes, cuya compasión no parece tener límites; y luego, ahí fuera, en el mundo, aquellos –¿por qué no habrían de hacerlo?– que no pueden evitar reírse. Y, mira, hay ocasiones en las que incluso soy uno de ellos: comprendo, siento compasión y también veo la broma. Gozar de ella es otra cuestión. Si pudiera sostener la risa más de unos pocos segundos... si no fuese tan breve y tan amarga. Claro que tal vez deba esperar aún más regocijo, si los médicos son capaces de mantenerme vivo en semejante estado, y si yo sigo deseando que lo hagan. Soy un pecho. Un fenómeno que me han descrito de diversas maneras, como «un influjo hormonal masivo», «una catástrofe endocrinopática» o «una explosión hermafrodítica de cromosomas», tuvo lugar en mi organismo entre la medianoche y las cuatro de la madrugada del 18 de febrero de 1971 y me convirtió en una glándula mamaria sin ninguna relación con ninguna forma humana, como solo podría aparecer, habría pensado uno, en un sueño o una pintura de Dalí. Me dicen que ahora soy un organismo con la forma general de un balón de fútbol norteamericano o de un dirigible; dicen que tengo una consistencia esponjosa, peso setenta y tres kilos (antes pesaba setenta y cinco) y que sigo midiendo metro ochenta de altura. Aunque conservo, si bien dañado y de forma «irregular», gran parte de los sistemas cardiovascular y nervioso, un sistema excretor calificado como «reducido y primitivo» y un sistema respiratorio que termina justo por encima del diafragma en algo que recuerda un ombligo con un opérculo, la arquitectura básica en la que estas características humanas están desordenadas y enterradas es la de un pecho de mamífero hembra. La mayor parte de mi peso corresponde a tejido adiposo. Por un extremo estoy redondeado como una sandía, por el otro finalizo en un pezón, de forma cilíndrica, que se proyecta trece centímetros desde mi «cuerpo» y está perforado en la punta por diecisiete aberturas, cada una más o menos de la mitad del tamaño de un orificio uretral masculino. Estas son las aberturas de los conductos lactíferos. Tal como lo entiendo sin la ayuda de diagramas, pues estoy ciego, los conductos se ramifican hacia atrás en lóbulos compuestos por la clase de células que segregan leche y que es transportada a la superficie del pezón normal al succionarlo o bien ordeñarlo mecánicamente. Mi piel es suave y «juvenil», y sigo siendo de «raza blanca». El color del pezón es rosado. Esto último se considera peculiar, puesto que en mi encarnación anterior era muy moreno. Como le dije al endocrinólogo que hizo esta observación, me parece menos peculiar que otros aspectos de la transformación, claro que yo no soy endocrinólogo. Un chiste lleno de amargura, pero chiste al fin y al cabo, y deben de haberlo observado y anotado. El pezón es rosado, como la mancha en la base del pene que descubrí la noche en que empezó todo esto. Dado que los orificios del pezón me proporcionan algo similar a una boca y oídos vestigiales (por lo menos me ha parecido que soy capaz de hacerme oír a través del pezón y percibir vagamente lo que sucede a mi alrededor), había supuesto que era mi cabeza lo que se había transformado en pezón, pero los médicos son de otra opinión, por lo menos desde el mes corriente. En primer lugar, no hay duda de que mi voz, por débil que sea, emana del opérculo en el diafragma, a pesar de que mi sentido del paisaje interno siga asociando tercamente las funciones de la conciencia con el punto más elevado del cuerpo. Ahora los médicos sostienen que la piel arrugada y áspera del pezón (que, desde luego, es exquisitamente sensible al tacto, como ningún tejido de la cara, incluida la membrana mucosa de los labios) se ha formado a partir del glande. La fruncida y rosada areola que rodea al pezón parece ser una metamorfosis del miembro bajo el ataque de una secreción volcánica del fluido «mamogénico» de la pituitaria. Dos pelos largos y rojizos se extienden desde una de las pequeñas elevaciones en el borde de mi areola. –¿Qué longitud tienen? –Dieciocho centímetros exactamente. –Mis antenas. –Amargura. Luego incredulidad–. ¿Quiere tirar de uno de ellos, por favor? –Si lo desea, David, tiraré de él con mucha suavidad. El doctor Gordon no mentía. Había tirado de uno de mis pelos. Una sensación bastante familiar, tanto que deseé estar muerto. Por supuesto, transcurrieron varios días después del cambio (¡el «cambio»!) antes de que recobrara la conciencia, y otra semana antes de que me dijeran algo, aparte de que había estado «muy enfermo» con un «desequilibrio endocrino». Cada vez que me despertaba y descubría de nuevo que no podía ver, oler, saborear y moverme me lamentaba y aullaba de tal modo que debían mantenerme bajo una fuerte sedación. Cuando me tocaban el «cuerpo» no sabía a qué carta quedarme: la sensación era inesperadamente tranquilizante, pero lejana, y me recordaba el lamido del agua en una playa. Una mañana, al despertar, noté que les sucedía algo nuevo a mis extremidades. No era dolor, al contrario, la sensación era más bien agradable, y no obstante me parecía tan extraño sentir aquello que grité. –¡Me he quemado! ¡Ha sido un incendio! –Cálmese, señor Kepesh –me dijo una mujer–. Solo le estoy lavando. Me limito a lavarle la cara. –¿La cara? ¿Dónde está? ¿Dónde están mis brazos? ¿Y mis piernas? ¿Dónde está mi boca? ¿Qué me ha ocurrido? Entonces habló el doctor Gordon. –Se encuentra en el hospital Lenox Hill, David. Está en una habitación particular en la séptima planta. Lleva aquí diez días. Le he visitado a diario por la mañana y la noche. Disfruta usted de excelentes cuidados y de todas las atenciones que requiere. En estos momentos le están lavando con una esponja, agua templada y jabón. Eso es todo. ¿Acaso le duele lo que le están haciendo? –No –gemí–, pero ¿dónde está mi cara? –Deje que la enfermera le lave y dentro de un rato hablaremos. Debe descansar todo lo que pueda. –¿Qué me ha ocurrido? Recordaba el dolor y el terror, pero nada más: había sido como si me hubiesen disparado una y otra vez desde un cañón contra un muro de ladrillo y a continuación me hubiera pisoteado un ejército de botas. En realidad era más bien como si hubiera sido un hombre de caramelo masticable, extendido en direcciones opuestas por el pene y las nalgas, hasta llegar a ser tan ancho como largo había sido. Los médicos me dicen que no pude estar consciente más que unos pocos minutos una vez iniciada la «catástrofe», pero, al rememorarlo, me parece que estuve despierto para notar que cada hueso de mi cuerpo se quebraba y reducía a polvo. –Si ahora pudiera relajarse... –¿Cómo me alimentan? –Intravenosamente. No debe preocuparse. Se le alimenta todo lo necesario. –¿Dónde están mis brazos? –Deje que la enfermera le lave y luego le friccione con aceite, y ya verá cómo se siente mucho mejor. Entonces podrá dormir. Cada mañana me despertaban así, pero pasó otra semana o más tiempo antes de que estuviera lo bastante calmado (o aletargado) para asociar las sensaciones del lavado con la excitación erótica. Por entonces estaba convencido de que me habían amputado las extremidades superiores e inferiores, de que la caldera, que estaba bajo mi piso, había estallado y de que la explosión me había dejado ciego y mutilado. Sollozaba casi continuamente, pues no daba el menor crédito a las explicaciones sobre las hormonas que el doctor Gordon proponía como el origen de mi «enfermedad». Entonces, una mañana, agotado y entumecido al cabo de varios días de llorar sin lágrimas, noté que me excitaba, una suave palpitación en la vecindad de lo que todavía consideraba mi cara, una agradable sensación de... tumefacción. –¿Le gusta así? –¡La voz era masculina! ¡Un desconocido! –¿Quién eres? ¿Dónde estoy? ¿Qué está pasando? –Soy el enfermero. –¿Dónde está la otra enfermera? –Hoy es domingo. Cálmese, no ha venido porque es domingo. A la mañana siguiente, la enfermera habitual, la señorita Clark, entró de servicio, acompañada por el doctor Gordon. Me lavaron, bajo la supervisión del doctor, y esta vez, cuando empecé a experimentar las sensaciones que acompañan a las caricias eróticas, dejé que me envolvieran. –Ah –susurré–, qué agradable es. –¿A qué se refiere? –me preguntó el doctor Gordon–. ¿Qué está diciendo, David? La enfermera empezó a restregarme con aceite. Notaba cada uno de sus dedos masajeando aquella cara que ya no era una cara. Todo mi ser hervía con la sensación de inminencia que precede a una eyaculación perfecta. –Oh, Dios mío, qué fenomenal es esto –dije, y me puse a sollozar de un modo tan incontrolable que tuvieron que sedarme de nuevo. Poco después entró el doctor Gordon acompañado por el doctor Klinger, quien había sido mi psicoanalista durante cinco años, y me dijeron qué era aquello en lo que me había convertido. Me lavaban suavemente pero a fondo cada mañana, luego me embadurnaban de aceite y me daban un masaje. Después de escuchar la verdad de lo sucedido, después de saber que ahora vivía en una hamaca, el pezón en un extremo, la redondeada y prominente parte inferior en el otro, y con dos cabestrillos de terciopelo sujetando mi volumen en su lugar, transcurrieron varios meses antes de que aquellas abluciones matinales me procurasen el menor placer. E incluso entonces, solo cuando el doctor Gordon consintió en dejarme a solas con la enfermera, fui capaz de abandonarme de nuevo por completo a las atentas manos de la señorita Clark. Pero cuando lo hacía, las palpaciones eran casi insoportables, un «casi» delicioso, un frenesí similar a lo que había experimentado en aquellas últimas semanas de relación sexual con Claire, pero que parecía incluso más intenso, pues lo experimentaba en un estado de absoluta impotencia e inesperadamente, y provocado por aquellas manos dedicadas por completo a despertar mi excitación. Una vez finalizada la sesión, cuando la señorita Clark se había retirado con la palangana de agua tibia y los frascos de aceite (yo imaginaba unos frascos coloreados), la hamaca se mecía cómodamente a uno y otro lado, hasta que por fin cedía mi agitación, el pezón se ablandaba y me sumía en el sueño del saciado. Digo que el doctor consentía en dejarnos a solas en la habitación, pero ¿cómo sé que alguien me ha dejado solo o incluso que me encuentro en una habitación? El doctor Gordon me asegura que no estoy sometido a más vigilancia que la de cualquier otro caso difícil, que no me exhiben en un anfiteatro de facultad de medicina ni estoy bajo las cámaras de un circuito cerrado de televisión... pero ¿qué le impediría mentirme? Dudo de que en medio de esta calamidad haya alguien que se preocupe por mis libertades civiles. Eso sí que haría reír. ¿Y qué me importa si no estoy solo cuando creo que lo estoy? Si me encuentro bajo una cúpula insonorizada en una plataforma colocada en medio de Madison Square Garden, si me exhiben en un escaparate de Macy's, ¿qué más me da? Dondequiera que me hayan puesto, por numerosos que sean los espectadores, la verdad es que estoy tan solo como cualquiera podría desear estarlo. Es mejor que deje de pensar en mi «dignidad», al margen de lo que significara para mí cuando era profesor de literatura, amante, hijo, amigo, vecino, consumidor, cliente y ciudadano. Si jamás ha habido una época para olvidar las convenciones, el decoro y el orgullo personal, es ahora. Pero como estas son cuestiones íntimamente relacionadas con mi idea de la cordura y el amor propio, la verdad es que en estos momentos me siento atribulado como nunca lo estuve en mi vida anterior, en la que adoptaba con toda facilidad el comedimiento social practicado por las clases educadas, y al hacerlo así experimentaba una auténtica satisfacción. Ahora la idea de que mis sesiones matinales con la señorita Clark se retransmiten en directo por el circuito de televisión interno del hospital, que mis delirantes contorsiones son observadas por decenas de científicos reunidos en la galería por encima de mí... en fin, a veces eso resulta casi tan insoportable como todo lo demás. Sin embargo, cuando el doctor Gordon me asegura que respetan mi «intimidad», ya no le llevo la contraria, sino que le expreso mi agradecimiento, y de esa manera soy capaz por lo menos de fingir ante ellos que creo estar solo aunque no lo esté. Mira, no se trata de hacer lo correcto o lo bien visto; puedo asegurarte que me tiene sin cuidado la etiqueta que conlleva ser un pecho. Lo que me importa es hacer lo que debo, seguir siendo yo. Pues, de lo contrario, ¿quién o qué soy? O bien no dejo de ser yo mismo o bien enloquezco y luego me muero. Y parece ser que no quiero morir. Eso también es una sorpresa para mí, pero ahí está. Tampoco preveo un milagro, una especie de ataque como represalia por parte de mis hormonas antimamogénicas, si existen tales (y solo Dios sabe si existen en una cosa como la que soy ahora), que reparará el daño. Sospecho que es un poco tarde para eso, y por ello si el pecho humano sigue deseando existir no es porque albergue semejante esperanza. Insisto en que soy humano, pero no tan humano. Tampoco creo que lo peor haya pasado. Tengo la sensación de que lo peor está por llegar. No, se trata sencillamente de que, como la muerte me aterra desde los dos años de edad, me he atrincherado en el odio que le tengo, he adoptado una postura personal contra la muerte que parezco incapaz de modificar debido a que me ha ocurrido «esto». Sí, «esto» es en verdad horrible, pero, por otro lado, hace tanto tiempo que no deseo morir que me resulta imposible cambiar de actitud de la noche a la mañana. Necesito tiempo. Como puedes imaginar, mi supervivencia es de gran interés para la ciencia médica. Microbiólogos, psicólogos y bioquímicos siguen estudiando _ese_ milagro, tanto aquí, en el hospital, como, según me dicen, en instituciones médicas de todo el país. Están tratando de averiguar qué es lo que me hace seguir vivo. El doctor Klinger opina que no importa cómo unan las piezas del rompecabezas, porque al final todo se reducirá a esas manidas expresiones de púlpito, «fuerza de carácter» y «voluntad de vivir». ¿Y quién soy yo para no estar de acuerdo con tan heroica percepción de mi persona? –Entonces parece ser que mi análisis ha «cuajado» –le digo al doctor Klinger–. Es usted digno de alabanza, señor. Él se ríe. –Siempre ha sido usted más fuerte de lo que creía –replica. –Habría preferido no tener nunca que descubrirlo. Y, además, eso no es cierto. No puedo vivir así mucho más tiempo. –Sin embargo, ha de hacerlo, y ciertamente lo hace. –Sí, lo hago, pero no puedo. Nunca he sido fuerte. Tan solo resuelto. Un pie delante del otro. Buenas calificaciones en todas las asignaturas. Se remonta a la época en que entregaba los deberes a tiempo y me llevaba los premios. Estar aquí dentro es espantoso, doctor Klinger. Quiero abandonar, quiero volverme loco, salir dando tumbos, echando pestes y delirante, solo que no puedo. Sollozo. Grito. Toco fondo. ¡Me quedo ahí tendido en ese fondo! Pero entonces vuelvo en mí. Hago mis chistecillos mordaces. Escucho la radio. Escucho el fonógrafo. Pienso en lo que hemos dicho. Refreno mi furor y mi amargura, y espero a que usted vuelva a visitarme. Pero esto, volver en mí, es una locura. Poner un pie delante del otro es una locura, ¡sobre todo porque no tengo pies! ¡Esta cosa atroz ha sucedido, y escucho las noticias de las seis de la tarde! ¡Esta increíble catástrofe, y escucho el boletín meteorológico! No, no, dice el doctor Klinger: fuerza de carácter, voluntad de vivir. Le digo que quiero enloquecer, y él responde que es imposible: eso está más allá de mí, está por debajo de mí. Ha sido necesario «esto» para descubrir que soy una ciudadela de cordura. Así pues, puede que finja otra cosa, pero sé que me están estudiando, mirándome como contemplarían desde el fondo de vidrio de un barco la vida privada de una marsopa o un manatí. Pienso en esos mamíferos acuáticos debido al parecido general que tengo con ellos, lo sé, en tamaño y forma, y porque de la marsopa en particular se dice que es una criatura inteligente, tal vez incluso racional. Una marsopa con doctorado, el profesor adjunto Marsopa Kepesh. A decir verdad, en una clase de vida como esta, lo que uno echa más en falta es la estupidez, la trivialidad, la falta de sentido de la vida, pues, aparte de la realidad monstruosa y ridícula en que me he convertido, está la responsabilidad intelectual que parece desprenderse de esta absurda desgracia. ¿QUÉ SIGNIFICA? ¿CÓMO HA PODIDO SUCEDER? ¿POR QUÉ, EN TODA LA HISTORIA DEL GÉNERO HUMANO, HA TENIDO QUE OCURRIRLE AL PROFESOR KEPESH? Sí, el doctor Klinger actúa de un modo inteligente al atenerse a lo que es corriente y familiar, al soltar su cantinela sobre la fuerza de carácter y la voluntad de vivir. Mejor estas banalidades que lo altisonante o lo apocalíptico, ya que, por más que sea la ciudadela de la cordura, mi capacidad de aguante tiene un límite. Que yo sepa, mis únicos visitantes, aparte de los científicos, los médicos y el personal del hospital, han sido Claire, mi padre y Arthur Schonbrunn, el ex presidente de mi departamento y ahora decano de Artes y Ciencias. El comportamiento de mi padre ha sido asombroso. No sé cómo explicarlo, y tan solo puedo decir que hasta ahora no había sabido qué clase de hombre es en realidad. Nadie lo sabía. Agresivo, astuto, tiránico en su trabajo, pero con nosotros, su pequeña familia, inocente, protector, tierno y profundamente afectuoso. Pero ese dominio de sí mismo cuando se enfrenta al horror... ¿Quién habría esperado tal cosa del propietario de un hotel de segunda clase en South Fallsburg? Empezó como cocinero de comidas rápidas y llegó a ser el propietario del establecimiento. Ahora está jubilado y «mata el tiempo» por las mañanas respondiendo a las llamadas telefónicas en el servicio de catering, un negocio boyante, que su hermano posee en Bayside. Una vez a la semana viene a visitarme, se sienta en una silla colocada al lado de mi pezón y me cuenta todas las noticias acerca de las personas invitadas a nuestra casa en el pasado. ¿Te acuerdas de Abrams, el sombrerero? ¿De Cohen, el pedicuro? ¿Te acuerdas de Rosenheim, con sus trucos de naipes y el Cadillac? Sí, sí, creo que sí. Pues bien, uno se está muriendo, el otro se ha mudado, el hijo de aquel se ha casado con una egipcia. –¿Qué te parece eso? –Ni siquiera sabía que allí estuviera permitida tal cosa. Es una actuación impresionante. Pero ¿se trata realmente de una actuación? ¿Es el actor más brillante del mundo o tan solo un bobalicón, o acaso se ha vuelto por completo insensible? ¿O no tiene más alternativa que seguir comportándose como siempre? «Pero ¿no ve lo que ha sucedido? ¿No comprende que ciertas cosas son todavía más extraordinarias que el hecho de que un judío se case con una egipcia?» Está conmigo una hora, y entonces regresa a casa, sin darme un beso. Eso de que mi padre se marche sin darme un beso es una novedad. Y entonces es cuando me doy cuenta de que no es un bobalicón y lo que hace en realidad es actuar, y pienso que mi padre es un gran hombre, valiente y noble. ¿Y mi nerviosa madre? Por suerte para ella está muerta; de lo contrario, esto la habría matado. ¿O también me equivoco con respecto a ella? Soportó a panaderos alcohólicos, confeccionadores de ensaladas homicidas y ayudantes de camarero que todavía se orinaban en la cama, de modo que, quién sabe, tal vez también podría haberme soportado. Bestias, los llamaba, animales de establo, pero siempre volvía a los pucheros, a los productos de limpieza, las fregonas y la ropa blanca, pese a la angustia que la embargaba desde la semana del Memorial Day hasta el Yom Kippur debido a la radical imperfección de la ayuda que le prestábamos. Para empezar, ¿no fue de mi madre de quien adquirí la cualidad de tener resolución? ¿No aprendí de su ejemplo la manera en que uno pasa del verano al invierno y de nuevo al verano, a pesar de todo? Así pues, más trivialidad todavía: estoy dispuesto a soportar mi condición de glándula mamaria debido a mi crianza en un típico hotel de Catskill donde ocurría una crisis tras otra. Claire, cuya ecuanimidad desde el principio ha sido tan tonificante para mí, un antídoto relajante contra el carácter impulsivo de mi ex mujer, e incluso supongo que contra las palpitaciones de mi madre y las crisis en la cocina del hotel, Claire, curiosamente, no mostraba ni mucho menos la capacidad de mi padre para reprimir su angustia desde el primer momento. Pero lo sorprendente no eran sus lágrimas, sino el peso de su cabeza sobre mi zona central cuando no pudo contenerse y empezó a sollozar. «¿Su cara sobre esta carne? ¿Cómo puede tocarme?» Había esperado que no volviera a tocarme nadie más aparte del personal médico. «Si Claire se hubiera convertido en un pene...», me dije. Pero esa idea era demasiado ridícula, en la medida en que tal cosa no había sucedido, por supuesto. Además, lo ocurrido me había ocurrido a mí y a nadie más que a mí, porque no le podía ocurrir a nadie más, y aunque no supiera por qué era así, lo cierto es que era así, y debía de haber razones para que lo fuera, tanto si alguna vez iba a conocerlas como si no. Tal vez, como observaba el doctor Klinger, ponerme en el lugar de Claire rebasaba con creces el cumplimiento del deber. Tal vez; pero si Claire se hubiera convertido en un miembro viril de metro ochenta de longitud, dudo de que yo hubiera sido capaz de semejante lealtad. Tan solo unos pocos días después de su primera visita, Claire consintió en masajearme el pezón. Si se hubiera puesto a llorar a cierta distancia de mí, nunca habría podido sugerirle que lo hiciera, pero en cuanto noté el peso de su cabeza sobre mí, todas las posibilidades se abrieron en mi mente, y solo fue cuestión de tiempo (y no demasiado, por cierto) antes de que me atreviera a pedirle el supremo acto de esperpento sexual, dadas las circunstancias. Antes de seguir adelante, debo aclarar que Claire no es precisamente una zorra; a pesar de que durante nuestra relación amorosa las prácticas sexuales corrientes la habían excitado de maravilla, no le gustaba nada, por ejemplo, el coito _per anum_ , e incluso le daba asco recibir mi semen en la boca. Si llevaba a cabo la felación, era solo como un breve antecedente del acto, y jamás con la intención de prolongarla hasta que me corriera. No me quejaba agriamente de esta actitud, pero de vez en cuando, como acostumbran a hacer los hombres que aún no se han convertido en pechos, expresaba mi insatisfacción. Veréis, no estaba obteniendo de la vida todo lo que deseaba. Sin embargo, fue Claire quien propuso jugar con mi pezón si eso era lo que más deseaba. Sucedió durante su cuarta visita en cuatro días. Le había contado por primera vez cómo me atendía la enfermera por la mañana, con la intención de no decirle más que eso, por lo menos de momento, pero Claire me lo planteó. –¿Te gustaría que te hiciera lo mismo que ella? –¿Me harías... eso? –Pues claro, si quieres que te lo haga. Pues claro. ¡Una chica fría e imperturbable! –¡Quiero que lo hagas! –grité–. Hazlo, por favor. –Entonces dime qué es lo que te gusta –dijo ella–. Dime qué es lo que resulta más agradable. –Oye, Claire, ¿hay alguien más en la habitación? –No, no, solo tú y yo. –¿Nos están televisando? –Pero qué dices, cariño, claro que no. –Entonces apriétame, ¡apriétame fuerte! Al cabo de unos días, después de que le hubiera hablado de un modo incoherente acerca de mi enfermera durante casi una hora, Claire volvió a preguntarme: –¿Qué ocurre, David, vida mía? ¿Quieres que te chupe? –¡Sí! ¡Sí! ¿Cómo es capaz de hacerlo? ¿Por qué lo hace? ¿Lo haría yo? Es demasiado pedir –le digo al doctor Klinger–. Es demasiado terrible. Es preciso que ponga fin a esto. Quiero que ella lo haga continuamente, durante todo el tiempo de la visita. Ya no quiero hablar, no quiero que me lea, ni siquiera la escucho. Solo deseo que me apriete, me chupe y me lama. Nunca me canso de eso. Cuando ella se detiene, es insoportable. «¡Sigue! ¡Más! ¡Sigue!», le grito. Pero si no pongo fin a esto, dejará de venir a verme, lo sé. Y entonces no tendré a nadie. Entonces tendré a la enfermera por la mañana, y eso será todo. Vendrá mi padre y me hablará de quién se ha muerto y quién se ha casado. Y usted vendrá y me hablará de la fortaleza de mi carácter y mi voluntad de vivir. ¡Pero no tendré una mujer! ¡No estará Claire ni habrá sexo ni amor nunca más! Quiero que se desnude, doctor, pero ¿cómo puedo pedírselo? No quiero alejarla de mí, las cosas ya son bastante extrañas tal como están, pero quiero que se desnude, quiero que su ropa esté en el suelo, alrededor de sus pies. Quiero que se ponga encima de mí y se mueva. ¡Quiero tirármela, doctor! ¡Con el pezón! ¡Pero si le digo eso, se marchará! ¡Se irá corriendo y nunca volverá! Claire me visita todas las noches, después de la cena. Durante el día da clases a los alumnos de cuarto curso en la escuela de la calle Bank, aquí, en Nueva York. Es graduada por Cornell y miembro de la Phi Beta Kappa, su madre es directora de escuela en Schenectady y está divorciada de su padre, ingeniero de la Western Electric. Su hermana mayor está casada con un economista del Departamento de Comercio, y vive con él y cuatro hijos en Alexandria, Virginia. Tienen una casa en South Beach, en Martha's Vineyard, donde Claire y yo les visitamos el verano pasado cuando íbamos camino de Nantucket para pasar una semana de vacaciones. Discutimos de política... la guerra de Vietnam. Entonces jugamos a lanzar y recoger pelotas de béisbol con los niños, tras lo cual fuimos a comer langosta hervida a Edgartown; luego fuimos al cine y, allí sentados, éramos unos carnívoros voluminosos, robustos y peludos, reducidos en la cómoda oscuridad a tan solo unas caras curtidas por el viento y unos dedos pringados de mantequilla. Delicioso. Lo pasamos muy bien, de veras, «convencionales» como lo eran nuestros anfitriones; sé que eran convencionales porque me lo decían una y otra vez. Pero lo pasamos muy bien. A ella vale la pena verla en la playa, una rubia de ojos verdes, alta, esbelta y con grandes pechos. Incluso cuando el deseo menguaba, nada me gustaba más que echarme en la cama y mirarla mientras se vestía por la mañana y se desnudaba por la noche. Allá, en el hueco de las dunas, le desato la parte superior del biquini y las veo caer. «Imagina dónde estarán a los cincuenta si a los veinticinco caen así», me dice. «No puedo imaginar eso, no quiero», replico y, poniéndola de rodillas, me recuesto en la arena caliente, hinco los talones, cierro los ojos y aguardo con los labios abiertos a que su pecho me llene la boca. ¡Qué sensación, con el mar resonando allá abajo! ¡Como si fuese el mismo globo, un globo blando y succionable! ¡Y yo Poseidón o Zeus! Ah, nada supera a los placeres del dios antropomórfico. «Pasemos todo el verano próximo junto al mar», le digo, como lo hace la gente el primer día feliz de las vacaciones. Claire susurra: «Primero vayamos a casa y hagamos el amor». Ha pasado cierto tiempo desde la última vez, tiene razón. «Oh, quedémonos aquí tendidos –le digo–. ¿Dónde está esa cosa tan extraña? Sí, otra vez, otra vez.» «No quiero que te quedes sin respiración. Te estabas poniendo verde.» «De envidia», replico. Sí, admito sinceramente que eso es lo que decía. Y si se tratara de un cuento de hadas en lugar de mi vida, ahora vendría la moraleja: «Ten cuidado con los deseos ridículos, pues es posible que tengas suerte». Pero como no hay duda de que esto no es un cuento de hadas (por lo menos no lo es para mí, querido lector), ¿por qué semejante deseo habría de ser el que se hiciera realidad? Te aseguro que he deseado en mi vida cosas mucho más caprichosas que succionar un pecho en aquella playa. ¿Por qué unas palabras juguetonas y amorosas, pronunciadas aquel primer día de nuestras idílicas vacaciones, habrían de encarnarse, mientras que todo cuanto he deseado vivamente solo he podido conseguirlo, si es que lo he conseguido, poniendo un pie delante del otro en el transcurso de treinta y ocho años? No, me niego a supeditar mi desconcierto a la teoría de la satisfacción de los deseos. Por pulcra, moderna y deliciosamente punitiva que sea, me niego a creer que esto sea algo que deseaba ser. ¡No! La realidad es más imponente que eso, la realidad tiene cierta distinción. Ahí lo tienes. Para los que prefieran un cuento de hadas a la vida, una moraleja: «La realidad –concluye el amargado profesor que, por razones que desconoce, se ha convertido en un pecho femenino– tiene distinción». ¡Andad, elegantes houyhnhnms satisfechos de vosotros mismos a los que nada repugnante ha sucedido todavía, andad a moralizar sobre eso! No fue a Claire a quien le hice entonces mi «grotesca» propuesta, sino a mi enfermera. –¿Sabe lo que me gustaría hacer cuando me lava así? –le pregunté–. ¿Puedo decirle en qué estoy pensando ahora mismo? –¿En qué, profesor Kepesh? –Me gustaría tirármela con mi pezón. –No le oigo, profesor. –¡Me excito tanto que quiero tirármela! ¡Quiero que se siente sobre mi pezón... que me ponga ahí el coño! –Solo un poco más y ya estará... –¿Me has oído, puta? ¿Has oído lo que quiero? –Ahora lo estoy secando... Cuando el doctor Klinger llegó a las cuatro, me carcomía el remordimiento. Incluso empecé a sollozar un poco cuando le dije lo que había hecho a pesar de mis recelos y de su advertencia. Le dije que ahora todo estaba registrado en cinta magnetofónica, y muy bien podría salir en los periódicos sensacionalistas del día siguiente. Un momento de diversión para los pasajeros apretujados en el metro camino del trabajo. Y es que, ciertamente, mi situación tenía un aspecto cómico. ¿Qué es una catástrofe sin su lado cómico? La señorita Clark, como la conozco desde el principio, es una solterona de baja estatura, rechoncha, y tiene cincuenta y seis años. Al contrario que el doctor Gordon, Claire y mi padre, quien continuamente me asegura que solo me observan quienes anuncian su presencia, el doctor Klinger nunca se ha molestado en llevarme la contraria sobre ese particular. –¿Y qué más da que salga en la primera plana? –¡No es asunto de nadie! –replico, todavía sollozando. –Pero le gustaría hacerlo, ¿no es cierto? –¡Sí! ¡Sí! ¡Pero ella no me ha hecho caso! ¡Ha fingido que le pedía que se diera prisa a terminar! No quiero que vuelva. ¡Quiero una nueva enfermera! –¿Ha pensado en alguien concretamente? –Una mujer joven... ¡y guapa! ¿Por qué no? –Alguien que le escuche y acepte lo que le pide. –¡Sí! ¿Por qué no? ¡De lo contrario es demencial! ¡Debo conseguir lo que quiero! ¡Esta no es una clase de vida ordinaria y no estoy dispuesto a fingir que lo es! Usted pretende que sea normal, espera de mí que sea normal, ¡en estas condiciones! He de ser un hombre juicioso... ¡en estas condiciones! ¡Pero esa es una pretensión absurda por su parte, doctor! ¡Quiero que ella se siente encima de mí y me ponga ahí el coño! ¿Por qué no? ¡Quiero que Claire haga lo que deseo! ¿Qué tiene eso de grotesco? Que se me niegue el placer en esta situación... ¡eso sí que es grotesco! ¡Quiero que me follen! ¿Por qué no habrían de follarme? ¡Dígame qué motivos hay para no hacerlo! ¡En cambio usted me tortura! ¡En cambio me impide que consiga lo que deseo! ¡En cambio estoy aquí tendido y soy juicioso! Y en eso radica la locura, doctor... ¡en ser juicioso! No sé hasta qué punto el doctor Klinger entendía siquiera lo que le estaba diciendo; es bastante difícil seguirme cuando hablo con parsimonia, concentrado, y ahora sollozaba y gritaba sin pensar para nada en las cámaras de televisión ni en los espectadores sentados en la tribuna... ¿O acaso ese era el motivo de que me expresara así? ¿Tan atormentado estaba por la proposición que le había hecho a la señorita Clark aquella mañana? ¿O daba aquel espectáculo sobre todo en beneficio de mi gran público, para convencerle, dejando de lado las apariencias, de que sigo siendo un hombre, pues, quién sino un hombre tiene conciencia, razón, deseo y remordimiento? Esta crisis se prolongó durante meses. Cada vez me mostraba más lascivo con la robusta e implacable señorita Clark, hasta que, finalmente, una mañana le ofrecí dinero. –¡Agáchate... tómalo por detrás! ¡Te daré lo que quieras! Durante mis largos y vacíos días había intentado imaginar cómo le pondría el dinero en las manos y cómo obtendría un préstamo si ella me pedía más de lo que tenía ahorrado en mi cuenta. ¿Quién me ayudaría? No podía solicitar semejante cosa a mi padre o a Claire, y eran las dos únicas personas cuyas visitas aceptaba de buen grado. Ridículo, tal vez, dado lo seguro que estaba de que las cámaras de televisión recogían continuamente mi imagen y que el _Daily News_ publicaba a diario mis progresos, pero téngase en cuenta que no estoy arguyendo que desde mi transformación haya sido un modelo de «conducta responsable de adulto maduro». Tan solo trato de expresar, lo mejor que puedo, las etapas por las que he tenido que pasar camino de la actual fase de equilibrio melancólico... Cierto que en lo que se refiere a la ayuda –para hacerme con el dinero, para llevar a cabo los arreglos financieros, con la señorita Clark o, si fuese necesario, con alguna mujer cuya profesión no se circunscriba a la actitud ética de una enfermera– podría haber recurrido fácilmente a un joven y barbudo colega, un inteligente poeta de Brooklyn que no es gazmoño y cuya audacia sexual le ha valido cierta notoriedad en nuestro departamento de lengua y literatura inglesas. Pero tampoco yo era gazmoño, y de vez en cuando me había apetecido una aventura sexual no menos desarrollada que la de mi joven amigo. Has de comprender que no era un hombre de escasa experiencia y sofocantes inhibiciones quien se veía atormentado por sus deseos en aquella hamaca. No había tenido ninguna dificultad para experimentar con prostitutas cuando era veinteañero, y durante el año que pasé estudiando en Londres, con una beca Fulbright, durante varios meses tuve una emocionante y agitada aventura con dos mujeres jóvenes, estudiantes de mi edad, procedentes de una universidad sueca, que compartían conmigo un dormitorio en un sótano, hasta que la menos estable de las dos intentó, con bastante desgana, arrojarse bajo las ruedas de un camión. Lo que me alarmaba no era la rareza de mis deseos en aquella hamaca, sino el grado en que rompería con mi pasado (y mi especie) si cedía a ellos. Temía que, cuanto más lejos fuese, más lejos estaría dispuesto a ir, hasta que llegase a un extremo de frenesí en el que mi existencia ya no tendría nada que ver con el hombre que había sido. Ni siquiera se trataba de que ya no sería yo mismo: ya no sería nadie. Me habría convertido en carne anhelante y nada más. Así pues, con la ayuda del doctor Klinger, me dispuse a extinguir –y, si no a extinguir, por lo menos, por emplear la palabra predilecta del doctor, a _tolerar_ – el deseo de insertar mi pezón en una vagina. Pero, con toda mi fuerza de voluntad, que, como la de mi madre, puede ser considerable cuando me empeño, me resultaba imposible dominarme cuando empezaba el lavado. Finalmente decidieron rociar con un anestésico suave el pezón y la areola antes de que la señorita Clark se pusiera manos a la obra. Y lo cierto es que esta medida redujo la sensación en grado suficiente para darme ventaja en la batalla contra unos impulsos tan poco prácticos; una batalla que, sin embargo, solo gané cuando los médicos decidieron, con mi consentimiento, someterme a los cuidados de un enfermero. Eso fue lo que surtió efecto. Insertar mi pezón en la boca o el ano del señor Brooks, el enfermero, es algo que no puedo imaginar en el estado de excitación con que lo imaginaría en Claire o incluso en la señorita Clark, aunque soy consciente de que la conjunción de boca masculina y pezón femenino difícilmente podría considerarse un acto homosexual. Pero tal es la fuerza de mi pasado y sus tabúes, y el poder que ejercen sobre mi imaginación las mujeres y sus aberturas, que ahora, temporalmente anestesiado y en manos de un hombre, puedo recibir las abluciones matinales más o menos como cualquier otro inválido. Y aún está ahí Claire, la angélica e imperturbable Claire, para «hacerme el amor», con la boca si no con la vagina. ¿Y no basta con eso? ¿No es tal cosa lo bastante increíble? Claro que sueño con MÁS, sueño con ello durante todo el día, pero ¿de qué me sirve MÁS, de todos modos, cuando mi excitación carece de un final orgásmico y no tengo más que esa sensación sostenida de que estoy a punto de eyacular, un estado en el que me contorsiono desde el primero al último momento? La verdad es que, a estas alturas, he llegado a conformarme con menos en vez de MÁS. Creo que sería mejor evitar que Claire llegara a verse tan solo como la máquina femenina solicitada cada noche para que monte al ridículo organismo que en el pasado fue David Kepesh. Sin duda cuanto menos tiempo pase sobre mi pezón, tanto mayores serán mis posibilidades de seguir siendo para ella (y para mí) algo distinto de ese pezón. En consecuencia, ahora solo durante la mitad de la hora que dura su visita tenemos relación sexual, y el resto del tiempo lo pasamos conversando. A ser posible, incluso me gustaría reducir a la mitad esa media hora. Si la excitación se produce siempre al mismo nivel, sin aumentar ni disminuir de intensidad una vez que ha comenzado, ¿qué diferencia hay en que la experimente durante quince minutos en lugar de treinta? ¿Qué diferencia hay si dura tan solo un minuto? De todos modos, todavía no me siento capaz de semejante renuncia, como tampoco estoy convencido de que sea deseable desde el punto de vista de Claire. Pero créeme si te digo que el mero hecho de tener tal idea después del tormento que he conocido, es admirable. Incluso ahora hay todavía momentos, infrecuentes pero penosos, cuando sus labios me están palpando rítmicamente el pezón, en los que apenas puedo contener el impulso de gritar: «¡Fóllatelo, Ovington! ¡Métetelo en el coño!». Pero no lo hago, no. Si Claire estuviera dispuesta a hacerlo, ella misma ya me lo habría sugerido. Al fin y al cabo, sigue siendo solo una maestra de cuarto curso en la escuela de la calle Bank, una muchacha criada en Schenectady, Nueva York, miembro de la asociación Phi Beta Kappa de Cornell. No tiene sentido que le haga considerar con demasiado detenimiento las cosas grotescas en las que, milagrosamente, ya se ha manifestado dispuesta a participar con seres como yo. En algún momento entre la primera y la segunda de las dos grandes «crisis» a las que he sobrevivido hasta ahora en el hospital (si de un hospital se trata), recibí la visita de Arthur Schonbrunn, decano del departamento de Artes y Ciencias en Stony Brook, a quien conozco desde mi estancia en Palo Alto, cuando él era el joven y célebre profesor de Stanford y yo estudiaba allí para obtener el doctorado en filosofía y letras. Hace ocho años, Arthur, como presidente del recién creado departamento de literatura comparada, me llevó desde Stanford a Stony Brook. Ahora tiene cerca de cincuenta años y es un caballero irónico y encantador, un hombre que, pese a que se dedica a la docencia, tiene una elegancia, tanto de maneras como de indumentaria, que resulta excepcional y casi alarmante. La competencia social de Arthur y el hecho de que nos conocemos desde hace tanto tiempo fue lo que me decidió (así como al doctor Klinger) a elegirlo como la persona idónea para realizar mi presentación en sociedad tras la victoria sobre los anhelos fálicos de mi pezón. También deseaba que Arthur viniera para poder hablarle –si no durante la primera visita, entonces en la siguiente– sobre el modo de enfocar mi continuidad como profesor universitario. En Stanford yo había sido profesor adjunto de una de sus muy concurridas clases de segundo curso, la de «Obras maestras de la literatura universal», y empezaba a preguntarme si cabría la posibilidad de desempeñar nuevamente esa actividad. Claire podría leerme en voz alta los trabajos de los alumnos, y yo le dictaría mis comentarios y las calificaciones... ¿O era una idea del todo imposible? El doctor Klinger necesitó varias semanas para convencerme de que no había nada malo en preguntarlo. No tenía la menor posibilidad. Incluso mientras le estaba diciendo, inevitablemente un poco «lloroso», hasta qué punto me conmovía que fuese el primero de mis colegas que me visitaba, me pareció que le oía reír. –¿Estamos solos, Arthur? –le pregunté. –Sí –respondió él, y percibí con toda claridad su risa. Carecía de visión, pero podía imaginar a mi antiguo mentor: el blazer con forro de un color vivo que le había confeccionado la sastrería Kilgore and French de Londres; los pantalones de franela suaves y los relucientes zapatos de Gucci... ¡el diplomático decano, con su hermosa mata de pelo negro entreverado de blanco, riéndose de mí! Y ni siquiera le había planteado mi deseo de ser profesor adjunto del departamento. Riéndose no debido a alguna ridiculez que le hubiera propuesto, sino porque constataba que era cierto, que realmente me había convertido en un pecho. Mi asesor del curso de posgrado, mi superior universitario, el profesor más distinguido que hubiera conocido jamás, y, sin embargo, a juzgar por los sonidos que emitía, no podía reprimir la risa tan solo con verme. –Lo... lo siento, David... Pero ahora se reía tanto que ni siquiera podía hablar. Arthur Schonbrunn incapaz de hablar. Nada podría ser más increíble. Veinte, treinta segundos más de carcajadas, y entonces se marchó. La visita había durado unos tres minutos. Al cabo de dos días llegaron las disculpas, expresadas con tanta elegancia como todo lo que Arthur había escrito desde su librito sobre Robert Musil. Y a la semana siguiente llegó un paquete enviado por Sam Goody's, con una tarjeta firmada por «Debbie y Arthur S.». Un álbum de discos de _Hamlet_ interpretado por Laurence Olivier. Arthur había escrito: «No debería haber aumentado tu desgracia con mi pusilánime e imperdonable actuación. No sé cómo explicar lo que me ocurrió. Si lo intentara, a los dos nos parecería pura hipocresía». Trabajé en mi respuesta durante una semana. Debí de dictar unas cincuenta cartas: corteses, elocuentes, comprensivas, desenfadadas, maliciosas, disparatadas, serias, avergonzadas, literarias y algunas incluso más bobas que la que le envié. «¿Pusilánime? –le escribí a Arthur–. Hombre, en todo caso, que te hayas desternillado de risa es una prueba de tu campechana vitalidad. El pusilánime soy yo, y de no ser así me habría reído contigo. Si no llego a apreciar la enorme comedia de todo esto, se debe tan solo a que en realidad tengo más de Arthur Schonbrunn que tú mismo, ¡gilipollas vano, ególatra y alechuguinado!» Pero la que elegí finalmente tan solo decía: «Queridos Debbie y Arthur S.: Muchas _grasias_ por los discos. Dave "el Pecho" K.». Me aseguré de que Claire había escrito «gracias» con ese antes de que enviara por correo mi pequeño mensaje. Si lo enviaba. Si se molestaba en anotarlo. La segunda crisis que amenazó con destruirme y que, por el momento, parezco haber sorteado podría considerarse una crisis de fe. Como sucedió pasado un mes desde la visita de Arthur, no resulta fácil saber si la precipitó aquella humillación. Hace mucho que he dejado de aborrecer a Arthur Schonbrunn por lo que hizo aquel día (por lo menos sigo empeñándome en no aborrecerlo) y por ello ahora tiendo a estar de acuerdo con el doctor Klinger, quien cree que aquello con lo que hube de habérmelas a continuación era inevitable y no se puede achacar la culpa a los tres minutos que el decano pasó conmigo. Es evidente que no puedo culpar a nadie de nada de lo que ha sucedido, ni siquiera a mí mismo. Lo que sucedió a continuación fue que me negué a creer que me había convertido en un pecho. Tras haber conseguido renunciar (más o menos) a mis sueños de acoplamiento por medio del pezón con Claire, con la señorita Clark, con cualquier mujer que estuviese dispuesta, me di cuenta de que aquello era imposible. Un hombre solo puede convertirse en pecho en su propia imaginación. Había tardado seis meses en comprenderlo. –Mire, esto no puede ocurrir... ¡de ninguna manera! –¿Por qué no? –replicó el doctor Klinger. –¡Usted sabe por qué! ¡Cualquier niño sabe por qué! ¡Porque es una imposibilidad fisiológica, biológica y anatómica! –¿Cómo explica entonces el aprieto en que se encuentra? –¡Es un sueño! No han pasado seis meses... eso también es una ilusión. ¡Estoy soñando! ¡Solo se trata de despertar! –Pero está usted despierto, señor Kepesh. Sabe muy bien que lo está. –¡Deje de decir eso! ¡No me torture así! ¡Deje que me levante! ¡Basta! ¡Quiero levantarme! Durante días y más días, o lo que pasa por días en una pesadilla, luché por despertarme. Claire venía todas las tardes para chuparme el pezón y hablar, mi padre venía el domingo para contarme las últimas noticias, el señor Brooks se presentaba todas las mañanas y me hacía salir del sueño con unos suaves golpecitos en el borde de la areola. Por lo menos imaginaba que me había despertado al tocarme el borde de la areola. Entonces comprendía que no me había despertado de un sueño real, sino del sueño que soñaba dentro de la pesadilla. No era un pecho que se despertara, sino yo mismo, y seguía soñando. ¡Ah, cómo maldecía a mis captores!, aunque, desde luego, si se trataba de un sueño solo maldecía a unos captores de mi propia invención. «¡Dejad de torturarme, todos vosotros! ¡Que alguien me ayude a levantarme!» Maldecía a los espectadores del anfiteatro que había construido, maldecía a los técnicos del circuito de televisión que había imaginado («¡Mirones! –gritaba–, ¡crueles y sádicos mirones que me coméis con los ojos!»), hasta que finalmente, temerosos de que mi deteriorado organismo cediera bajo la tensión emocional (sí, tales eran las palabras de preocupación que ponía en sus bocas mentirosas), decidieron someterme a una profunda sedación. ¡Cómo aullé entonces! «¡Jodida e insensible Claire! ¡Padre idiota e ignorante! ¡Eres un matasanos, Klinger, eres un fraude!», gritaba incluso mientras la droga me iba debilitando, una droga sedante que de alguna manera yo mismo había administrado al soñador. Cuando volví en mí, por fin me di cuenta de que había enloquecido. No estaba soñando. Estaba loco. No habría ningún despertar mágico, no abandonaría la cama, me cepillaría los dientes e iría a dar clases como si nada más que una pesadilla hubiera interrumpido mi vida corriente y predecible; en caso de que pudiera esperar algo, sería el largo camino de retorno a la cordura. Y, por supuesto, el primer paso hacia la recuperación de la cordura era comprender que la sensación de que me había convertido en un pecho era el delirio de un lunático. En vez de estar colgado en una hamaca tras una catástrofe endocrinopática como ningún endocrinólogo había conocido hasta entonces, era más que probable que me encontrara sentado, delirante, en una habitación de un manicomio. Y no hay duda de que eso es algo que puede suceder y les sucede a muchas personas, continuamente. Que no pudiera ver ni saborear ni oler, que solo pudiera oír débilmente, que no pudiera establecer contacto con mi propia anatomía, que al hablar con otros tuviera la sensación de estar enterrado y casi estrangulado por mi propio tejido adiposo... ¿eran estos síntomas tan insólitos en el estado de estupor de la psicosis? Sin embargo, me resultaba difícil comprender por qué motivo había perdido la cordura. ¿Qué podía haber desencadenado un desplome esquizofrénico tan absoluto en un hombre que aparentemente se encontraba tan bien? Pero, por otro lado, lo que podría haber causado semejante crisis era sin duda tan aterrador que me habría visto obligado a borrar por completo su recuerdo... Pero entonces, ¿por qué el doctor Klinger (y estaba seguro de que la persona con la que hablaba era el doctor Klinger; tenía que estar seguro de algo para empezar, así que me aferraba a su inglés con un suave acento, su franqueza y su humor vulgar como prueba de que eso por lo menos era real en mi experiencia), por qué, pues, el doctor Klinger me pedía que aceptara mi destino, cuando era evidente que el camino de retorno a la cordura suponía plantar cara a aquella concepción de mí mismo absolutamente demencial? La respuesta era obvia, debería haberlo sido desde el principio. Eso no era lo que Klinger estaba diciendo. Debido a mi enfermedad, tomaba sus palabras y, a pesar de lo sencillas y claras que eran, les daba exactamente el sentido contrario al que tenían. Aquella tarde, cuando llegó Klinger, tuve que hacer acopio de toda mi famosa fuerza de carácter a fin de explicarle, tan sencilla y claramente como yo podía hacerlo, el increíble descubrimiento que había hecho. Al terminar sollozaba, pero por lo demás había estado tan inspirado como siempre al hablar. Cuando uno da clase, a veces se oye a sí mismo hablar con unas cadencias perfectas, desarrollando ideas con frases precisas y combinándolas en párrafos llenos a rebosar, y entonces resulta difícil creer que el individuo que se dirige a sus silenciosos alumnos con su pico de oro y su gran decisión pueda haberse hecho tal lío con sus notas solo una hora antes. Pues bien, todavía es más difícil de creer que el tono comedido en el que le había dado la noticia al doctor Klinger procedía del loco injurioso al que sus guardianes habían sedado. Si aún era un lunático –y puesto que continuaba siendo un pecho, seguía siendo un lunático–, ahora por lo menos era uno de los más lúcidos y elocuentes de la planta del hospital donde me hallaba. –Curiosamente, la visita de Arthur Schonbrunn es lo que me convence de que estoy en el camino correcto –le dije–. ¿Cómo podría haber creído jamás que Arthur vendría aquí y se echaría a reír? ¿Cómo podría confundir con la verdad un engaño tan ostensiblemente paranoico? Hace un mes que le maldigo, y a Debbie también, por enviarme esos discos idiotas, y nada de esto tiene el menor sentido. Porque si hay una persona en el mundo que nunca pierde el dominio de sí mismo, es Arthur. –¿Acaso ese decano está por encima de los riesgos de la naturaleza humana? –¿Sabe una cosa? La respuesta a esa pregunta es afirmativa. Está por encima de los riesgos de la naturaleza humana. –Un astuto vivales, ¿eh? –No es que sea tan astuto, esa es una manera errónea de considerarlo. Lo que ocurre es que me he vuelto muy loco. ¡Pensar que me he inventado todo esto...! –¿Y su nota, a la que usted respondió con tanta amabilidad? ¿La nota que le puso tan furioso? –Más paranoia. –¿Y la grabación de _Hamlet_? –Ah, eso sí que es real. Es real y muy propio de Debbie. Oh, sí, ahora veo la diferencia, incluso mientras hablo percibo la diferencia entre lo demencial y lo que ha sucedido realmente. Percibo la diferencia, debe usted creerme. ¡Me he vuelto loco, pero ahora lo sé! –¿Y qué cree que le ha hecho, como dice usted, «volverse loco»? –inquirió el doctor Klinger. –No lo recuerdo. –¿No tiene ninguna idea? ¿Qué podría haber motivado que una persona como usted sufra un delirio tan completo e impenetrable? –Le estoy diciendo la verdad, doctor. No tengo la menor idea. Todavía no, por lo menos. –¿No se le ocurre nada? ¿Nada en absoluto? –Verá, lo que se me ocurre... lo que se me ha pasado por la cabeza esta mañana... –¿Qué es? –Me estoy aferrando a un clavo ardiendo, y sé lo caprichoso que eso parece en estas circunstancias, pero he pensado que esto procede de la literatura. Los libros sobre los que he dado clases... ellos me han metido la idea en la cabeza. Pienso en mi curso de literatura europea. Ocuparme de Gogol y Kafka un año tras otro, explicar _La nariz_ y _La metamorfosis_. –Sin embargo, muchos otros profesores de literatura centran también sus clases en esas obras. –Pero tal vez sin tanta convicción –repliqué, con un rasgo de humor intencionado. Él se echó a reír. –La cuestión es que estoy loco, ¿verdad? –No. Solo me sentí contrariado un momento. Me di cuenta de que había invertido el sentido de su negativa tan fácil e inconscientemente como enderezamos las imágenes que se proyectan al revés en la retina. –Debo decirle –le expliqué con calma– que aunque usted ha dicho que sí cuando le he preguntado si estaba loco, le he oído decir que no. –Le he dicho que no. Usted no está loco. No sufre ningún delirio, ni desde luego lo ha sufrido hasta ahora. Es un pecho, si se le puede llamar así. Sus esfuerzos por adaptarse a una misteriosa desgracia han sido heroicos. Uno comprende la tentación, desde luego: todo esto no es más que un sueño, una alucinación, un delirio, incluso un estado mental inducido por drogas. Pero lo cierto es que no se trata de nada de eso. Es algo que le ha ocurrido a usted. Y la mejor manera de enloquecer, ¿me escucha, señor Kepesh?, es fingir otra cosa. El consuelo que eso puede procurarle durará poco, se lo aseguro. Quiero que deje de engañarse y abandone ahora mismo la idea de que está loco. No lo está, y fingir otra cosa solo le causará pesar. La locura no es ninguna solución, tanto si es una locura imaginaria como real. –Una vez más lo oigo todo invertido. He dado por completo la vuelta al sentido de sus palabras. –No, no lo ha hecho. –¿Tiene algún sentido para usted que considere mi delirio como algo alimentado por los años dedicados a enseñar esos relatos? Es decir, al margen del trauma que desencadenó la crisis. –Pero no hubo ningún trauma, ninguno de naturaleza psicológica; y, como le he dicho, le repito y seguiré diciéndoselo: esto no es un delirio. ¿Cómo insistir? ¿Cómo abrirme paso a través de aquella inversión de la realidad? Con una astucia que me satisfizo, y que me pareció una prueba de buena salud mental, repliqué: –Pero si lo fuese, doctor Klinger, puesto que una vez más he entendido que decía lo contrario de lo que ha dicho, si fuese un delirio, ¿vería usted entonces alguna relación entre la clase de alucinación que sufro y el poder que ejercen sobre mi imaginación Kafka o Gogol? ¿O Swift? Pienso en _Los viajes de Gulliver_ , otro libro sobre el que he impartido clases durante años. Tal vez si siguiéramos hablando hipotéticamente... –Basta, señor Kepesh. No engaña usted a nadie más que a sí mismo, si es que en verdad se engaña. Ha sufrido una conmoción, pánico, furor, desesperación, desorientación, profundos sentimientos de impotencia y aislamiento, la depresión y el miedo más oscuros, pero a través de todo ello, de una manera milagrosa, absolutamente maravillosa, no hay ni rastro de delirio. Ni siquiera cuando su viejo amigo, el decano, se presentó aquí y le dio el ataque de risa. Es natural que eso le conmocionara, es natural que le dejara abatido. ¿Por qué no habría de ser así? Pero no ha imaginado la desafortunada conducta de Arthur Schonbrunn. No se ha inventado lo que le ha sucedido a usted, ni tampoco lo que le sucedió a él cuando estuvo aquí. No ha tenido necesidad de inventárselo. Finge usted que es un ingenuo, ¿sabe?, cuando me dice que un hombre con la posición de Arthur Schonbrunn no puede reaccionar en absoluto como él lo ha hecho. Es demasiado buen estudioso de la naturaleza humana para creer tal cosa. Ha leído demasiado a Dostoievski para eso. –¿Servirá de algo que le repita lo que he creído haberle oído decir? –No es necesario. Lo que cree haber oído, lo ha oído. Esto se conoce como cordura. Déjese de monsergas lunáticas, señor Kepesh, y cuando antes lo haga, tanto mejor. Gogol, Kafka y compañía... va a tener serios problemas si sigue por ese camino. Antes de que se dé cuenta habrá causado unos delirios auténticos e irreversibles, exactamente como esos de los que ahora afirma que desea librarse. ¿Me sigue? Creo que sí. Es usted un hombre muy inteligente, tiene una notable fuerza de voluntad y quiero que termine con eso ahora mismo. ¡Qué agotador era oírlo todo al revés! ¡Qué ingeniosa es la locura! Pero por lo menos ahora sabía la verdad. –¡Doctor Klinger! ¡Escúcheme, doctor Klinger! ¡No permitiré que esto siga volviéndome loco! ¡Lucharé por liberarme! ¡Dejaré de oír lo contrario! ¡Empezaré a oír lo que todos ustedes me están diciendo! ¿Me escucha, doctor? ¿Comprende mis palabras? ¡No seguiré participando en este engaño! ¡Me niego a formar parte de él! ¡Entenderé lo que quiere usted decir! ¡Pero no se dé por vencido! Por favor –le supliqué–, ¡no me considere un caso perdido! ¡Superaré todo y seré de nuevo yo mismo! ¡Estoy decidido a hacerlo! ¡Con todas mis fuerzas, con toda mi voluntad de vivir! Ahora me pasaba los días tratando de desentrañar las palabras que oía decir a los médicos, a Claire y al señor Brooks. El esfuerzo que esto requería era tan absoluto y tan agotador, que cuando llegaba la noche tenía la sensación de que bastaría el soplido de unos labios infantiles para extinguir definitivamente la oscilante llamita de memoria, inteligencia y esperanza que seguía empeñada en afirmar mi identidad. El domingo, cuando me visitó mi padre, se lo conté todo, aunque estaba seguro de que Claire y Klinger se lo habrían comunicado por teléfono el día que sucedió. Balbucí como un niño que ha ganado un trofeo. Le dije la verdad: ya no creía que era un pecho. Si bien aún no había podido despojarme de la sensación física de irrealidad, a diario me libraba de la ridícula ilusión psíquica; cada día, a cada hora, notaba que volvía lentamente a ser yo mismo, y que incluso podía entrever el momento en que volvería a dar clases sobre Gogol y Kafka en vez de experimentar indirectamente las transformaciones antinaturales que imaginaron en sus famosas obras. Como mi padre no sabe nada de libros, le conté cómo, en el relato de Kafka, Gregorio Samsa se despierta y descubre que se ha convertido en un enorme escarabajo; le resumí _La nariz_ , diciéndole que una mañana el personaje de Gogol se despierta sin nariz, sale a buscarla por San Petersburgo, pone un anuncio en el periódico solicitando que se la devuelvan, la ve «caminando» por la calle, un ridículo encuentro tras otro, hasta que al final la nariz aparece de nuevo en su cara, sin que el retorno tenga motivo alguno, como tampoco lo había tenido la desaparición. (Imaginé a mi padre pensando: «¿Enseña estas cosas en la universidad?».) Le expliqué que seguía sin poder recordar el golpe causante del estado en que me hallaba, que me había vuelto sordo, no oía nada cuando el médico intentaba que me enfrentara a la situación. Pero al margen de cuál hubiera sido el trauma, por terrible, horroroso y repelente que fuese, yo sabía que mi ruta de huida era la fantasía de la transformación física que tenía a mano, los relatos catastróficos de Kafka y Gogol y sobre los que solo una semana antes había dado clase a mis alumnos. Ahora, con la ayuda del doctor Klinger, trataba de averiguar por qué, entre todas las posibilidades, había elegido un pecho femenino. ¿Por qué razón una voluminosa y estúpida bolsa de tejido mudo y deseable, objeto de acciones en vez de actor, desprotegido, pendiente, ahí, como un pecho se limita a pender y estar ahí? ¿Por qué aquella primitiva identificación con el objeto infantil de veneración? ¿Qué apetitos no satisfechos, qué confusiones de la cuna, qué fragmentos de mi remoto pasado podrían haber chocado para provocar un delirio de semejante simplicidad clásica? Seguí parloteando de este modo ante mi padre, y entonces, una vez más, jubilosamente, sollocé. No vertí lágrimas, me limité a sollozar. ¿Dónde estaban mis lágrimas? ¿Cuánto tiempo pasaría antes de que volviera a notarlas? ¿Cuándo volvería a notar los dientes, la lengua, los dedos de los pies? Durante largo rato mi padre no dijo nada. Pensé que tal vez también estaba llorando. Entonces me dio las noticias semanales: la hija de Fulano está embarazada, el hijo de Mengano se ha comprado una casa de ciento cincuenta mil dólares, mi tío suministra la comida y la bebida para el banquete de bodas del hijo del hermano menor de Richard Tucker. Ni siquiera me había oído. Naturalmente. Tal vez yo había superado la creencia de que era un pecho, pero al parecer aún era casi necesario que recitara, como desde un escenario, si quería que me entendieran. Lo que me parecía un tono de conversación normal daba la impresión de que sonaba como el susurro de alguien que estuviera en el otro extremo de la estancia. Pero esto no se debía a que mi voz estuviera sepultada en una glándula mamaria de setenta kilos. ¡Mi cuerpo seguía siendo un cuerpo! ¡Tan solo tenía que poner fin al susurro! ¿Podría ser eso parte de mi locura? ¿El hecho de que cuando creía que estaba hablando en voz alta, en realidad solo hablaba conmigo mismo? ¡Pues habla más alto! Y eso fue lo que hice. Con toda la fuerza de mis pulmones (¡mis dos buenos pulmones!) le repetí a mi padre el relato del descubrimiento que había hecho. Y entonces llegó el momento de dar el paso siguiente. Un pie delante del otro. –¿Dónde estamos, papá? Dímelo. –En tu habitación –respondió él. –Y dime, ¿me he convertido en un pecho de mujer? –Bueno, eso es lo que dicen. –Pero no es cierto. Soy un enfermo mental. A ver, vuelve a decírmelo. ¿Qué soy? –Por favor, Davey. –¿Qué soy? –Eres un pecho de mujer. –¡Eso no es cierto! ¡Lo que te he oído decir no es cierto! ¡Soy un enfermo mental! ¡Estoy en un manicomio! Y tú has venido a visitarme. Si esa es la verdad, papá, quiero que digas que sí. Escúchame, tienes que ayudarme. Soy un enfermo mental. Estoy en un manicomio. He sufrido un grave colapso mental. Sí o no. Dime la verdad. –Sí, hijo, sí, eres un enfermo mental –respondió mi padre. Más tarde, cuando llegó Klinger, le grité: –¡He oído a mi padre! ¡He oído la verdad! ¡Le he oído decir que soy un enfermo mental! –No debería haberle dicho tal cosa. –¡Lo he oído! ¡Tampoco lo estoy imaginando! ¡No lo he entendido al revés! –Claro que lo ha oído. Su padre le quiere. Es un hombre sencillo y le quiere mucho. Ha pensado que decirle eso le sería de ayuda. Ahora sabe que no es así. Y usted también lo sabe. Pero yo no podría haberme sentido más feliz. Mi padre me había entendido. ¡Era posible entenderme! Muy pronto los demás también lo harían. –¡Lo he oído! –grité–. ¡No soy un pecho! ¡Estoy loco! ¡Cómo me esfuerzo en los días siguientes por recuperar la cordura! Remuevo el lodo de mis inicios, en busca de lo que explique, y por lo tanto aniquile, este ridículo delirio. Le digo al médico que he regresado al amanecer de mi vida, a mis primeras mil horas tras las infinitas horas de inexistencia, he regresado al momento en que todo es uno mismo y uno mismo es todo, al momento en que lo cóncavo es lo convexo y lo convexo lo cóncavo... ¡ah, cómo hablo! ¡Cómo me afano por burlar a mi locura! ¡Ojalá pudiera recordar mis hambrientas encías en la amorosa espita, mi nariz en el globo nutricio! –Si ella viviese, si pudiera decirme... –¿Sí? –inquiere el doctor Klinger–. ¿Decirle qué? –¿Cómo voy a saberlo? –replico en tono quejumbroso. Pero ¿por dónde empezar si no es por ahí? Solo que resulta que ahí no hay nada. Todo es demasiado remoto, el regreso al lugar donde estoy ahora. Bucear hasta ese fondo marino donde empecé a ser, ¡descubrir en el limo mi precioso secreto! Pero cuando asciendo a la superficie, ni siquiera tengo cieno bajo las uñas. He ascendido sin nada. Le digo al médico que tal vez, solamente tal vez, se trate de un desmoronamiento postanalítico que se ha estado incubando durante un año, el medio más desesperado que se me podía ocurrir para aferrarme a Klinger. –¿Ha pensado alguna vez en las fantasías de dependencia que florecen en las mentes de sus pacientes debido a su apellido?* ¿Ha caído en la cuenta, doctor, de que todos nuestros apellidos empiezan por K., el suyo, el mío y el de Kafka? Y sin olvidar a Claire... ¡y a la señorita Clark? –El alfabeto –me recuerda a mí, un profesor de lengua– solo tiene veintiséis letras. Y somos cuatro mil millones necesitados de iniciales con fines de identificación. –¡Pero...! –Pero ¿qué? –¡Algo, lo que sea! ¡Una pista, por favor! Si yo no puedo... entonces usted. Por favor, alguna pista, una orientación... ¡Tengo que salir de aquí! Repaso de nuevo con él los momentos destacados de mi desarrollo psicológico, una vez más paso las páginas de la antología de relatos que los dos recopilamos como texto para el curso que impartimos, tres veces por semana, durante cinco años, _La historia de David Alan Kepesh_. Pero lo cierto es que esos relatos han sido contados y glosados de manera exhaustiva tantas veces que me resultan tan rancios como el viejo cuento preferido del maestro de escuela más retrógrado de Estados Unidos. El drama de mi vida, tan emocionante en los primeros años de terapia como _Los hermanos Karamazov_ , tiene ahora el atractivo de un libro de lectura de décimo curso que empezara con _El collar_ y siguiera hasta _La suerte del Campamento Rugiente_. Y esto explica el éxito con que terminaron las sesiones de análisis el año anterior. ¡Ahí radica mi trauma!, me dije. ¡El mismo éxito! Allí estaba lo que no podía aceptar: ¡una vida feliz! –¿De qué se trata? –me pregunta burlonamente el doctor Klinger–. ¿Qué es lo que no puede aceptar? –¡Recompensas en vez de castigos! ¡Consuelo! ¡Placer! Un estilo de vida gratificante, una vida sin... –Espere un momento, por favor. ¿Por qué no podría aceptarlo? Son cosas estupendas. Vamos, señor Kepesh, no diga tonterías. Recuerdo que aceptaba la felicidad junto con todas esas cosas buenas. Pero me niego a escucharle, puesto que de todos modos lo que le oigo decir no es lo que está diciendo. Eso se debe a mi enfermedad, que vuelve las cosas del revés para que siga loco. Sin embargo, sigo adelante, y a continuación hablo de aquello a lo que los pacientes se refieren más tarde o más temprano, de ese amigo imaginario al que llaman «mi culpa». Hablo de Helen, mi ex mujer, cuya vida, según me han dicho, no es mejor ahora de lo que lo era cuando padecimos juntos los cinco años de nuestro matrimonio. Recuerdo mi inevitable deleite cuando un viejo amigo de San Francisco, que había venido a cenar conmigo y mi encantadora e imperturbable Claire, me informó de la continua desdicha de Helen. Me dije que aquella zorra se lo tenía bien merecido... –¿Y ahora –me pregunta Klinger en un tono de regocijo– cree que se está castigando a sí mismo de esta manera por un rencor tan vulgar y corriente? –¡Le estoy diciendo que mi nueva vida llena de felicidad era excesiva para mí! –alego–. Eso explica que perdiera el deseo por Claire: ¡aquello era demasiado bueno para que durase! Tanta satisfacción parecía... ¡parecía injusta! ¡Comparada con el destino de Helen parecía de algún modo inicua! ¡Me abrumaba el sentimiento de culpa! –Esto es análisis de pacotilla, mi querido señor –replica él–, y usted lo sabe tan bien como yo. –Pues si esa no es la causa, ¿cuál es? ¡Ayúdeme! ¡Dígamelo! ¿Qué lo ha provocado? –Nadie lo ha «provocado». –Entonces, por el amor de Dios, ¿por qué estoy loco? –Pero no está loco, y eso también lo sabe. El domingo siguiente, cuando mi padre viene a visitarme, vuelvo a preguntarle si soy un enfermo mental, solo para asegurarme. –No –me responde esta vez. –¡Pero la semana pasada me dijiste que sí! –Estaba equivocado. –¡Pero es la verdad! –No lo es. –¡Otra vez invierto el sentido de lo que me dicen! Contigo no me pasaba y ahora ya ves. ¡Vuelvo a estar donde estaba! ¡Entiendo al revés lo que me dice todo el mundo! –En absoluto –replicó el señor Klinger. –¿Qué está haciendo aquí? Hoy es domingo. ¡Mi padre está aquí, no usted! ¡No quiero seguir estando loco! ¡Ayúdeme! ¿Me oye? ¡Ayúdeme, por favor! ¡Necesito su ayuda! ¡No puedo hacer esto solo! ¡Ayúdeme! ¡Sáqueme de aquí! ¡Dígame tan solo la verdad! Si soy un pecho, ¿dónde está la leche? Cuando Claire me chupa, ¿dónde está la leche? ¡Dígamelo! –¡Oh, David! –Era mi padre, ¡su cara sin afeitar en mi areola!–. Hijo mío, mi pobre hijito. –¿Qué ha pasado, papá? Abrázame, papá, por favor. ¿Qué ha pasado realmente? Dímelo, por favor, ¿por qué me he vuelto loco? –No te has vuelto loco, cariño –replicó él entre sollozos. –Entonces, ¿dónde está mi leche? ¡Contéstame! ¡Si soy un pecho debería producir leche! ¡Retener leche! ¡Estar hinchado de leche! ¡Y eso es demasiado absurdo para que cualquiera se lo crea! ¡Incluso yo! ¡ESO ES SENCILLAMENTE IMPOSIBLE! Pero no hay duda de que es posible. De la misma manera que son capaces de incrementar la producción láctea de las vacas con inyecciones del agente lactogénico GH, la hormona del crecimiento, también han formulado la hipótesis de que es muy probable que yo pueda llegar a ser una glándula mamaria mediante una estimulación hormonal apropiada. De ser así, no faltarán científicos que quieran aprovechar la oportunidad de averiguarlo. Y tal vez, cuando no pueda seguir soportando todo eso, les dé esa oportunidad. ¿Y si la experimentación no acaba con mi vida? ¿Si tienen éxito y la leche empieza a brotar? Bueno, entonces sabré que soy un auténtico pecho, o bien que estoy tan loco como el más loco que haya existido jamás. Entretanto han pasado quince meses, según me dicen, y de momento vivo con un relativo equilibrio. Es decir, las cosas han sido peores y volverán a serlo, pero por ahora Claire viene a visitarme todos los días, sin faltar uno solo, y durante la primera media hora, sin quejarse y sin repugnancia, se ocupa de proporcionarme placer. Convierte una perversión asquerosa en un amable acto de amor. Y entonces hablamos. Me está ayudando en mis estudios sobre Shakespeare. Últimamente he escuchado los discos de las tragedias. Empecé con el regalo de los Schonbrunn, Olivier en _Hamlet_. El álbum estuvo meses aquí, en la habitación, antes de que una mañana le pidiera al señor Brooks que rompiera el envoltorio de celofán y pusiera un disco en el fonógrafo. (Resulta que el señor Brooks es negro, así que, en el ojo de mi mente –en el ojo de la mente del pecho–, lo imagino como ese guapo senador negro de Massachusetts. ¿Por qué no, si me hace más llevadera esta situación?) Como tantas otras personas, desde que finalicé los estudios universitarios siempre he deseado tomarme tiempo algún día para releer a Shakespeare. Supongo que en una u otra ocasión así se lo dije a Debbie Schonbrunn, y ella compró el álbum al darse cuenta de que ahora yo disponía de tiempo. Sin duda no tuvo la menor intención satírica, por mucho que yo creyera otra cosa cuando llegó el _Hamlet_ una semana después de la fugaz visita de Arthur. Debo recordar que, aparte de las dificultades más obvias ocasionadas por mi transformación, ya no soy persona a la que resulta más fácil en el mundo hacerle un regalo. Todas las mañanas, durante varias horas, y de nuevo en ocasiones por las tardes, cuando no hay nada mejor que hacer, escucho mis discos de Shakespeare: Olivier interpreta a Hamlet y Otelo, Paul Scofield en el papel de Lear, _Macbeth_ representada por la compañía del Old Vic. Incapaz de seguir con el texto mientras los actores declaman sus papeles, siempre me pierdo el significado de una palabra con la que no estoy familiarizado o me desoriento en la sintaxis enrevesada. Entonces mi mente empieza a divagar, y cuando sintonizo de nuevo, escucho líneas y más líneas que apenas tienen sentido. A pesar del esfuerzo –¡oh, el esfuerzo, este esfuerzo un minuto tras otro!– por mantener la atención fijada en las dificultades por las que atraviesan los sufrientes personajes de Shakespeare, sigo considerando mi propio sufrimiento por encima de lo tolerable. La edición de Shakespeare que utilizaba en la universidad – _Obras teatrales completas y poemas de Willian Shakespeare_ , de Neilson y Hill, encuadernada en tela azul, con el lomo desgastado por mi manoseo estudiantil, y con el texto muy subrayado en aquella época en que aspiraba a la sabiduría– está sobre la mesa al lado de la hamaca. Es uno de los varios libros que le he pedido a Claire que traiga del piso. Recuerdo con exactitud el aspecto que tiene, el motivo por el que deseaba tenerlo aquí. Por las tardes, durante la segunda media hora de su visita, Claire busca para mí en las notas al pie las palabras cuyo significado aprendí mucho tiempo atrás y luego olvidé; o bien ella me lee lentamente algún pasaje que se me pasó por alto aquella mañana en que mi mente se alejó del castillo de Elsinor y fue al hospital Lenox Hill. Me parece importante grabar con claridad esos pasajes en mi cerebro antes de dormirme. De lo contrario podría parecer que escucho _Hamlet_ por la misma razón por la que mi padre atiende al teléfono en el servicio de catering de tío Larry, para matar el tiempo. Olivier es un gran hombre, ¿sabes? Me he enamorado un poco de él, como una colegiala de un astro de la pantalla. Jamás hasta ahora me había entregado de una manera tan completa a un genio, ni siquiera al leer. Cuando era estudiante y luego profesor, experimentaba la literatura como algo inevitablemente contaminado por mi timidez o por las responsabilidades del discurso serio; o bien aprendía o bien enseñaba. Pero ahora las responsabilidades han quedado atrás; por fin puedo limitarme a escuchar. Al principio, cuando me quedaba solo por la noche, trataba de divertirme imitando a Olivier. Durante el día escuchaba los discos para memorizar los famosos soliloquios, y de noche actuaba, tratando de aproximarme a su manera tan personal de declamar. Tras unas semanas de práctica, me pareció que realmente había dominado su Otelo, y una noche, después de que Claire se hubiera marchado, declamé el texto de la escena de la muerte con una pasión tan quejumbrosa que podría haber hecho llorar al público, si lo hubiera habido. Entonces me di cuenta de que había un público. Era alrededor de medianoche, pero nadie me ha dado todavía un buen motivo por el que la cámara de televisión debiera estar desconectada a alguna hora del día o de la noche, de modo que seguí con mi actuación. Nada más fácil que exagerar el patetismo. «Vamos, David –me dije–, todo esto es demasiado conmovedor y descorazonador, un pecho recitando "Y agregad que una vez en Alepo...". Harás que el personal del turno de noche vuelva a casa lloroso.» Sí, amargura, querido lector, y de la clase más superficial, pero permite que mi pobre dignidad de profesor tenga un respiro, ¿quieres? Esto no tiene más de tragedia que de farsa. No es más que vida, y yo solo soy humano. –¿Me ha causado esto la literatura? –¿Cómo podría ocurrir tal cosa? –replica el doctor Klinger–. No, las hormonas son hormonas y el arte es arte. No sufre usted una sobredosis de las grandes imaginaciones. –¿De veras? Pues me extraña. Esta bien podría constituir mi manera de ser un Kafka, un Gogol, un Swift. Ellos podían imaginar lo increíble, dominaban el lenguaje y tenían aquel implacable talento creador. Pero yo no contaba con ninguna de esas cosas... añoranzas literarias, eso era todo. En literatura, me encantaba lo extremo, idolatraba a los autores que lo cultivaban, su imaginación y su poderío casi me hipnotizaban... –¿Y qué? –¿Cómo? –El mundo está lleno de amantes del arte. ¿Qué tiene de especial...? –Entonces di el salto. Convertí la carne en palabra. ¿No lo ve? He sido más kafkiano que Kafka. –Klinger se echó a reír, como si solo lo hubiera dicho en broma–. Al fin y al cabo, ¿quién es el artista más grande, el que imagina la maravillosa transformación o el que se transforma maravillosamente a sí mismo? ¿Por qué David Kepesh, entre todos los seres humanos, se ve dotado de tales poderes? Es sencillo. ¿Por qué Kafka? ¿Por qué Gogol? ¿Por qué Swift? ¿Por qué cualquiera? El gran arte, como todo lo demás, es algo que le sucede a la gente. ¡Y esta es mi gran obra de arte! –Pero me apresuré a añadir–: He de mantener mi perspectiva cuerda y razonable. No quiero volver a inquietarle. Nada de delirios, y sobre todo delirios de grandeza. Pero si no grandeza, ¿qué te parece humillación? ¿Qué te parece depravación y vicio? Podría ser rico, ¿sabes?, podría ser rico, célebre y delirar de placer el día entero. Cada vez pienso más en ello. Podría pedirle a mi amigo que me visitara, el joven y audaz colega del que antes te he hablado. Si todavía no me he atrevido a invitarle, no es porque me asuste que se ría de mí y huya como lo hizo Arthur Schonbrunn, sino porque echará un vistazo a lo que soy (y lo que podría ser) y estará demasiado deseoso de ayudar; porque cuando le diga que me he hartado de afrontar esta situación como un individuo heroicamente civilizado, me he hartado de escuchar a Olivier, de hablar con mi analista y gozar a diario durante media hora con la idea del sexo ardiente que tiene un maestro de escuela virtuoso, él no discutirá como lo harían los otros. –Quiero salir de aquí –le diré–, y necesito un cómplice. Podemos llevarnos todas las bombas y tubos que me mantienen vivo. Y para cuidar de mi salud, por así decirlo, podemos contratar a médicos y enfermeras. El dinero no será ningún problema. Pero estoy harto y cansado de preocuparme por la posibilidad de perder a Claire. Que se busque otro amante cuyo semen no engullirá y lleve con él una vida normal y productiva. Estoy cansado de protegerme contra la pérdida de la bondad angélica. Y, entre tú y yo, también estoy un tanto cansado de mi padre, que me aburre. Y en cuanto a Shakespeare, ¿cuánto más puedo seguir encajando? No sé si eres consciente de la cantidad de grandes obras de la literatura occidental que ahora están disponibles en excelentes discos de larga duración. Cuando termine con Shakespeare, podré seguir con magníficas representaciones de Sófocles, Sheridan, Aristófanes, Shaw, Racine... pero ¿con qué finalidad? ¿Para qué? Eso sí que es matar el tiempo. Para un pecho eso es el puñetero asesino del tiempo. Voy a ganar un montón de dinero, amigo. Tampoco creo que sea difícil. Si los Beatles son capaces de llenar el estadio Shea, ¿por qué no puedo hacerlo yo? Tenemos que pensar en ello a fondo, tú y yo, claro que ¿para qué ha servido toda aquella educación si no fue para aprender a pensar las cosas a fondo? ¿Para escribir más libros? ¿Para escribir más ensayos críticos? ¿Para contemplar más las cosas superiores? ¿Y qué me dices de la contemplación de las inferiores? Ganaré cientos de miles de dólares, y entonces tendré chicas, de doce y trece años, tres, cuatro, cinco a la vez, desnudas y soltando risitas, y todas al mismo tiempo sobre mi pezón. Quiero que estén ahí días seguidos, codiciosas y traviesas chiquillas, lamiéndome y chupándome a discreción. Y podemos encontrarlas, ya lo sabes. Si los Rolling Stones pueden encontrarlas, si Charles Manson puede encontrarlas, también nosotros, con la educación que tenemos, probablemente podremos encontrar unas cuantas. Y mujeres. También habrá mujeres deseosas de abrirse de piernas sobre una polla tan nueva y emocionante como mi pezón. Creo que será una agradable sorpresa el número de respetables mujeres que llamarán a la puerta del camerino vestidas con sus respetables pieles de chinchilla solo para tener un atisbo del tono de mi suave piel hermafrodita. Bueno, tendremos que ser exigentes, ¿no crees?, tendremos que seleccionarlas de acuerdo con su belleza, buena crianza y deseo lascivo. Y mi felicidad será delirante. Repito: mi felicidad será delirante. ¿Recuerdas a Gulliver entre los brobdingnags? ¿Cómo las sirvientas le hacían pasear sobre sus pezones por pura diversión? Él no consideraba que aquello fuera divertido, pobre y perdido hombrecillo. Claro que era humano, un médico inglés, un hijo de la Era de la Razón, un fiel seguidor del Sentido de la Proporción atrapado en un continente de extravagantes gigantes; pero aquí, mi amigo y cómplice, estamos en la Tierra de la Oportunidad, esta es la Era de la Realización de Sí Mismo, y yo soy el Pecho, ¡y viviré mediante mis propias luces! –¿Vivir o morir por medio de ellas? –Eso está por ver, doctor Klinger. Permítanme ahora que finalice mi conferencia citando al poeta Rilke. Cuando era un profesor de literatura apasionadamente bienintencionado, siempre me gustaba finalizar la clase con algo conmovedor para que los alumnos se lo llevaran del aula sin contaminar al mundo caído de la comida basura, las estrellas pop y la droga. Es cierto que la ocupación de Kepesh ha desaparecido ( _Otelo_ , acto III, escena 3), pero no he perdido del todo mis buenas intenciones de profesor. Tal vez ni siquiera he perdido a mis alumnos. Debido a mi fama, incluso es posible que haya adquirido nuevos y grandes rebaños de ovejas estudiantiles, tan desconocedoras de la calamidad como de la poesía. Es posible que ahora incluso sea una estrella pop y tenga lo que hace falta para poner la gran poesía al alcance de la gente. (–¿Su fama? –dice el doctor Klinger. –Seguramente ahora el mundo entero está enterado –dijo–, excepto tal vez los chinos y los rusos. –De acuerdo con sus propios deseos, el caso se ha llevado con la mayor discreción. –Pero mis amigos lo saben. El personal sanitario lo sabe. Eso basta para empezar cuando se trata de semejante fenómeno. –Es cierto, pero cuando la noticia se filtra desde quienes lo saben al hombre de la calle, este, en general, tiende a no creérselo. –Piensa que es una broma. –Si es que puede apartar la mente de sus propios problemas el tiempo suficiente para pensar en cualquier cosa. –¿Y los medios de comunicación? ¿Me está diciendo que tampoco ellos se han ocupado de esto? –No han dicho ni palabra. –Eso no me lo creo, doctor Klinger. –Mire, no voy a discutir. Se lo dije hace mucho tiempo. Por supuesto al principio hubo indagaciones. Pero no se prestó a nadie la menor ayuda, y como esa gente ha de ganarse la vida igual que todo el mundo, al cabo de un tiempo se marcharon hacia la siguiente desgracia prometedora. –Entonces nadie sabe todo lo que ha ocurrido. –¿Todo? Nadie más que usted lo sabe todo, señor Kepesh. –Bien, tal vez debería ser yo quien se lo contara todo. –Entonces será famoso, ¿no es cierto? –Es mejor la verdad que la fantasía de los periódicos sensacionalistas. Es mejor que lo cuente yo que los locos charlatanes y los imbéciles. –Naturalmente, ¿sabe?, los locos charlatanes y los imbéciles hablarán de todos modos. Debe comprender que nunca aceptarán su punto de vista, al margen de lo que les diga. –Seguiré siendo una broma. –Una broma. Un bicho raro. Y también, si insiste en ser usted quien se lo diga, un charlatán. –Me aconseja que deje las cosas tal como están. Me aconseja que no le diga nada a nadie. –No le aconsejo nada, solo le recuerdo a su amigo barbudo que se sienta en el trono. –El señor Realidad. –Y su principio –dice Klinger.) Y ahora concluiré la clase con el poema de Rainer Maria Rilke titulado «Torso arcaico de Apolo», escrito en París en 1908. Tal vez mi relato, contado aquí en su totalidad por primera vez, y con toda la veracidad de que soy capaz, ilustrará como mínimo esos grandes versos para aquellos de ustedes que no conocían el poema, en particular la admonición final del poeta, que tal vez no sea un sentimiento tan elevado como parece a primera vista. Imbéciles y locos, tipos duros y escépticos, amigos, alumnos, parientes, colegas y todos ustedes desconocidos trastornados, con sus mil millones de huellas dactilares y caras distintas, mis congéneres mamíferos, sigamos todos y cada uno con nuestra educación. _Su inaudita cabeza no hemos visto_ , _donde los ojos maduraban. Pero_ _su torso aún fulge como un candelabro_ , _con su mirar, tan solo atornillado_ _más atrás. Si no, no te cegaría_ _el álabe del pecho, y en el giro_ _silencioso del muslo, una sonrisa_ _no iría al centro donde estuvo el sexo_ ; _la piedra fuera corta y deformada_ _bajo los hombros de caer translúcido_ ; _no brillaría como piel de fiera_ , _ni irrumpiría por todo contorno_ _como una estrella; porque no hay un sitio_ _que no te mire: Has de cambiar tu vida_.* * «Klinger» contiene la palabra _cling_. _To cling to_ significa «aferrarse a». ( _N. del T.)_ * Traducción del alemán de José M.ª Valverde, _Obras de Rainer Maria Rilke_ , Plaza & Janés, Barcelona, 1967. **Philip Roth** obtuvo el Premio Pulitzer por _Pastoral americana_ en 1997. En 1998 recibió la Medalla Nacional de las Artes y las Letras en la Casa Blanca, y la Medalla de Oro de Narrativa, concedida anteriormente a John Dos Passos, William Faulkner y Saul Bellow, entre otros. Ha sido galardonado en dos ocasiones con el National Book Award y el National Book Critics Circle Award. Ha ganado el PEN/Faulkner Award tres veces. En 2005, _La conjura contra América_ obtuvo el Premio de la Society of American Historians. Recientemente Roth ha recibido los dos premios PEN de mayor prestigio: en 2006 el PEN/Nabokov Award y en 2007 el PEN/Saul Bellow Award por logro en la literatura estadounidense. En 2011 se ha sumado a esta formidable lista el Man Booker International. Philip Roth será el tercer escritor estadounidense vivo cuya obra publicará la Library of America en una edición completa y definitiva. Está previsto que el último de los ocho volúmenes vea la luz en 2013. Obras del autor publicadas en Random House Mondadori: _La conjura contra América_ (Mondadori 2005, Debolsillo 2007); _El pecho_ (Mondadori 2006, Debolsillo 2007); _Elegía_ (Mondadori 2006, Debolsillo 2008); _Deudas y dolores_ (Mondadori 2007, Debolsillo 2008); _El profesor del deseo_ (Mondadori 2007, Debolsillo 2009); _Sale el espectro_ (Mondadori 2008, Debolsillo 2009); _Lecturas de mí mismo_ (Mondadori 2008, Debolsillo 2010); _Nuestra pandilla_ (Mondadori 2008, Debolsillo 2010); _Indignación_ (Mondadori 2009, Debolsillo 2010); _La humillación_ (Mondadori 2010, Debolsillo 2011) y _Némesis_ (Mondadori 2011, Debolsillo 2012). Además se han publicado también en Debolsillo: _Pastoral americana, Me casé con un comunista, Operación Shylock, El teatro de Sabbath, Cuando ella era buena, Zuckerman encadenado, La contravida, Patrimonio, El oficio: un escritor, sus colegas y sus obras, Mi vida como hombre, Goodbye, Columbus, La mancha humana, El mal de Portnoy, El animal moribundo, Los hechos_ y _Engaño_. Título original: _The Breast_ Publicado por acuerdo con Farrar, Straus and Giroux LLC, Nueva York Edición en formato digital: mayo de 2013 © 1972, Philip Roth © 2013, Random House Mondadori, S. A. Travessera de Gràcia, 47-49. 08021 Barcelona © 2013, Jordi Fibla, por la traducción «Torso arcaico de Apolo» reproducido de Translations from the Poetry of Rainer Maria Rilke, de M. D. Herter Norton (trad. cast.: Obras de Rainer Maria Rilke, Plaza & Janés, Barcelona, 1967). Reproducido con autorización de W. W. Norton & Company, Inc. © 1938, W. W. Norton & Company, Inc., renovado en 1966 por M. D. Herter Norton. Diseño de la cubierta: © Luz de la Mora Quedan prohibidos, dentro de los límites establecidos en la ley y bajo los apercibimientos legalmente previstos, la reproducción total o parcial de esta obra por cualquier medio o procedimiento, así como el alquiler o cualquier otra forma de cesión de la obra sin la autorización previa y por escrito de los titulares del copyright. Diríjase a CEDRO (Centro Español de Derechos Reprográficos, http://www.cedro.org) si necesita reproducir algún fragmento de esta obra. ISBN: 978-84-397-2766-8 Conversión a formato digital: Newcomlab, S.L. www.megustaleer.com Consulte nuestro catálogo en: www.megustaleer.com Random House Mondadori, S.A., uno de los principales líderes en edición y distribución en lengua española, es resultado de una _joint venture_ entre Random House, división editorial de Bertelsmann AG, la mayor empresa internacional de comunicación, comercio electrónico y contenidos interactivos, y Mondadori, editorial líder en libros y revistas en Italia. Forman parte de Random House Mondadori los sellos Beascoa, Caballo de Troya, Collins, Conecta, Debate, Debolsillo, Electa, Endebate, Grijalbo, Grijalbo Ilustrados, Lumen, Mondadori, Montena, Nube de Tinta, Plaza & Janés, Random, RHM Flash, Rosa dels Vents, Sudamericana y Conecta. Sede principal: Travessera de Gràcia, 47–49 08021 BARCELONA España Tel.: +34 93 366 03 00 Fax: +34 93 200 22 19 Sede Madrid: Agustín de Betancourt, 19 28003 MADRID España Tel.: +34 91 535 81 90 Fax: +34 91 535 89 39 Random House Mondadori también tiene presencia en el Cono Sur (Argentina, Chile y Uruguay) y América Central (México, Venezuela y Colombia). Consulte las direcciones y datos de contacto de nuestras oficinas en www.randomhousemondadori.com.
New device to detect breath metabolites indicative of breast cancer One of the main obstacles in the battle against breast cancer is the lack of effective and economical early diagnostic tools. However, this could now be set to change. Scientists from the University of Michigan have been developing a device able to detect the presence of metabolites linked with breast cancer on the breath of patients. As a result, the team has won a Breast Cancer Research Program Idea award which will support their continued research. “We are very excited about getting this grant without having had too much real exposure to breast cancer research”, said Joerg Lahann, Assistant Professor of Chemical Engineering and principal investigator. The key to the device’s action is based upon ‘switchable surface technology’, the principal of which states that switchable surfaces have molecularly designed sites which attract metabolites associated with breast cancer. The sites are nanopockets able to interact with oil and water. The surfaces are able to stand upright or lie flat. When upright, the spaces are open and thus able to attract the metabolites. The metabolites can be detected optically or via a change in conductance. In order that the device may be reusable, an electric charge may be applied to the surface which would cause the particles to bend, and therefore close, releasing the metabolites. The inspiration for the device came about when one of Lahann’s graduate students, David Pang, read two papers which demonstrated that certain metabolites could mark the presence of breast cancer, via breath and urine. “We realized that if one could put these molecules in a screening platform, they might develop a noninvasive, quick and inexpensive over-the-counter breast cancer screening test”, Lahann said.
#include <iostream> #include<string> #include<queue> using namespace std; int main() { int n , d; cin >> n >> d; string P; cin >> P; int A[n][n] = {}; for(int i = 0 ; i < n ; i++){ if(P[i] == '1'){ for(int j = i + 1 ; j <= (i+d <= n-1) * (i+d) + (i+d > n-1) * (n-1) ; j++){ if(P[j] == '1'){ A[i][j] = 1; A[j][i] = 1; } } } } int R[n] = {}; R[0] = 0; queue<int> Q; Q.push(0); while(!Q.empty()){ for(int i = 0 ; i < n ; i++){ if(A[Q.front()][i] and R[i]==0){ Q.push(i); R[i] = R[Q.front()]+1; } } Q.pop(); } if(R[n-1]) cout << R[n-1]; else cout << -1; }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, ViewEncapsulation, OnInit, ViewChild } from '@angular/core'; import addSeconds from 'date-fns/add_seconds'; import format from 'date-fns/format'; import { CountdownEvent, CountdownConfig, CountdownComponent } from 'ngx-countdown'; import { warnDeprecation } from 'ng-zorro-antd/core'; @Component({ selector: 'count-down', exportAs: 'countDown', template: ` <countdown #cd *ngIf="config" [config]="config" (event)="handleEvent($event)"></countdown> `, preserveWhitespaces: false, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class CountDownComponent implements OnInit { @ViewChild('cd', { static: false }) readonly instance: CountdownComponent; @Input() config: CountdownConfig; /** * 目标时间 */ @Input() set target(value: number | Date) { this.config = { format: `HH:mm:ss`, stopTime: typeof value === 'number' ? addSeconds(new Date(), value).valueOf() : +format(value, 'x'), }; } @Output() readonly begin = new EventEmitter<void>(); @Output() readonly notify = new EventEmitter<number>(); @Output() readonly end = new EventEmitter<void>(); @Output() readonly event = new EventEmitter<CountdownEvent>(); ngOnInit(): void { if (this.begin.observers.length > 0 || this.notify.observers.length > 0 || this.end.observers.length > 0) { warnDeprecation(`begin, notify, end events is deprecated and will be removed in 9.0.0. Please use 'event' instead.`); } } handleEvent(e: CountdownEvent) { switch (e.action) { case 'start': this.begin.emit(); break; case 'notify': this.notify.emit(e.left); break; case 'done': this.end.emit(); break; } this.event.emit(e); } }
// ToDecimal converts value to it"s decimal representation in string. func (web3 *Web3) ToDecimal(value interface{}) string { n := web3.ToBigNumber(value) if n.IsInt() { return n.Num().String() } return n.String() }
def writeTags(event, tags): tagsAsKeyValue = getKeyValueFromEnv(tags) logIfDebug('Tags to change:',tagsAsKeyValue) try: ec2_client = boto3.client('ec2', region_name=event['region']) response = ec2_client.create_tags( DryRun=False, Resources=getIdFromVpcArn(event['resources']), Tags=tagsAsKeyValue ) logIfDebug('create_tags response', response) except Exception as e: logger.error('writeTags: ' + e.message)
<reponame>aut0mat3d/platform-atmelavr import sys from os.path import join from SCons.Script import Import, Return Import("env") def get_lfuse(target, f_cpu, oscillator, bod, eesave): targets_1 = ( "atmega2561", "atmega2560", "atmega1284", "atmega1284p", "atmega1281", "atmega1280", "atmega644a", "atmega644p", "atmega640", "atmega328", "atmega328p", "atmega324a", "atmega324p", "atmega324pa", "atmega168", "atmega168p", "atmega164a", "atmega164p", "atmega88", "atmega88p", "atmega48", "atmega48p") targets_2 = ( "atmega328pb", "atmega324pb", "atmega168pb", "atmega162", "atmega88pb", "atmega48pb", "at90can128", "at90can64", "at90can32") targets_3 = ("atmega8535", "atmega8515", "atmega32", "atmega16", "atmega8") targets_4 = ("attiny13", "attiny13a") if target in targets_1: if oscillator == "external": return 0xf7 else: return 0xe2 if f_cpu == "8000000L" else 0x62 elif target in targets_2: if oscillator == "external": return 0xff else: return 0xe2 if f_cpu == "8000000L" else 0x62 elif target in targets_3: if bod == "4.0v": bod_bits = 0b11 elif bod == "2.7v": bod_bits = 0b01 else: bod_bits = 0b00 bod_offset = bod_bits << 6 if oscillator == "external": return 0xff & ~ bod_offset else: if f_cpu == "8000000L": return 0xe4 & ~ bod_offset else: return 0xe1 & ~ bod_offset elif target in targets_4: eesave_bit = 1 if eesave == "yes" else 0 eesave_offset = eesave_bit << 6 if oscillator == "external": return 0x78 & ~ eesave_offset else: if f_cpu == "9600000L": return 0x7a & ~ eesave_offset elif f_cpu == "4800000L": return 0x79 & ~ eesave_offset elif f_cpu == "1200000L": return 0x6a & ~ eesave_offset elif f_cpu == "600000L": return 0x69 & ~ eesave_offset elif f_cpu == "128000L": return 0x7b & ~ eesave_offset elif f_cpu == "16000L": return 0x6b & ~ eesave_offset else: sys.stderr.write("Error: Couldn't calculate lfuse for %s\n" % target) env.Exit(1) def get_hfuse(target, uart, oscillator, bod, eesave): targets_1 = ( "atmega2561", "atmega2560", "atmega1284", "atmega1284p", "atmega1281", "atmega1280", "atmega644a", "atmega644p", "atmega640", "atmega328", "atmega328p", "atmega328pb", "atmega324a", "atmega324p", "atmega324pa", "atmega324pb", "at90can128", "at90can64", "at90can32") targets_2 = ("atmega164a", "atmega164p", "atmega162") targets_3 = ( "atmega168", "atmega168p", "atmega168pb", "atmega88", "atmega88p", "atmega88pb", "atmega48", "atmega48p", "atmega48pb") targets_4 = ("atmega128", "atmega64", "atmega32") targets_5 = ("atmega8535", "atmega8515", "atmega16", "atmega8") targets_6 = ("attiny13", "attiny13a") eesave_bit = 1 if eesave == "yes" else 0 eesave_offset = eesave_bit << 3 ckopt_bit = 1 if oscillator == "external" else 0 ckopt_offset = ckopt_bit << 4 if target in targets_1: if uart == "no_bootloader": return 0xdf & ~ eesave_offset else: return 0xde & ~ eesave_offset elif target in targets_2: if uart == "no_bootloader": return 0xdd & ~ eesave_offset else: return 0xdc & ~ eesave_offset elif target in targets_3: if bod == "4.3v": return 0xdc & ~ eesave_offset elif bod == "2.7v": return 0xdd & ~ eesave_offset elif bod == "1.8v": return 0xde & ~ eesave_offset else: return 0xdf & ~ eesave_offset elif target in targets_4: if uart == "no_bootloader": return (0xdf & ~ ckopt_offset) & ~ eesave_offset else: return (0xde & ~ ckopt_offset) & ~ eesave_offset elif target in targets_5: if uart == "no_bootloader": return (0xdd & ~ ckopt_offset) & ~ eesave_offset else: return (0xdc & ~ ckopt_offset) & ~ eesave_offset elif target in targets_6: if bod == "4.3v": return 0x9 elif bod == "2.7v": return 0xfb elif bod == "1.8v": return 0xfd else: return 0xff else: sys.stderr.write("Error: Couldn't calculate hfuse for %s\n" % target) env.Exit(1) def get_efuse(mcu, uart, bod): mcus_1 = ( "atmega2561", "atmega2560", "atmega1284", "atmega1284p", "atmega1281", "atmega1280", "atmega644a", "atmega644p", "atmega640", "atmega328", "atmega328p", "atmega324a", "atmega324p", "atmega324pa", "atmega164a", "atmega164p") mcus_2 = ("atmega328pb", "atmega324pb") mcus_3 = ( "atmega168", "atmega168p", "atmega168pb", "atmega88", "atmega88p", "atmega88pb") mcus_4 = ("atmega128", "atmega64", "atmega48", "atmega48p") mcus_5 = ("at90can128", "at90can64", "at90can32") mcus_6 = ("atmega162",) mcu_without_efuse = ("atmega8535", "atmega8515", "atmega8", "atmega16", "atmega32") if mcu in mcu_without_efuse: return None if mcu in mcus_1: if bod == "4.3v": return 0xfc elif bod == "2.7v": return 0xfd elif bod == "1.8v": return 0xfe else: return 0xff elif mcu in mcus_2: if bod == "4.3v": return 0xf4 elif bod == "2.7v": return 0xf5 elif bod == "1.8v": return 0xf6 else: return 0xf7 elif mcu in mcus_3: return 0xfd if uart == "no_bootloader" else 0xfc elif mcu in mcus_4: return 0xff elif mcu in mcus_5: if bod == "4.1v": return 0xfd elif bod == "4.0v": return 0xfb elif bod == "3.9v": return 0xf9 elif bod == "3.8v": return 0xf7 elif bod == "2.7v": return 0xf5 elif bod == "2.6v": return 0xf3 elif bod == "2.5v": return 0xf1 else: return 0xff elif mcu in mcus_6: if bod == "4.3v": return 0xf9 elif bod == "2.7v": return 0xfb elif bod == "1.8v": return 0xfd else: return 0xff else: sys.stderr.write("Error: Couldn't calculate efuse for %s\n" % mcu) env.Exit(1) def is_target_without_bootloader(target): targets_without_bootloader = ( "atmega48", "atmega48p", "attiny4313", "attiny2313", "attiny1634", "attiny861", "attiny841", "attiny461", "attiny441", "attiny261", "attiny167", "attiny88", "attiny87", "attiny85", "attiny84", "attiny48", "attiny45", "attiny44", "attiny43", "attiny40", "attiny26", "attiny25", "attiny24", "attiny13", "attiny13a" ) return target in targets_without_bootloader def get_lock_bits(target): if is_target_without_bootloader(target): return "0xff" return "0x0f" board = env.BoardConfig() platform = env.PioPlatform() core = board.get("build.core", "") target = board.get("build.mcu").lower() if board.get( "build.mcu", "") else env.subst("$BOARD").lower() lfuse = board.get("fuses.lfuse", "") hfuse = board.get("fuses.hfuse", "") efuse = board.get("fuses.efuse", "") lock = board.get("fuses.lock", get_lock_bits(target)) if (not lfuse or not hfuse) and core not in ( "MiniCore", "MegaCore", "MightyCore", "MajorCore"): sys.stderr.write("Error: Dynamic fuses generation for %s is not supported." " Please specify fuses in platformio.ini\n" % target) env.Exit(1) if core in ("MiniCore", "MegaCore", "MightyCore", "MajorCore"): f_cpu = board.get("build.f_cpu", "16000000L").upper() oscillator = board.get("hardware.oscillator", "external").lower() bod = board.get("hardware.bod", "2.7v").lower() uart = board.get("hardware.uart", "uart0").lower() eesave = board.get("hardware.eesave", "yes").lower() print("Target configuration:") print("Target = %s, Clock speed = %s, Oscillator = %s, BOD level = %s, " "UART port = %s, Save EEPROM = %s" % (target, f_cpu, oscillator, bod, uart, eesave)) lfuse = lfuse or hex(get_lfuse(target, f_cpu, oscillator, bod, eesave)) hfuse = hfuse or hex(get_hfuse(target, uart, oscillator, bod, eesave)) efuse = efuse or get_efuse(target, uart, bod) fuses_cmd = [ "avrdude", "-p", "$BOARD_MCU", "-C", '"%s"' % join(platform.get_package_dir("tool-avrdude"), "avrdude.conf"), "-c", "$UPLOAD_PROTOCOL", "$UPLOAD_FLAGS" ] if not is_target_without_bootloader(target): fuses_cmd.append("-e") fuses_cmd.extend([ "-Ulock:w:%s:m" % lock, "-Uhfuse:w:%s:m" % hfuse, "-Ulfuse:w:%s:m" % lfuse ]) if efuse: efuse = efuse if isinstance(efuse, str) else hex(efuse) fuses_cmd.append("-Uefuse:w:%s:m" % efuse) print("Selected fuses: [lfuse = %s, hfuse = %s%s]" % ( lfuse, hfuse, ", efuse = %s" % efuse if efuse else "")) fuses_action = env.VerboseAction(" ".join(fuses_cmd), "Setting fuses") Return("fuses_action")
/** * An exception handler that reports exceptions using a <em>shiny banner</em> * (an alert placed on the top of the screen). Once the stack trace is * prepared, it is revealed in the banner via a link. */ public class ErrorHandler implements GWT.UncaughtExceptionHandler { // Use of GWT logging is only intended for sending exception reports to the // server, nothing else in the client should use java.util.logging. // Please also see WebClientDemo.gwt.xml. private static final Logger REMOTE_LOG = Logger.getLogger("REMOTE_LOG"); /** Next handler in the handler chain. */ private final GWT.UncaughtExceptionHandler next; /** * Indicates whether an error has already been reported (at most one error * is ever reported by this handler). */ private boolean hasFired; private ErrorHandler(GWT.UncaughtExceptionHandler next) { this.next = next; } public static void install() { GWT.setUncaughtExceptionHandler(new ErrorHandler( GWT.getUncaughtExceptionHandler())); } @Override public void onUncaughtException(Throwable e) { if (!hasFired) { hasFired = true; final ErrorIndicatorPresenter error = ErrorIndicatorPresenter.create(RootPanel.get("banner")); if (LogLevel.showErrors()) { getStackTraceAsync(e, new AsyncHolder.Accessor<SafeHtml>() { @Override public void use(SafeHtml stack) { error.addDetail(stack, null); REMOTE_LOG.severe(stack.asString().replace("<br>", "\n")); } }); } } if (next != null) { next.onUncaughtException(e); } } private void getStackTraceAsync(final Throwable t, final AsyncHolder.Accessor<SafeHtml> whenReady) { // TODO: Request stack-trace de-obfuscation. For now, just use the // javascript stack trace. // // Use minimal services here, in order to avoid the chance that reporting // the error produces more errors. In particular, do not use WIAB's // scheduler to run this command. // Also, this code could potentially be put behind a runAsync boundary, to // save whatever dependencies it uses from the initial download. new Timer() { @Override public void run() { SafeHtmlBuilder stack = new SafeHtmlBuilder(); Throwable error = t; while (error != null) { String token = String.valueOf((new Date()).getTime()); stack.appendHtmlConstant("Token: " + token + "<br> "); stack.appendEscaped(String.valueOf(error.getMessage())). appendHtmlConstant("<br>"); for (StackTraceElement elt : error.getStackTrace()) { stack.appendHtmlConstant("\t at ") .appendEscaped(maybe(elt.getClassName(), "??")) .appendHtmlConstant(".") // .appendEscaped(maybe(elt.getMethodName(), "??")) .appendHtmlConstant("(") // .appendEscaped(maybe(elt.getFileName(), "??")) .appendHtmlConstant(":") // .appendEscaped(maybe(elt.getLineNumber(), "??")) .appendHtmlConstant(")") // .appendHtmlConstant("<br>"); } error = error.getCause(); if (error != null) { stack.appendHtmlConstant("Caused by: "); } } whenReady.use(stack.toSafeHtml()); } }.schedule(1); } private static String maybe(String value, String otherwise) { return value != null ? value : otherwise; } private static String maybe(int value, String otherwise) { return value != -1 ? String.valueOf(value) : otherwise; } }
WASHINGTON, DC, January 24, 2013 (ENS) – Climate change is getting renewed attention in Congress. Representative Henry Waxman of California and Senator Sheldon Whitehouse of Rhode Island, both Democrats, today announced the formation of a Task Force on Climate Change that will be active in both the House and the Senate. Inspired by President Barack Obama’s statement in his inaugural address that failing to respond to the threat of climate change would “betray our children and future generations,” the task force aims to focus Congressional and public attention on developing effective policy responses, and will be open to all Members of Congress interested in collaborating on this issue. The Task Force will be co-chaired by Waxman, who serves as the Ranking Member of the House Energy and Commerce Committee, and Whitehouse, who chairs the Subcommittee on Oversight for the Senate Environment and Public Works Committee. “Congress and the public need to understand that climate change impacts are turning out worse than expected and our window to act is closing,” said Waxman. “This threat is not waiting until we are ready to deal with it. That is why I am pleased to join with Senator Whitehouse to work to educate our colleagues and all Americans about the magnitude of the problem and the urgency of the threat we are confronting.” “I’m honored to join Representative Waxman in this effort,” said Whitehouse. “Carbon pollution is wreaking havoc on our atmosphere and on our oceans, and it’s time to bring all hands on deck as we seek to meet that challenge.” “We intend this new group to bring the attention and energy to the issue necessary to get something done,” he said. “I look forward to working with President Obama, Chairman [Barbara] Boxer in the Senate, and any of our other colleagues who wish to join us.” Senator Boxer, who chairs the Senate Environment and Public Works Committee, said, “Dangerous climate change poses an urgent threat and we have a responsibility to address that threat.” On January 11, Boxer announced that environmental attorney Joe Mendelson will join her EPW team as chief climate counsel. Previously, Mendelson served as the policy director of the Climate and Energy Program at the National Wildlife Federation. He played a key role in a landmark 2007 U.S. Supreme Court decision that established that the Environmental Protection Agency has jurisdiction over reducing carbon pollution from motor vehicles. As a first order of business in the new task force, Waxman, Whitehouse and Congressman Ed Markey of Massachusetts, the Ranking Member of the House Committee on Natural Resources, today sent a letter to President Obama. They applauded his recognition of climate change in his inaugural address, pledged to help him address this issue, and urged him to quickly develop a comprehensive climate change plan. “The window to deal effectively with a warming planet and to mitigate long-term risks is quickly closing,” they wrote. “Meanwhile, oil and coal industries continue to spend hundreds of millions of dollars denying the science, exaggerating the costs, and confusing the public. As a result, too few Americans fully appreciate the magnitude of the problem or the urgency of the threat we are confronting.” The lawmakers ask for “presidential leadership” to “forge together a national consensus that insists on addressing climate change.” They ask the President not to wait for Congress to act, but to use his administration’s “broad authorities” to lower heat-trapping emissions, to encourage clean energy research and development and develop adaptive strategies. “We in Congress need your leadership most of all,” the Democratic lawmakers wrote. “Virtually all Republicans in Congress opposed comprehensive climate legislation in the 11th Congress, and they voted to strip EPA of regulatory authority in the last one.” “Progress in Congress may be so difficult or protracted that you should not hesitate to act,” they wrote. “Congress will benefit from knowing what actions you will take administratively to meet your climate pledge and protect our nation. And we will benefit even more from a concerted effort between your administration and your allies in Congress to marshal the latent public support into a political force.” Environmentalists greeted the climate task force with enthusiasm. Environmental Defense Fund President Fred Krupp said, “I’m very happy to hear that Senator Sheldon Whitehouse and Congressman Henry Waxman are creating a new task force to fight climate change. In his inaugural address, President Obama called on all of us to protect our children and future generations from the dangers of climate change.” “At EDF, we’re grateful to these lawmakers for their ongoing leadership on this critical issue, and we stand ready to help the task force however we can.” Krupp said the task force, along with Senator Barbara Boxer’s recently announced “climate clearinghouse,” are steps towards “reducing the pollution that endangers us.” Boxer said in December that this year she will hold weekly “open forums” on climate change, and she hopes both Republicans and Democrats will participate in the “climate change clearinghouse” to discuss potential global warming legislation. “We are going to review the latest information, we are going to work on supporting a major bill, we are also going to work on various smaller provisions that we think will move us forward and focus on green jobs, energy efficiency and making sure that we get the carbon out of the air, and work with the administration on some executive stuff,” Boxer told “The Hill.” Boxer said a major climate change bill would cap carbon emissions and find ways to “harden our infrastructure to protect our people against extreme weather.” Copyright Environment News Service (ENS) 2013. All rights reserved.
AN ANALYSIS ON CBT NATIONAL EXAMINATION EFFECT: STUDENTS’ COGNITIVE READINESS AND ANXIETY FACING ENGLISH TESTS The purpose of this study was to know the influence of CBT and PBT national examination dealing with students’ cognitive readiness and anxiety facing English national examination in Cilacap regency, the influence of major in terms of students’ cognitive readiness and anxiety facing English national examination in Cilacap regency, and the interaction between national examination and major. This research was descriptive explorative and the method was ex-post facto. The population was all of natural and social science high school students in grade XII in Cilacap regency. The number of sample used was 352 students. The results showed that there was significant influence of national examination in terms of students’ cognitive readiness and anxiety facing national examination. However, CBT and PBT national examination did not influence the cognitive readiness facing national examination, CBT and PBT national examination influence in national examinations in terms of students’ anxiety facing national examination. The average score of the students' anxiety facing CBT national exam was higher than that of the students' anxiety facing PBT national examination. There was no effect caused by differences in majoring in terms of cognitive readiness and anxiety in facing English national examination; and there was no interaction between the different types of national examinations and majors. : ‫األساسية‬ ‫الكلمات‬ CBT. PBT ‫الوطني‬ ‫االمتحان‬ ، ‫القلق‬ ‫املعرفي‬ ‫االستعداد‬ A. INTRODUCTION As stated at Ministerial regulation number 20, 2003 that education is an effort to create an atmosphere of learning and the learning process consciously and deliberately as learners are actively developing the potential to have the spiritual power of religion, self-control, personality, intelligence, character, and skill needed by society, nation and state. The implementation of education is learning process where the success of learning process measured from the implementation of learning objectives. According to Nitko (2011, p.20), the student's achievement of learning process implementation is specific goal. To know the result of learning process, Bichi & Moses (2015. P.290) mentioned that assessment takes an important role in the educational process and it is used as a tool in students' performance evaluation. Moreover, Ebbut & Straker (Marsigit, 2003, pp.5-6), clarify that the evaluation phase is the final stage of a learning process. Dealing with assessment, the government used national examination (UN) to determine the extent of competence achieved by students. As stated by Ministry of Education, national examination is the measurement and assessment of the national competency achievement in specific subjects. One of the subjects in the national examination in Senior High School is English. English national examination aims at measuring the ability of English from the first to the last year. Based on the Permendikbud number 5 (2015, p.9), national examination in the academic year 2014/2015 on junior and senior high school are conducted in two types, namely Paper-Based Test (PBT) and/or Computer-Based Test (CBT). PBT national examination system is also called Pencil and Paper Test (PPT). It is because PBT needs pencils and papers in doing national examination. One of problem on PBT is paper distribution especially to remote areas in Indonesia. However, there are some advantages of PBT national examination system as students can perform the examination in an easy way because it allows students to do the examination without any special preparation. Bennett (2003, p.4), states that examination or lab tests with PBT systems for certain classes generate learning outcomes higher than to other systems, especially in English examination. In addition, the infrastructure used in PBT is simpler because its implementation does not require a lot of devices for preparation and costs for the development of facilities and infrastructure. AlAmri (2007, p.107), states that PBT national examination system is more convenient, comfortable, and already accustomed. Recently, the government adopted CBT as the latest national examination systems. The use of CBT national examination for schools in Indonesia started in 2014/2015. In the early stage, the CBT national examination system in Cilacap Regency and followed by 8 schools included senior and vocational schools. In 2015/2016, the number of schools implementing CBT national examination was increase 14 high schools. CBT system, according to Anies Baswedan, needs three sessions with only one subject a day so the result are maintained. In addition, Temitayo, Adebisi, & Alice (2013, p.336), added that CBT is suitable way for school which has many students in evaluation or educational assessment. In contrast, Thurlow, Lazarus, Albus, et al. (2010, pp.22-28) state that it is possible if the lack of computers and supporting infrastructure will cause anxiety among students since they are not accustomed to use it. Although, CBT national exam system is done in three sessions in a day, the third sessions will be done in the afternoon at 2:00-4:00 p.m. as the result, the implementation CBT national examination system is longer than the PBT national examination system which can accommodate two subjects in one day. Beside considering the students' anxiety aspect, the students' readiness is also important aspect. The national examination is conducted in every year and it demands the readiness of both students and schools. Readiness is important especially for students in class XII. It is because students will face national examination. Based on the results of a research conducted by Rumasoreng & Sugiman (2014, p.27), 58.95% of students in DIY give wrong answer in English national examination. It shows that readiness is very needed to face English national examination. Schools which implement CBT national examination also should prepare a sufficient number of computers or the number of the examinees, the internet network, the bandwidth capacity of at least 1 Mbps, Uninterruptable Power Supply (UPS), and two technicians. So, it takes more and longer preparation. English national examination in senior high school level is obligated to all majors chosen by students. The majors are natural science, social science, and language major. However, in general, most of senior high school offers social and science major. Burns (2004, p.119), state that the success of the exam is influenced by students' activities during preparations and their knowledge. Therefore, the students hope that the result will be in line with their knowledge and readiness. According to Harjanto, (2000, p.24) readiness is defined as a willingness to determine what type of actions as a result of it being received. Moreover, Hamalik (2005, P.39), states that readiness is a result of training or learning and maturity. The results of students' learning or maturity in national examination can be seen from students' cognitive readiness. Consequently, to know the students' cognitive readiness level, the school implemented test which is called "try out" of national examination. According to Mardapi (2012: pp.6-7), national examination has both positive and negative effects. One of the negative impacts is teachers and students' anxiety. Although anxiety in certain limits is needed to motivate students to learn better, too high level of anxiety can lead students to become stressful. Woolfolk, Anita, and Loraine (1984, p.301), supported that test or examination are situation in schools which mostly cause students' high level of anxiety. It is because the result of a national examination is considered to be an important factor to determine the next level of education that will be faced by students. In reality, some students still feel anxiety although the process of improving students' cognitive readiness has been done. Each student faced different level of anxiety from one to another. As stated by Dobson (2012, p.4), different students will have a different anxiety response to face a situation. In addition, Woolfolk, Anita, and Loraine (1984, p.298), students' anxiety is the result of unsuccessful tasks. Students' anxiety in facing a national examination also can be caused by their high expectations of the national examinations result. As mentioned in the background, this paper is intended to investigate the effects of CBT national examination system to students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency. The study is purposed to determine the influences of the CBT and PBT national examination systems for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency, to determine the effects of taking major in natural and social science for cognitive readiness and anxiety in facing English national examination in Cilacap Regency, and to investigate the relations between national examination systems and the majors taken. B. METHODS This research is done in descriptive exploratory study with an ex-post facto method. The research was conducted to grade XII students in the academic year of 2016/2017 in 2 schools that implemented the PBT national examination system and 2 schools that employed the CBT national examination system in Cilacap regency. The study started on March 19th, 2017 until May 10th, 2017. Population and Sample The population in this study was all students of class XII from high schools in Cilacap in the academic year of 2016/2017. The school was determined by selecting state or private school which has huge number of students. The number of schools selected implementing CBT national examination were the same with schools implementing PBT national examination. There were 783 populations. Based on Krejcie and Morgan's table, the number of minimum sample will be 176 students. This study used 352 students as samples. Research Variables The variables in this study consist of independent variables that is government policy on the CBT and PBT national examination system, and high school students who take natural and social science major. The dependent variables of this study consist of students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency. Instruments and Data Collection Techniques The study was done before the national examination was held. The students were asked to do multiple choice test instruments to measure their English cognitive readiness. The test had been adapted by indicators of English national examination in 2016/2017. Supporting the data from the test result, the samples were also given a questionnaire to measure students' anxiety in facing English national exams using either CBT or PBT system. Time allocation was 120 minutes. The next step in this research was analyzing data from the results of students' cognitive readiness and anxiety test statistically. It was to determine effects of CBT national examination system for students' cognitive readiness and anxiety in facing English national examination in Cilacap regency. Validity and Reliability Instruments This study used content and construct validity. Content validity was used to prove the validity of test instruments. It was suited with indicators of English national examination in 2016/2017. Content validity was also used to prove the validity of the anxiety questionnaire. Construct validity was used to prove the validity of the questionnaires. Construct validity used factor analysis. Results of construct validity for the anxiety questionnaire instrument shows that KMO's value is 0.620. It is more than 0.5 which means that samples used in the study are sufficient. In addition, from the analysis, it is shown that there are 9 factors obtained from the total factors. The number represents 59.14% of the variables. The construct validity result of the anxiety in facing PBT national examination system questionnaire is 0.640. It is more than 0.5 which means that the number of samples used in the study is sufficient. In addition, from the analysis, it is shown that there are 9 factors obtained from the total factors. The number represents 65.44% of the variables. Estimated reliability of the cognitive readiness instrument used was KR-20. It is because the instrument used multiple choice formats. Estimated reliability of students' anxiety used was internal consistency reliability shown by Cronbach alpha coefficient. The reliability test estimation result of cognitive readiness in natural science major was calculated using the KR-20. It is 0.681 and the SEM score is 1.453. The reliability test estimation result of cognitive readiness in social science major was also calculated using the KR20. It is 0.803 and the SEM score is 2.82. The results of the analysis of the anxiety reliability estimation in facing examination using CBT questionnaire is 0.724 to 5.79 in SEM values. The reliability estimation results of the anxiety in facing PBT national examination questionnaire is 0,880 and the SEM score is 5.78 Data Analysis Techniques A descriptive analysis was conducted to obtain data descriptions of students' cognitive readiness and anxiety in facing CBT and PBT national examination. Descriptive analysis was presented in the average, median, mode, standard deviation, and the maximum and minimum score of each data. The next analysis was equalization. The purpose of this analysis is to produce scores that are interchangeable (Retnawati, 2014, p.93). It used horizontal equalization with equivalent group design. Equalization method was based on the classical theory using equipercentile method. Percentile metric scores on two tests were matched according to the same percentile (Dragon, 1992, p.358). The analysis was followed by hypothesis testing. Hypothesis testing was done by using two-ways MANOVA. However, before the hypothesis test, there were previous assumption tests of normality and homogeneity. Prerequisite test was used to test the normality of the data by looking at the samples. Multivariate normality test used Mahalanobis distance test. : Mahalonobis distance : jth-data, j = 1,2, ..., n : Average of data : Inverse matrix of covariates A decision criterion is if the correlation coefficient is more than r table or sig. less than 0.5., it means that there is a significant correlation or normal distribution of data. The second assumption used was homogeneity test. Homogeneity test aims to determine the variety of the population. It is shown by looking at the matrix covariance of cognitive readiness and anxiety in facing CBT and PBT national examination scores. Multivariate homogeneity test used was Box's M test. A decision criterion is if the significant value is more than 0.05 then the data is homogeneous. Hypothesis testing used was two-ways MANOVA analysis. The first hypothesis test was to determine implementation effects of CBT and PBT national examination system for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency. Hypothesis: (There was no influence of national examination system (CBT and PBT) for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency). (There was influence of national examination system (CBT and PBT) for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency). The second hypothesis was to determine influences of the majors (natural and social science) for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency. Hypothesis: (There was no effect of majors on the students' cognitive readiness and anxiety facing English national examination in Cilacap Regency) (There was effect of majors on the students' cognitive readiness and anxiety facing English national examination in Cilacap Regency). The third hypothesis test was to determine relations between the national examination system and majors. Hypothesis: (There were no interaction between national examination system and majors). Tarling Vol. 1 No. 2 (There were no interaction between national examination system and majors). : An average score of students who did the CBT national examination system on natural science major. : Students' average score of students who did the CBT national examination system on social science major. : Students' average score of students who did the PBT national examination system on natural science major. : Students' average score of students who did the PBT national examination system on social science major. If the hypothesis test showed that there is an influence of the national examination system for students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency, it is continued by looking at tables Test of Between-Subject Effects to determine the differences between variables. C. RESULTS AND DISCUSSIONS The data description of cognitive readiness of students facing CBT national examination is presented in Table 1. Minimum score 10 10 10 Table 1 shows that the students' cognitive readiness in facing CBT national examination. Natural science students' average score of cognitive readiness is lower (20.467) than social science students (20.717), while the overall average score is 20.284. Both natural and social science students have the same median score which is 19. The mode score of natural science students is lower than social science students'. The natural science students' mode score is 15 and the social science students' is 19. It is the same mode score overall. Standard deviation scores of natural science students is higher (6.174) that social science (5.809). Both groups have the same minimum score that is 10 but they have different maximum score. Natural science students have 35 as the maximum score while the maximum score of social science is 32. Actually, the overall maximum score is 35 It implies that the range scores of cognitive readiness in facing CBT national examination is 10-35 and overall score range is 0-40. Facing PBT National Examination. The data description of students' anxiety in facing English national examination is presented in Table 2. Minimum score 10 10 10 Table 2 shows that the study conducted to 186 students majoring natural science and 166 sudents majoring social science. Natural science students' average score of cognitive readiness is lower (22.567) than social science students (19.817), while the overall average score is 20.83. Median score of students majoring natural science is same with overall median score that is 20. But it is lower than students majoring social science median score that is 21. However, the students majoring natural science mode scores that is same as the overall mode score 25 is higher than students majorng social science mode score that is 19. Students majoring natural science standard deviation score is also higher than social science. Although the students majoring natural science have higher maximum score (35) than social science (32), but the minimum score of the two majors are same that was 10. It implies that the range score of cognitive readiness in facing PBT national examination is same with the range scores of cognitive readiness in facing CBT national examination that was 10-35. Maximum score 120 118 120 Minimum score 50 50 50 Table 3 shows that the study conducted to 186 students majoring natural science and 166 students majoring social science facing CBT national examination. Natural science students' average score of anxiety is higher (88,75) than social science students (86,43). It states that natural science students feel more anxious than the other group. Natural science students' median score of anxiety is also higher (89) than social science (85). It is also higher than the overall median score. Natural science students' mode score of anxiety facing CBT national examination is also higher at 87 and 88 than Tarling Vol. 1 No. 2 social at 83. Standard deviation score of natural science students is 14,46 and social science is 14,90. Maximum and minimum anxiety score of natural science student is also higher than social science, maximum is 120 and minimum is 48, than social science that has maximum score is 118 and minimum score is 50. It implies that the overall range anxiety scores facing CBT national examination is 45-118. Table 4 shows that the study conducted to 186 students majoring natural science and 166 students majoring social science facing PBT national examination. Natural science students' average score of anxiety facing national exami-nation is higher (82.75) than social science students that students' average scores is 78.35. While the overall average score is 81,89. Natural science students' median score is also higher at 83 then social sciences that are 84. Overall median score is 82,5. Natural science, social science, and overall mode score is same that is 85. The standard deviation of natural science students is higher (12,46) than social science that is11,85. Maximum score of natu-ral science students (115) is higher than social science (108). Meanwhile, minimum score of natural science student facing PBT national examination is lower (40) than social science students (50). It implies that overall range anxiety scores facing PBT national examination is 40-118. The anxiety criteria of each student in facing national examination are different. Students' anxiety criteria in facing CBT and PBT national examination systems are categorized in Table 5. Based on a range of anxiety criteria in Table 5, it explains that the average score of natural science students' anxiety in facing CBT national examination is 88,75 while the average score of social science students' anxiety is 86,43. The both of them categorized into moderate. Overall, the average score of students' anxiety in facing CBT national examination (87,64) is categorized into a moderate criterion. The average score of natural science students' anxiety in facing PBT national examination system (82,75) is categorized into a moderate criterion. The average score of social science (78, 35) is categorized into a low criterion. However, overall average scores of students' anxiety in facing PBT national examination system (81,89) are categorized into a moderate criterion. The result shows that the highest students' anxiety facing CBT national examination belongs to natural science students while the lowest belongs to social science students. In addition, it demonstrates that the average score of students' anxiety in facing CBT national examination is higher than those facing PBT. The hypothesis analysis was further examined by using two-ways Manova. Previously, prerequisite tests consisting of normality and homogeneity tests must be done. The normality test is used to determine whether the data obtained is a normal distribution or not. Mahalanobis distance analysis used SPSS application. It used a correlation between Mahalanobis distance and value. It is presented in Table 6 . According to Table 6, it is shown that the normality test conducted to a sample group of students implementing the CBT national examination has 0.00 significance values. It is less than 0.05 so that there is a significant correlation. In other word, the data have a multivariate normal distribution. Moreover, the correlation value 0.993 which is higher than r-table = 0.1519 states that data is normal. Students implementing PBT national examination has normality test score 0.000 which is less than 0.05. It shows that there is a significant correlation or the data have a multivariate normal distribution. The prerequisite test aims to determine the homogeneity of variance of the population. Based on the multivariate calculation, it is known that the significance level is 0.051 or higher than 0.05. It means that the data is homogeneous. In other word, the covariance matrix score of students facing CBT national examination system is the same with students facing PBT national examination system. The first hypothesis test is to answer the problem formulation whether the CBT and PBT national examination system significantly influence students' cognitive readiness and anxiety in facing English national examination in Cilacap Regency. Based on the analysis, the significance value is 0,001. It is less than 0.05 so that H0 was rejected. It means that there is a significant influence of national examination systems on the students' cognitive readiness and anxiety. The second hypothesis test is to answer the problem whether the majors taken affect students' cognitive readiness and anxiety in facing English national examination. Manova test results show 0.691 significance value, higher than 0.05 so that H0 was accepted. It states that there is no influence caused by different majors for students' cognitive readiness and anxiety. Some natural or social science students faced CBT national examination and others faced PBT national examination system. There is no significant difference in anxiety level among them. Moreover, sense of inadequacy was also felt by students in both majors. Each of the students had personal goals that must be achieved on the national examination. It triggered students' anxiety that appeared on each student's self. The third hypothesis test is used to answer the problem formulation whether there are relations between the national examination systems and the majors. The score earned from multivariate analysis is 0.914. It is more than 0.05 so that H0 is accepted. It means that there is no relation between national examination systems and majors. In natural and social science major, there were different English materials. Besides, the majors got the same treatment from school to improve student's cognitive readiness. National examination indicators were different between both of majors. Consequently, each student from both majors tried to get the best results in English national examination. In other words, the difference of national examination system did not influence if it was given to natural or social science students. It is because both national examination and the majors are different. Based on the first hypothesis analysis, there are significant influences of national examination system for students' cognitive readiness and anxiety in facing English national examination. The next step used Table Test of Between-Subject Effects of two-ways Manova analysis. The result states that significant value of students' cognitive readiness is 0.590. It was more than 0.05. It means that the national examination systems have no influence on students' cognitive readiness. It is because of all students who both types of national examination systems should prepare their cognitive readiness in facing national examination using the same indicators. The schools with both national examination systems provided more exercises and students understood about the subjects in national examination. This analysis is also supported by Retnawati (2015, p.135) that in general CBT and PBT are relatively similar in terms of the measurement of the ability of TOEP. In addition, these result are also consistent with the result of Piaw research (Piaw, 2012, p. 655) that the scores of pre-test and posttest on biology lesson are consistent between Paper-Based Testing and Computer-Based Testing. Furthermore, the results of Table Test of Between-Subject Effects are used to determine whether national examination systems influence students' anxiety in facing national examination. The analysis shows 0.00 as significant value which is less than 0.05 so that H0 is rejected. It means that there are significant influences of national examination systems for students' anxiety in facing national examination. Students' anxiety will increase when students should face new kind of national test examination systems such as CBT. The new thing for students will give effects to their anxiety. Some students who are already accustomed to using computers will have lower anxiety in facing CBT national examination than those who are not familiar with computers in daily life. Besides, the anxiety level of students who did the PBT national examination system also increase. It is because of fear or worry about the results of national examination. It is in line with Wolfolk, Anita, and Loraine's theory (1984, p.298) that students who are not able to complete a task is often filled with anxiety. This finding supports Taylor's theory (Leonard & Supardi U.S., 2010, p. 342) that anxiety is the effect of the inability of the individual in dealing with problems. However, anxiety of the students can be minimalized with the roles of the teacher. Dobson (2012, p.5) states that if the teacher is able to recognize the signs of students' anxiety, it will assist students in overcoming their anxiety. Teachers should understand different methods in overcoming students' anxiety. The next analysis was independent sample t-test. It was done if national examination influences students' anxiety. This analysis aims to determine the differences of anxiety average score between students facing CBT and PBT national examination. Based on the analysis, the tvalue obtained is 4.47. It is more than ttable = 1.963. It means that the average score of the students' anxiety in facing CBT national examination is not equal to the average score of the students' anxiety in facing PBT national examination. Based on students' anxiety average score, it proves that the average score of students who did CBT national examination is higher (85.371) than another (80.833). It means that the anxiety level of students who did the CBT national examination is higher and significantly different compared to another. The next data analysis was to know the correlation between students' cognitive readiness and anxiety in facing national examination. Based on the analysis, the significance value is 0.016. It is less than 0.05, which means that there is a significant relation between students' cognitive readiness and anxiety. The value correlation is -0.94. It means that there is a very strong relation between the students' cognitive readiness and anxiety in facing national examination and viceversa. If the students' anxiety level is high then the students get low cognitive readiness, and vice-versa. Agustiar & Asmi (2010, p. 13) clarify that the students who have high anxiety also tend to worry, anxious, and difficult to concentrate when they face a threatening situation as well as the national examination. Students who have low anxiety tend to be aware of situations such as national examination so that they can anticipate the situation. Dobson (2012, p.26) states that students who have more time preparing the examination will have lower anxiety than others. The last data analysis was to Tarling Vol. 1 No. 2 make an equalization data of students' anxiety in facing national examination systems. It was done because the measurement of students' anxiety was done by different instruments although the indicators were the same. The result aims to produce a score that can replace each other if only one of anxiety test instruments national examination. Graph 1 shows that at a certain percentile, anxiety instruments in facing CBT national examination give students higher anxiety scores than anxiety instruments in facing PBT national examination. The next step was converting scores of students' anxiety in facing English PBT national examination to students' anxiety score in facing CBT national examination. Converted score is range scores that exist in the both data of students' anxiety in facing CBT and PBT national examination systems. D. CONCLUSIONS Based on the results of the discussion, it can be concluded that there are significant influences of CBT and PBT CBT and PBT national examination system for students' cognitive readiness and anxiety in facing English national 80 60 40 20 examination. However, the national examination system has no effect for students' cognitive readiness. It only influences students' anxiety in English national examination. In addition, the average scores of the students' anxiety in facing CBT national examination systems are different from those who do PBT national examination system. The majors taken have no influence for students' cognitive readiness and anxiety in facing English national examination. There is no interaction between the national examination system and the majors. Based on these results, further research is expected to expand the coverage area and add a dependent variable in order to get an overview of the results of a broader research and include more aspect.
#nsolve_8solutions.py #number place problem of 8 solutions. Test for search all. #program generated . # #T.Hayashi v=[[8,9,0,0,0,1,0,0,6],[1,6,0,9,0,0,0,0,0],[4,0,0,6,2,0,0,9,0], [0,7,0,0,0,0,6,0,0],[9,0,0,0,0,0,0,3,0],[0,0,1,0,0,0,9,0,7], [5,0,6,7,0,0,0,0,9],[0,0,0,3,5,0,4,0,0],[0,4,0,0,9,0,0,0,2]]
// Group returns group with given name func (router *Router) Group(name string) (cand *Group) { cand = &Group{ Name: name, RouteSorter: router.DefaultRouteSorter, Router: router, Data: make(map[string]interface{}), } i := sort.Search(len(router.Groups), func(i int) bool { return router.GroupSorter(router.Groups[i], cand) }) if i == len(router.Groups) || router.Groups[i].Name != name { router.Groups = append(router.Groups[:i], append([]*Group{cand}, router.Groups[i:]...)...) } else { cand = router.Groups[i] } return }
/// Prints the contents of the QByteArray if it contains UTF-8, nothing otherwise fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { unsafe { let c_ptr = cpp!([self as "const QByteArray*"] -> *const c_char as "const char*" { return self->constData(); }); f.write_str( std::ffi::CStr::from_ptr(c_ptr) .to_str() .map_err(|_| Default::default())?, ) } }
/** * Grid factory MBean data container. * Contains necessary data for selected MBeanServer. */ private static class GridMBeanServerData { /** Set of grid names for selected MBeanServer. */ private Collection<String> gridNames = new HashSet<>(); /** */ private ObjectName mbean; /** Count of grid instances. */ private int cnt; /** * Create data container. * * @param mbean Object name of MBean. */ GridMBeanServerData(ObjectName mbean) { assert mbean != null; this.mbean = mbean; } /** * Add grid name. * * @param gridName Grid name. */ public void addGrid(String gridName) { gridNames.add(gridName); } /** * Remove grid name. * * @param gridName Grid name. */ public void removeGrid(String gridName) { gridNames.remove(gridName); } /** * Returns {@code true} if data contains the specified * grid name. * * @param gridName Grid name. * @return {@code true} if data contains the specified grid name. */ public boolean containsGrid(String gridName) { return gridNames.contains(gridName); } /** * Gets name used in MBean server. * * @return Object name of MBean. */ public ObjectName getMbean() { return mbean; } /** * Gets number of grid instances working with MBeanServer. * * @return Number of grid instances. */ public int getCounter() { return cnt; } /** * Sets number of grid instances working with MBeanServer. * * @param cnt Number of grid instances. */ public void setCounter(int cnt) { this.cnt = cnt; } }
/** * The ratio of current size, calculated only when necessary. * * @return the ratio */ public double ratio() { if (ratio == 0 && width != 0) { ratio = (double) height / width; } return ratio; }
/// Asserts that the response body is bytes and it equals to `bytes`. pub async fn assert_bytes(self, bytes: impl AsRef<[u8]>) { assert_eq!( self.0.into_body().into_vec().await.expect("expect body"), bytes.as_ref() ); }
def make_map(): map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.connect('error/:action/:id', controller='error') map.connect(':fileoruri/wms', controller='csmlwms') map.connect('wcsroute', ':fileoruri/wcs', controller='csmlwcs') map.connect(':fileoruri/wfs', controller='csmlwfs') map.connect('filestore/:file', controller='fetch', action='fetchFile') map.connect(':fileoruri/demo', controller='demo') map.connect('', controller='catalogue') map.connect(':controller/:action/:id') map.connect('*url', controller='template', action='view') return map
<filename>script/ecdsa_checker.py import ecdsa from hashlib import sha256 user_id = input("input user_id: ") # user_id = '936da01f9abd4d9d80c702af85c822a8' timestamp = input("input timestamp: ") # timestamp = '1591208843' risk_level = input("input risk_level ('00' or '01'): ") # risk_level = '00' b_user_id = bytes.fromhex(user_id) b_timestamp = timestamp.encode() b_risk_level = bytes.fromhex(risk_level) message = b_user_id + b_timestamp + b_risk_level signature = input("input signature: ") # signature = '6586320e7785bfd780b15e15b23cbd09a153147c6390052ca34d49a5a17e128b423e16b866874d86ead8ecf0d1bebc6ef193e3b20d6f14070b5a295fce35555e' public_key = input("public key: ") # public_key = '3dffed5a98360323042f14484f887999cf7f86971d7bc6b8e1d670e56377f3c91d42eb4ff3563d7bb8b8d4524b7867788fe989cc0761dbed4a068f9fb4e79833' vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key), curve=ecdsa.NIST256p, hashfunc=sha256) try: result = vk.verify(bytes.fromhex(signature), message) if result: print("[+] VERIFICATION SUCCES!!") except ecdsa.keys.BadSignatureError as e: print("[-] VERIFICATION FAILED!!")
<filename>RAPIDpy/postprocess/generate_return_periods.py # -*- coding: utf-8 -*- """ generate_return_periods.py RAPIDpy Created by: <NAME> and <NAME>, 2015-2016. License: BSD 3-Clause """ from datetime import datetime import multiprocessing from netCDF4 import Dataset import numpy as np # local from ..dataset import RAPIDDataset from ..helper_functions import add_latlon_metadata, log from ..utilities import partition def generate_single_return_period(args): """ This function calculates a single return period for a single reach """ qout_file, return_period_file, rivid_index_list, step, num_years, \ method, mp_lock = args skewvals = [-3.0, -2.8, -2.6, -2.4, -2.2, -2.0, -1.8, -1.6, -1.4, -1.2, -1.0, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0] kfac2 = [0.396, 0.384, 0.368, 0.351, 0.33, 0.307, 0.282, 0.254, 0.225, 0.195, 0.164, 0.132, 0.099, 0.066, 0.033, 0, -0.033, -0.066, -0.099, -0.132, -0.164, -0.195, -0.225, -0.254, -0.282, -0.307, -0.33, -0.351, -0.368, -0.384, -0.396] kfac10 = [0.66, 0.702, 0.747, 0.795, 0.844, 0.895, 0.945, 0.994, 1.041, 1.086, 1.128, 1.166, 1.2, 1.231, 1.258, 1.282, 1.301, 1.317, 1.328, 1.336, 1.34, 1.34, 1.337, 1.329, 1.318, 1.302, 1.284, 1.262, 1.238, 1.21, 1.18] kfac25 = [.666, .712, .764, .823, .888, .959, 1.035, 1.116, 1.198, 1.282, 1.366, 1.448, 1.528, 1.606, 1.680, 1.751, 1.818, 1.880, 1.939, 1.993, 2.043, 2.087, 2.128, 2.163, 2.193, 2.219, 2.240, 2.256, 2.267, 2.275, 2.278] kfac50 = [0.666, 0.714, 0.768, 0.83, 0.9, 0.98, 1.069, 1.166, 1.27, 1.379, 1.492, 1.606, 1.72, 1.834, 1.945, 2.054, 2.159, 2.261, 2.359, 2.453, 2.542, 2.626, 2.706, 2.78, 2.848, 2.912, 2.97, 3.023, 3.071, 3.114, 3.152] kfac100 = [0.667, 0.714, 0.769, 0.832, 0.905, 0.99, 1.087, 1.197, 1.318, 1.499, 1.588, 1.733, 1.88, 2.029, 2.178, 2.326, 2.472, 2.615, 2.755, 2.891, 3.022, 3.149, 3.271, 3.388, 3.499, 3.605, 3.705, 3.8, 3.889, 3.973, 4.051] with RAPIDDataset(qout_file) as qout_nc_file: # get index of return period data if method == 'weibull': rp_index_20 = int((num_years + 1)/20.0) rp_index_10 = int((num_years + 1)/10.0) rp_index_2 = int((num_years + 1)/2.0) if method == 'weibull': return_20_array = np.zeros(len(rivid_index_list)) elif method == 'gumble': return_100_array = np.zeros(len(rivid_index_list)) return_50_array = np.zeros(len(rivid_index_list)) return_20_array = np.zeros(len(rivid_index_list)) elif method == 'log_pearson': return_100_array = np.zeros(len(rivid_index_list)) return_50_array = np.zeros(len(rivid_index_list)) return_25_array = np.zeros(len(rivid_index_list)) return_10_array = np.zeros(len(rivid_index_list)) return_2_array = np.zeros(len(rivid_index_list)) max_flow_array = np.zeros(len(rivid_index_list)) # iterate through rivids to generate return periods for iter_idx, rivid_index in enumerate(rivid_index_list): filtered_flow_data = qout_nc_file.get_qout_index( rivid_index, pd_filter="{0}D".format(step), filter_mode="max") sorted_flow_data = np.sort(filtered_flow_data)[:num_years:-1] max_flow = sorted_flow_data[0] if max_flow < 0.01: log("Return period data < 0.01 generated for rivid {0}" .format(qout_nc_file.qout_nc.variables[ qout_nc_file.river_id_dimension][rivid_index]), "WARNING") max_flow_array[iter_idx] = max_flow if method == 'weibull': return_20_array[iter_idx] = sorted_flow_data[rp_index_20] return_10_array[iter_idx] = sorted_flow_data[rp_index_10] return_2_array[iter_idx] = sorted_flow_data[rp_index_2] elif method == 'gumble': mean_flow = np.mean(filtered_flow_data) stddev = np.std(filtered_flow_data) return_100_array[iter_idx] = mean_flow + 3.14*stddev return_50_array[iter_idx] = mean_flow + 2.59*stddev return_20_array[iter_idx] = mean_flow + 1.87*stddev return_10_array[iter_idx] = mean_flow + 1.3*stddev return_2_array[iter_idx] = mean_flow - .164*stddev elif method == 'log_pearson': log_flow = np.log10(filtered_flow_data[filtered_flow_data > 0]) if len(log_flow) <= 0: continue mean_log_flow = np.mean(log_flow) std_log_flow = np.std(log_flow) log_flow_array = np.array(log_flow) skew = (num_years * (np.sum( np.power((log_flow_array - mean_log_flow), 3)))) / \ ((num_years - 1) * (num_years - 2) * std_log_flow ** 3) k2 = np.interp(skew, skewvals, kfac2) k10 = np.interp(skew, skewvals, kfac10) k25 = np.interp(skew, skewvals, kfac25) k50 = np.interp(skew, skewvals, kfac50) k100 = np.interp(skew, skewvals, kfac100) return_100_array[iter_idx] = \ np.power(10, (mean_log_flow + k100*std_log_flow)) return_50_array[iter_idx] = \ np.power(10, (mean_log_flow + k50*std_log_flow)) return_25_array[iter_idx] = \ np.power(10, (mean_log_flow + k25*std_log_flow)) return_10_array[iter_idx] = \ np.power(10, (mean_log_flow + k10*std_log_flow)) return_2_array[iter_idx] = \ np.power(10, (mean_log_flow + k2*std_log_flow)) mp_lock.acquire() return_period_nc = Dataset(return_period_file, 'a') return_period_nc.variables['max_flow'][rivid_index_list] = \ max_flow_array if method == 'weibull': return_period_nc.variables['return_period_20'][ rivid_index_list] = return_20_array elif method in 'gumble': return_period_nc.variables['return_period_100'][ rivid_index_list] = return_100_array return_period_nc.variables['return_period_50'][ rivid_index_list] = return_50_array return_period_nc.variables['return_period_20'][ rivid_index_list] = return_20_array elif method == 'log_pearson': return_period_nc.variables['return_period_100'][ rivid_index_list] = return_100_array return_period_nc.variables['return_period_50'][ rivid_index_list] = return_50_array return_period_nc.variables['return_period_25'][ rivid_index_list] = return_25_array return_period_nc.variables['return_period_10'][ rivid_index_list] = return_10_array return_period_nc.variables['return_period_2'][ rivid_index_list] = return_2_array return_period_nc.close() mp_lock.release() def generate_return_periods(qout_file, return_period_file, num_cpus=multiprocessing.cpu_count(), storm_duration_days=7, method='weibull'): """ Generate return period from RAPID Qout file """ # get ERA Interim Data Analyzed with RAPIDDataset(qout_file) as qout_nc_file: print("Setting up Return Periods File ...") return_period_nc = Dataset(return_period_file, 'w') return_period_nc.createDimension('rivid', qout_nc_file.size_river_id) timeSeries_var = \ return_period_nc.createVariable('rivid', 'i4', ('rivid',)) timeSeries_var.long_name = ( 'unique identifier for each river reach') max_flow_var = \ return_period_nc.createVariable('max_flow', 'f8', ('rivid',)) max_flow_var.long_name = 'maximum streamflow' max_flow_var.units = 'm3/s' if method == 'weibull': return_period_20_var = \ return_period_nc.createVariable('return_period_20', 'f8', ('rivid',)) return_period_20_var.long_name = '20 year return period flow' return_period_20_var.units = 'm3/s' if method == 'gumble': return_period_100_var = \ return_period_nc.createVariable('return_period_100', 'f8', ('rivid',)) return_period_100_var.long_name = '100 year return period flow' return_period_100_var.units = 'm3/s' return_period_50_var = \ return_period_nc.createVariable('return_period_50', 'f8', ('rivid',)) return_period_50_var.long_name = '50 year return period flow' return_period_50_var.units = 'm3/s' return_period_20_var = \ return_period_nc.createVariable('return_period_20', 'f8', ('rivid',)) return_period_20_var.long_name = '20 year return period flow' return_period_20_var.units = 'm3/s' if method == 'log_pearson': return_period_100_var = \ return_period_nc.createVariable('return_period_100', 'f8', ('rivid',)) return_period_100_var.long_name = '100 year return period flow' return_period_100_var.units = 'm3/s' return_period_50_var = \ return_period_nc.createVariable('return_period_50', 'f8', ('rivid',)) return_period_50_var.long_name = '50 year return period flow' return_period_50_var.units = 'm3/s' return_period_25_var = \ return_period_nc.createVariable('return_period_25', 'f8', ('rivid',)) return_period_25_var.long_name = '25 year return period flow' return_period_25_var.units = 'm3/s' return_period_10_var = \ return_period_nc.createVariable('return_period_10', 'f8', ('rivid',)) return_period_10_var.long_name = '10 year return period flow' return_period_10_var.units = 'm3/s' return_period_2_var = \ return_period_nc.createVariable('return_period_2', 'f8', ('rivid',)) return_period_2_var.long_name = '2 year return period flow' return_period_2_var.units = 'm3/s' lat_var = return_period_nc.createVariable('lat', 'f8', ('rivid',), fill_value=-9999.0) lon_var = return_period_nc.createVariable('lon', 'f8', ('rivid',), fill_value=-9999.0) add_latlon_metadata(lat_var, lon_var) return_period_nc.variables['lat'][:] = \ qout_nc_file.qout_nc.variables['lat'][:] return_period_nc.variables['lon'][:] = \ qout_nc_file.qout_nc.variables['lon'][:] river_id_list = qout_nc_file.get_river_id_array() return_period_nc.variables['rivid'][:] = river_id_list return_period_nc.return_period_method = method return_period_nc.close() time_array = qout_nc_file.get_time_array() log("Extracting Data and Generating Return Periods ...") num_years = int((datetime.utcfromtimestamp(time_array[-1]) - datetime.utcfromtimestamp(time_array[0])).days/365.2425) time_steps_per_day = (24 * 3600) / float( (datetime.utcfromtimestamp(time_array[1]) - datetime.utcfromtimestamp(time_array[0])).total_seconds()) step = max(1, int(time_steps_per_day * storm_duration_days)) # generate multiprocessing jobs # pylint: disable=no-member mp_lock = multiprocessing.Manager().Lock() job_combinations = [] partition_index_list = partition(river_id_list, num_cpus*2)[1] for sub_partition_index_list in partition_index_list: # pylint: disable=len-as-condition if len(sub_partition_index_list) > 0: job_combinations.append((qout_file, return_period_file, sub_partition_index_list, step, num_years, method, mp_lock )) pool = multiprocessing.Pool(num_cpus) pool.map(generate_single_return_period, job_combinations) pool.close() pool.join()
Though it’s only been 81 years since the death of apostle and member of the First Presidency (1925-1934) Anthony W. Ivins, much of what he taught has sadly not been heard from the pulpit or appeared in Church magazines in a very long time. That’s just a shame, so here are 7 essential Anthony W. Ivins quotes. 1. “We know that the Hill Ramah and the Hill Cumorah are one and the same hill. However, identification of the River Sidon with the River of Laman must await further revelation from the Lord.” (Conference Report, April, 1926). 2. “We have little evidence of existence of other beings in the universe. Yet it is my faith that other children of our Father live on other planets. And these beings are much taller than us, by 3 or 4 feet at least. And the much stronger force of gravity on these planets make them impossibly strong. And when the Savior visited them long ago, he told them how impressed he was with their physical prowess. This is my testimony.” (Conference Report, April 1911). 3. “There are some who say that eternal progression most broadly means progressing or advancing from one stage or form of life to another, forever, without end. That is exactly what it means.” (Conference Report, October 1919). 4. “Brethren, you must watch yourselves at all times. The devil never sleeps and is constantly seeking your undoing. Quietly yet assertively he whispers, “This giggle water is the bees knees. You can’t get zozzled with just one Jorum of skee.” Or, “That Sheba is a real Oliver Twist, isn’t she? Just one dance won’t hurt.” Or, “That one’s a real bearcat and no cancelled stamp. The fellas say she’s no icy mitt.” Phonus balonus! Nothing is Jake in the devil’s kingdom. Don’t take any wooden nickels, brethren. You are men of courage and valor, more hard boiled than the average fish.” (Conference Report, October 1921). 5. “There are mothers, but then there are angel mothers. But even beyond that there are archangel mothers, the highest, holiest mothers of all. Archangel mothers are rare and precious. Where mothers cook a hearty meal for their children, angel mothers do so using only the best ingredients and superb culinary skills. Archangel mothers, though, can spontaneously generate the perfect meal out of the very elements of the earth. Mothers will sacrifice their time and energy for their children. Angel mothers will give up all sense of self completely for their little ones, even unto their very lives. But Archangel mothers will demand–and receive–the Keys of Death and Salvation from God Himself and their children will never know discomfort, illness, or death. Sisters, ask yourself–‘What kind of mother am I?’ ” (Conference Report, April 1932). 6. “When you pray, do not use vain repetition. But remember, not all repetition is vain. The Lord cannot hear enough how wonderful are his works and mighty is his power. Because they are and it is. That is not vanity. Those are just facts.” (Conference Report, October 1927). 7. “Though the world has been shaken by the tragic economic events of 2 years ago, remember that gratitude is the greatest commodity of all. And gratitude for gratitude is therefore the highest virtue. Nevertheless, the truly grateful do not stop there. No, those who have gratitude for gratitude aspire to have gratitude for gratitude for gratitude, ad infinitum. The truly grateful–and, therefore, the truly righteous–are gratuitous in their gratitude and grateful in their gratuitousness, until in their infinite gratefulness they cease to be grateful for anything and become that for which gratitude itself is grateful.” (Conference Report, October 1931). Advertisements
<gh_stars>0 /** * brief Nordic nRF52840-specific definition of the "radio" bsp module. * * Authors: <NAME> (1, <EMAIL>) and <NAME> (2, <EMAIL>) * Company: (1) Institut fuer Mikroelektronik- und Mechatronik-Systeme gemeinnuetzige GmbH (IMMS GmbH) * (2) Faculty of Electronics and Computing, Zagreb, Croatia * Date: June 2018 */ #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdbool.h> #include "sdk/components/boards/boards.h" #include "sdk/components/drivers_nrf/radio_config/radio_config.h" #include "sdk/modules/nrfx/drivers/include/nrfx_systick.h" #include "sdk/modules/nrfx/mdk/nrf52840.h" #include "sdk/integration/nrfx/legacy/nrf_drv_clock.h" #include "nrf_delay.h" #include "app_config.h" #include "leds.h" #include "radio.h" #include "board.h" #include "board_info.h" #include "debugpins.h" #include "sctimer.h" //=========================== defines ========================================= #define RADIO_POWER_POWER_POS 0 #define STATE_DISABLED 0 #define STATE_RXRU 1 #define STATE_RXIDLE 2 #define STATE_RX 3 #define STATE_RXDISABLE 4 #define STATE_TXTU 9 #define STATE_TXIDLE 10 #define STATE_TX 11 #define STATE_TXDIABLE 12 /* For calculating frequency */ #define FREQUENCY_OFFSET 10 #define FREQUENCY_STEP 5 #define SFD_OCTET (0xA7) ///< start of frame delimiter of IEEE 802.15.4 #define MAX_PACKET_SIZE (127) ///< maximal size of radio packet (one more byte at the beginning needed to store the length) #define CRC_POLYNOMIAL (0x11021) ///< polynomial used for CRC calculation in 802.15.4 frames (x^16 + x^12 + x^5 + 1) #define WAIT_FOR_RADIO_DISABLE (0) ///< whether the driver shall wait until the radio is disabled upon calling radio_rfOff() #define WAIT_FOR_RADIO_ENABLE (1) ///< whether the driver shall wait until the radio is enabled upon calling radio_txEnable() or radio_rxEnable() //=========================== variables ======================================= typedef struct { radio_capture_cbt startFrame_cb; radio_capture_cbt endFrame_cb; radio_state_t state; uint8_t payload[1+MAX_PACKET_SIZE] __attribute__ ((aligned)); bool hfc_started; // volatile bool event_ready; } radio_vars_t; static radio_vars_t radio_vars; //=========================== prototypes ====================================== static uint32_t swap_bits(uint32_t inp); static uint32_t bytewise_bitswap(uint32_t inp); //=========================== public ========================================== void radio_init(void) { // clear internal variables memset(&radio_vars, 0, sizeof(radio_vars)); // set radio configuration parameters NRF_RADIO->TXPOWER = (RADIO_TXPOWER_TXPOWER_Pos4dBm << RADIO_TXPOWER_TXPOWER_Pos); // set radio mode to IEEE 802.15.4 NRF_RADIO->MODE = (RADIO_MODE_MODE_Ieee802154_250Kbit << RADIO_MODE_MODE_Pos); // set config field length to 8 NRF_RADIO->PCNF0 &= (~RADIO_PCNF0_LFLEN_Msk); NRF_RADIO->PCNF0 |= (((uint32_t)8) << RADIO_PCNF0_LFLEN_Pos); // set 32-bit zero preamble NRF_RADIO->PCNF0 &= (~RADIO_PCNF0_PLEN_Msk); NRF_RADIO->PCNF0 |= ((uint32_t) RADIO_PCNF0_PLEN_32bitZero << RADIO_PCNF0_PLEN_Pos); // set max packet size NRF_RADIO->PCNF1 &= (~RADIO_PCNF1_MAXLEN_Msk); NRF_RADIO->PCNF1 |= ((uint32_t) MAX_PACKET_SIZE << RADIO_PCNF1_MAXLEN_Pos); // set start of frame delimiter NRF_RADIO->SFD= (SFD_OCTET << RADIO_SFD_SFD_Pos) & RADIO_SFD_SFD_Msk; // set CRC to be included NRF_RADIO->PCNF0 &= (~RADIO_PCNF0_CRCINC_Msk); NRF_RADIO->PCNF0 |= ((uint32_t) RADIO_PCNF0_CRCINC_Include << RADIO_PCNF0_CRCINC_Pos); // set CRC length NRF_RADIO->CRCCNF &= (~RADIO_CRCCNF_LEN_Msk); NRF_RADIO->CRCCNF |= ((uint32_t) LENGTH_CRC << RADIO_CRCCNF_LEN_Pos); // configure CRC (CRC calculation as per 802.15.4 standard. Starting at first byte after length field.) NRF_RADIO->CRCCNF &= (~RADIO_CRCCNF_SKIPADDR_Msk); NRF_RADIO->CRCCNF |= ((uint32_t) RADIO_CRCCNF_SKIPADDR_Ieee802154 << RADIO_CRCCNF_SKIPADDR_Pos); // set CRC polynomial NRF_RADIO->CRCPOLY = (CRC_POLYNOMIAL << RADIO_CRCPOLY_CRCPOLY_Pos); NRF_RADIO->CRCINIT = 0x0UL; // set payload pointer NRF_RADIO->PACKETPTR = (uint32_t)(radio_vars.payload); // set up interrupts // disable radio interrupt NVIC_DisableIRQ(RADIO_IRQn); NRF_RADIO->INTENSET = // RADIO_INTENSET_READY_Enabled << RADIO_INTENSET_READY_Pos | RADIO_INTENSET_ADDRESS_Enabled << RADIO_INTENSET_ADDRESS_Pos | RADIO_INTENSET_END_Enabled << RADIO_INTENSET_END_Pos; NVIC_SetPriority(RADIO_IRQn, NRFX_RADIO_CONFIG_IRQ_PRIORITY); NVIC_ClearPendingIRQ(RADIO_IRQn); NVIC_EnableIRQ(RADIO_IRQn); } void radio_setStartFrameCb(radio_capture_cbt cb) { radio_vars.startFrame_cb = cb; } void radio_setEndFrameCb(radio_capture_cbt cb) { radio_vars.endFrame_cb = cb; } void radio_reset(void) { // reset is implemented by power off and power radio NRF_RADIO->POWER = ((uint32_t)(0)) << RADIO_POWER_POWER_POS; NRF_RADIO->POWER = ((uint32_t)(1)) << RADIO_POWER_POWER_POS; radio_vars.state = RADIOSTATE_STOPPED; } void radio_setFrequency(uint8_t frequency, radio_freq_t tx_or_rx) { NRF_RADIO->FREQUENCY = FREQUENCY_STEP*(frequency-FREQUENCY_OFFSET); radio_vars.state = RADIOSTATE_FREQUENCY_SET; } int8_t radio_getFrequencyOffset(void){ return 0; } void radio_rfOn(void) { // power on radio NRF_RADIO->POWER = ((uint32_t)(1)) << 0; radio_vars.state = RADIOSTATE_STOPPED; } void radio_rfOff(void) { radio_vars.state = RADIOSTATE_TURNING_OFF; NRF_RADIO->EVENTS_DISABLED = 0; // stop radio NRF_RADIO->TASKS_DISABLE = (uint32_t)(1); while(NRF_RADIO->EVENTS_DISABLED==0); leds_radio_off(); debugpins_radio_clr(); radio_vars.state = RADIOSTATE_RFOFF; } void radio_loadPacket(uint8_t* packet, uint16_t len) { radio_vars.state = RADIOSTATE_LOADING_PACKET; ///< note: 1st byte should be the payload size (for Nordic), and /// the two last bytes are used by the MAC layer for CRC if ((len > 0) && (len <= MAX_PACKET_SIZE)) { radio_vars.payload[0]= len; memcpy(&radio_vars.payload[1], packet, len); } // (re)set payload pointer NRF_RADIO->PACKETPTR = (uint32_t)(radio_vars.payload); radio_vars.state = RADIOSTATE_PACKET_LOADED; } void radio_txEnable(void) { radio_vars.state = RADIOSTATE_ENABLING_TX; NRF_RADIO->EVENTS_READY = (uint32_t)0; NRF_RADIO->TASKS_TXEN = (uint32_t)1; while(NRF_RADIO->EVENTS_READY==0); // wiggle debug pin debugpins_radio_set(); leds_radio_on(); radio_vars.state = RADIOSTATE_TX_ENABLED; } void radio_txNow(void) { NRF_RADIO->TASKS_START = (uint32_t)1; radio_vars.state = RADIOSTATE_TRANSMITTING; } void radio_rxEnable(void) { radio_vars.state = RADIOSTATE_ENABLING_RX; if (NRF_RADIO->STATE != STATE_RX) { // turn off radio first radio_rfOff(); NRF_RADIO->EVENTS_READY = (uint32_t)0; NRF_RADIO->TASKS_RXEN = (uint32_t)1; while(NRF_RADIO->EVENTS_READY==0); } } void radio_rxNow(void) { NRF_RADIO->TASKS_START = (uint32_t)1; debugpins_radio_set(); leds_radio_on(); radio_vars.state = RADIOSTATE_LISTENING; } void radio_getReceivedFrame(uint8_t* pBufRead, uint8_t* pLenRead, uint8_t maxBufLen, int8_t* pRssi, uint8_t* pLqi, bool* pCrc) { // check for length parameter; if too long, payload won't fit into memory uint8_t len; len = radio_vars.payload[0]; if (len == 0) { return; } if (len > MAX_PACKET_SIZE) { len = MAX_PACKET_SIZE; } if (len > maxBufLen) { len = maxBufLen; } // copy payload memcpy(pBufRead, &radio_vars.payload[1], len); // store other parameters *pLenRead = len; *pLqi = radio_vars.payload[radio_vars.payload[0]-1]; // For the RSSI calculation, see // // - http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.nrf52840.ps/radio.html?cp=2_0_0_5_19_11_6#ieee802154_rx and // - https://www.metageek.com/training/resources/understanding-rssi.html // // Our RSSI will be in the range -91 dB (worst) to 0 dB (best) *pRssi = (*pLqi > 91)?(0):(((int8_t) *pLqi) - 91); *pCrc = (NRF_RADIO->CRCSTATUS == 1U); } //=========================== private ========================================= static uint32_t swap_bits(uint32_t inp) { uint32_t i; uint32_t retval = 0; inp = (inp & 0x000000FFUL); for (i = 0; i < 8; i++) { retval |= ((inp >> i) & 0x01) << (7 - i); } return retval; } static uint32_t bytewise_bitswap(uint32_t inp) { return (swap_bits(inp >> 24) << 24) | (swap_bits(inp >> 16) << 16) | (swap_bits(inp >> 8) << 8) | (swap_bits(inp)); } //=========================== callbacks ======================================= //=========================== interrupt handlers ============================== void RADIO_IRQHandler(void) { if (NRF_RADIO->EVENTS_ADDRESS) { NRF_RADIO->EVENTS_ADDRESS = 0; if (radio_vars.startFrame_cb) { radio_vars.startFrame_cb(sctimer_readCounter()); } } if (NRF_RADIO->EVENTS_END) { NRF_RADIO->EVENTS_END = 0; if (radio_vars.endFrame_cb) { radio_vars.endFrame_cb(sctimer_readCounter()); } } }
The Effect of Valproic Acid on Olanzapine Serum Concentration: A Study Including 2791 Patients Treated With Olanzapine Tablets or Long-Acting Injections. BACKGROUND The combination of olanzapine and valproic acid (VPA) is regularly prescribed in the treatment of bipolar or schizoaffective disorders. The VPA has been shown to reduce olanzapine concentration, but the mechanism behind this interaction remains unknown. We aimed to investigate the effect of VPA on olanzapine concentration during oral versus long-acting injectable (LAI) formulation in a real-life setting. METHODS From a therapeutic drug monitoring service, prescribed doses and serum concentrations from 2791 olanzapine-treated patients (9433 measurements) were included. RESULTS The number of patients on olanzapine-LAI treatment was 328, whereas 2463 were using oral olanzapine. The frequency of patients comedicated with VPA was 9.4% for olanzapine tablets and 5.8% for olanzapine-LAI. The VPA had no effect on olanzapine dose-adjusted concentrations in LAI users (1.6 vs 1.7 / ; P = 0.38), whereas in the oral group the dose-adjusted olanzapine concentration was lower in VPA users (2.2 vs 2.7 / ; P < 0.001). For smokers in the oral olanzapine group using VPA, 8.7% of the measurements were in the subtherapeutic range (<10 ng/mL) compared with 6.0% in nonusers (P = 0.003). IMPLICATIONS These findings show that the VPA-olanzapine interaction involves a presystemic mechanism and is therefore restricted to oral olanzapine treatment. For oral treatment of olanzapine, comedication with VPA implies a risk of insufficient effect, which may be of clinical relevance in smokers in particular. Thus, it is important to be aware of the interaction potential with VPA during oral olanzapine use, whereas for LAI-treated patients fewer precautions are required from a pharmacokinetic point of view.
// Copyright 2004-present Facebook. All rights reserved. #pragma once #include "thrift/lib/cpp/async/TAsyncSocket.h" #include <stdint.h> #include <chrono> #include <iosfwd> namespace facebook { namespace json { class JsonObject; } namespace proxygen { class TcpEventsConfig { public: static const bool DEFAULT_ENABLED{false}; static const double DEFAULT_SAMPLE_RATE; static const uint32_t KERNEL_LIMIT_ACK_TRACKED{16}; static const uint32_t DEFAULT_ACK_TRACKED{4}; static const uint64_t DEFAULT_ACK_TIMEOUT_MS{10000}; static const char * const ENTITY; static TcpEventsConfig parse(const facebook::json::JsonObject& configObj); friend std::ostream& operator<<(std::ostream& os, const TcpEventsConfig& cfg); TcpEventsConfig(); virtual ~TcpEventsConfig() {} std::chrono::milliseconds getTimeout() const { return ackTimeout_; } uint32_t getMaxAckTracked() const { return maxAckTracked_; } void setMaxAckTracked(uint32_t n); bool shouldSample() const; void updateSocketOptions( apache::thrift::async::TAsyncSocket::OptionMap& opts); private: bool enabled_{DEFAULT_ENABLED}; double sampleRate_{DEFAULT_SAMPLE_RATE}; uint32_t samplingKey_{0}; uint32_t maxAckTracked_{DEFAULT_ACK_TRACKED}; std::chrono::milliseconds ackTimeout_{DEFAULT_ACK_TIMEOUT_MS}; }; }}
/** * Creates a new {@link UiElementNode} from the given {@link ElementDescriptor} * and appends it to the end of the element children list. * * @param descriptor The {@link ElementDescriptor} that knows how to create the UI node. * @return The new UI node that has been appended */ public UiElementNode appendNewUiChild(ElementDescriptor descriptor) { UiElementNode uiNode; uiNode = descriptor.createUiNode(); mUiChildren.add(uiNode); uiNode.setUiParent(this); uiNode.invokeUiUpdateListeners(UiUpdateState.CREATED); return uiNode; }
def detect_loop_cut(self, conn_components, this_nx_graph, strongly_connected_components): all_start_activities = self.start_activities all_end_activities = self.end_activities start_activities = all_start_activities end_activities = list(set(all_end_activities) - set(all_start_activities)) start_act_that_are_also_end = list(set(all_end_activities) - set(end_activities)) do_part = [] redo_part = [] dangerous_redo_part = [] exit_part = [] for sa in start_activities: do_part.append(sa) for ea in end_activities: exit_part.append(ea) for act in self.activities: if act not in start_activities and act not in end_activities: input_connected_activities = get_all_activities_connected_as_input_to_activity(self.dfg, act) output_connected_activities = get_all_activities_connected_as_output_to_activity(self.dfg, act) if set(output_connected_activities).issubset(start_activities) and set(start_activities).issubset( output_connected_activities): if len(input_connected_activities.intersection(exit_part)) > 0: dangerous_redo_part.append(act) redo_part.append(act) else: do_part.append(act) if len(do_part) > 0 and (len(redo_part) > 0 or len(exit_part)) > 0: if len(redo_part) > 0: return [True, [do_part + exit_part, redo_part], True, len(start_act_that_are_also_end) > 0] else: return [True, [do_part, redo_part + exit_part], False, len(start_act_that_are_also_end) > 0] return [False, [], False]
import java.io.*; import java.util.Scanner; public class B427 { static int [] cruelty; static int n; static int c; static int t; public static int number_of_ways() { int [] nCruel = new int[n]; nCruel[0] = 0; for (int i = 0; i < c; ++ i) if (cruelty[i] > t) ++nCruel[0]; for (int i = 1; i <= n - c; ++ i) { nCruel[i] = nCruel[i - 1]; if (cruelty[i - 1] > t) --nCruel[i]; if (cruelty[i - 1 + c] > t) ++nCruel[i]; } int res = 0; for (int i = 0; i <= n - c; ++ i) if (nCruel[i] == 0) ++res; return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); t = sc.nextInt(); c = sc.nextInt(); cruelty = new int[n]; for (int i = 0; i < n; ++ i) cruelty[i] = sc.nextInt(); System.out.println(number_of_ways()); } }
<filename>src/org/lwjgl/opengl/awt/PlatformLinuxGLCanvas.java package org.lwjgl.opengl.awt; import static org.lwjgl.system.jawt.JAWTFunctions.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.opengl.GLX.*; import static org.lwjgl.opengl.GLX13.*; import static org.lwjgl.opengl.GLXARBCreateContext.*; import static org.lwjgl.opengl.GLXARBCreateContextProfile.*; import static org.lwjgl.opengl.GLXARBCreateContextRobustness.*; import static org.lwjgl.opengl.GLXARBRobustnessApplicationIsolation.*; import static org.lwjgl.opengl.GLXEXTCreateContextESProfile.*; import java.awt.AWTException; import java.awt.Canvas; import java.nio.IntBuffer; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import org.lwjgl.opengl.ARBRobustness; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GL43; import org.lwjgl.system.APIUtil.APIVersion; import org.lwjgl.system.APIUtil; import org.lwjgl.system.Checks; import org.lwjgl.system.JNI; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.jawt.JAWT; import org.lwjgl.system.jawt.JAWTDrawingSurface; import org.lwjgl.system.jawt.JAWTDrawingSurfaceInfo; import org.lwjgl.system.jawt.JAWTX11DrawingSurfaceInfo; import org.lwjgl.system.linux.X11; public class PlatformLinuxGLCanvas implements PlatformGLCanvas { public static final JAWT awt; static { awt = JAWT.calloc(); awt.version(JAWT_VERSION_1_4); if (!JAWT_GetAWT(awt)) throw new AssertionError("GetAWT failed"); } public long display; public long drawable; public JAWTDrawingSurface ds; private long create(int depth, GLData attribs, GLData effective) throws AWTException { int screen = X11.XDefaultScreen(display); IntBuffer attrib_list = BufferUtils.createIntBuffer(16 * 2); attrib_list.put(GLX_DRAWABLE_TYPE).put(GLX_WINDOW_BIT); attrib_list.put(GLX_RENDER_TYPE).put(GLX_RGBA_BIT); attrib_list.put(GLX_RED_SIZE).put(attribs.redSize); attrib_list.put(GLX_GREEN_SIZE).put(attribs.greenSize); attrib_list.put(GLX_BLUE_SIZE).put(attribs.blueSize); attrib_list.put(GLX_DEPTH_SIZE).put(attribs.depthSize); attrib_list.put(GLX_DOUBLEBUFFER).put(attribs.doubleBuffer ? 1 : 0); attrib_list.put(0); attrib_list.flip(); PointerBuffer fbConfigs = glXChooseFBConfig(display, screen, attrib_list); if (fbConfigs == null || fbConfigs.capacity() == 0) { // No framebuffer configurations supported! throw new AWTException("No supported framebuffer configurations found"); } verifyGLXCapabilities(display, screen, attribs); IntBuffer gl_attrib_list = bufferGLAttribs(attribs); long share_context = NULL; if(Objects.nonNull(attribs.shareContext)) { if(attribs.shareContext.context == NULL){ throw new IllegalStateException( "Attributes specified shareContext but it is not yet created and thus cannot be shared"); } share_context = attribs.shareContext.context; } long context = glXCreateContextAttribsARB(display, fbConfigs.get(0), share_context, true, gl_attrib_list); if (context == 0) { throw new AWTException("Unable to create GLX context"); } populateEffectiveGLXAttribs(display, fbConfigs.get(0), effective); if (!makeCurrent(context)) { throw new AWTException("Unable to make context current"); } populateEffectiveGLAttribs(effective); makeCurrent(0 /* no context */); return context; } public void lock() throws AWTException { int lock = JAWT_DrawingSurface_Lock(ds, ds.Lock()); if ((lock & JAWT_LOCK_ERROR) != 0) throw new AWTException("JAWT_DrawingSurface_Lock() failed"); } public void unlock() throws AWTException { JAWT_DrawingSurface_Unlock(ds, ds.Unlock()); } public long create(Canvas canvas, GLData attribs, GLData effective) throws AWTException { this.ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface()); JAWTDrawingSurface ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface()); try { lock(); try { JAWTDrawingSurfaceInfo dsi = JAWT_DrawingSurface_GetDrawingSurfaceInfo(ds, ds.GetDrawingSurfaceInfo()); try { JAWTX11DrawingSurfaceInfo dsiWin = JAWTX11DrawingSurfaceInfo.create(dsi.platformInfo()); int depth = dsiWin.depth(); this.display = dsiWin.display(); this.drawable = dsiWin.drawable(); return create(depth, attribs, effective); } finally { JAWT_DrawingSurface_FreeDrawingSurfaceInfo(dsi, ds.FreeDrawingSurfaceInfo()); } } finally { unlock(); } } finally { JAWT_FreeDrawingSurface(ds, awt.FreeDrawingSurface()); } } public boolean deleteContext(long context) { return false; } public boolean makeCurrent(long context) { if (context == 0L) return glXMakeCurrent(display, 0L, 0L); return glXMakeCurrent(display, drawable, context); } public boolean isCurrent(long context) { return glXGetCurrentContext() == context; } public boolean swapBuffers() { glXSwapBuffers(display, drawable); return true; } public boolean delayBeforeSwapNV(float seconds) { throw new UnsupportedOperationException("NYI"); } public void dispose() { JAWT_FreeDrawingSurface(this.ds, awt.FreeDrawingSurface()); this.ds = null; } private static void verifyGLXCapabilities(long display, int screen, GLData data) throws AWTException { List<String> extensions = Arrays.asList(glXQueryExtensionsString(display, screen).split(" ")); if (!extensions.contains("GLX_ARB_create_context")) { throw new AWTException("GLX_ARB_create_context is unavailable"); } if (data.api == GLData.API.GLES && !extensions.contains("GLX_EXT_create_context_es_profile")) { throw new AWTException("OpenGL ES API requested but GLX_EXT_create_context_es_profile is unavailable"); } if (data.profile != null && !extensions.contains("GLX_ARB_create_context_profile")) { throw new AWTException("OpenGL profile requested but GLX_ARB_create_context_profile is unavailable"); } if (data.robustness && !extensions.contains("GLX_ARB_create_context_robustness")) { throw new AWTException("OpenGL robustness requested but GLX_ARB_create_context_robustness is unavailable"); } if (data.contextResetIsolation && !extensions.contains("GLX_ARB_robustness_application_isolation")) { throw new AWTException("OpenGL robustness requested but GLX_ARB_robustness_application_isolation is unavailable"); } } private static IntBuffer bufferGLAttribs(GLData data) throws AWTException { IntBuffer gl_attrib_list = BufferUtils.createIntBuffer(16 * 2); // Set the render type and version gl_attrib_list.put(GLX_RENDER_TYPE).put(GLX_RGBA_TYPE); if (data.majorVersion > 0) { gl_attrib_list .put(GLX_CONTEXT_MAJOR_VERSION_ARB).put(data.majorVersion) .put(GLX_CONTEXT_MINOR_VERSION_ARB).put(data.minorVersion); } // Set the profile based on GLData.api and GLData.profile int profile_attrib = -1; if (data.api == GLData.API.GLES) { if (data.profile != null) { throw new AWTException("Cannot request both OpenGL ES and profile: " + data.profile); } profile_attrib = GLX_CONTEXT_ES_PROFILE_BIT_EXT; } else if (data.api == GLData.API.GL || data.api == null) { if (data.profile == GLData.Profile.CORE) { profile_attrib = GLX_CONTEXT_CORE_PROFILE_BIT_ARB; } else if (data.profile == GLData.Profile.COMPATIBILITY) { profile_attrib = GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; } else if (data.profile != null) { throw new AWTException("Unknown requested profile: " + data.profile); } } else { throw new AWTException("Unknown requested API: " + data.api); } if (profile_attrib != -1) { gl_attrib_list.put(GLX_CONTEXT_PROFILE_MASK_ARB).put(profile_attrib); } // Set debugging and forward compatibility int context_flags = 0; if (data.debug) { context_flags |= GLX_CONTEXT_DEBUG_BIT_ARB; } if (data.forwardCompatible) { context_flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } if (data.robustness) { context_flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB; int notificationStrategy; if (data.loseContextOnReset) { notificationStrategy = GLX_LOSE_CONTEXT_ON_RESET_ARB; if (data.contextResetIsolation) { context_flags |= GLX_CONTEXT_RESET_ISOLATION_BIT_ARB; } } else { notificationStrategy = GLX_NO_RESET_NOTIFICATION_ARB; } gl_attrib_list.put(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB).put(notificationStrategy); } gl_attrib_list.put(GLX_CONTEXT_FLAGS_ARB).put(context_flags); gl_attrib_list.put(0).flip(); return gl_attrib_list; } private static void populateEffectiveGLXAttribs(long display, long fbId, GLData effective) throws AWTException { IntBuffer buffer = BufferUtils.createIntBuffer(1); glXGetFBConfigAttrib(display, fbId, GLX_RED_SIZE, buffer); effective.redSize = buffer.get(0); glXGetFBConfigAttrib(display, fbId, GLX_GREEN_SIZE, buffer); effective.greenSize = buffer.get(0); glXGetFBConfigAttrib(display, fbId, GLX_BLUE_SIZE, buffer); effective.blueSize = buffer.get(0); glXGetFBConfigAttrib(display, fbId, GLX_DEPTH_SIZE, buffer); effective.depthSize = buffer.get(0); glXGetFBConfigAttrib(display, fbId, GLX_DOUBLEBUFFER, buffer); effective.doubleBuffer = buffer.get(0) == 1; } private static void populateEffectiveGLAttribs(GLData effective) throws AWTException { long glGetIntegerv = GL.getFunctionProvider().getFunctionAddress("glGetIntegerv"); long glGetString = GL.getFunctionProvider().getFunctionAddress("glGetString"); APIVersion version = APIUtil.apiParseVersion(getString(GL11.GL_VERSION, glGetString)); effective.majorVersion = version.major; effective.minorVersion = version.minor; int profileFlags = getInteger(GL32.GL_CONTEXT_PROFILE_MASK, glGetIntegerv); if ((profileFlags & GLX_CONTEXT_ES_PROFILE_BIT_EXT) != 0) { effective.api = GLData.API.GLES; } else { effective.api = GLData.API.GL; } if (version.major >= 3) { if (version.major >= 4 || version.minor >= 2) { if ((profileFlags & GL32.GL_CONTEXT_CORE_PROFILE_BIT) != 0) { effective.profile = GLData.Profile.CORE; } else if ((profileFlags & GL32.GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0) { effective.profile = GLData.Profile.COMPATIBILITY; } else if ( (profileFlags & GLX_CONTEXT_ES_PROFILE_BIT_EXT) != 0) { // OpenGL ES allows checking for profiles at versions below 3.2, so avoid branching into // the if and actually check later. } else if (profileFlags != 0) { throw new AWTException("Unknown profile " + profileFlags); } } int effectiveContextFlags = getInteger(GL30.GL_CONTEXT_FLAGS, glGetIntegerv); effective.debug = (effectiveContextFlags & GL43.GL_CONTEXT_FLAG_DEBUG_BIT) != 0; effective.forwardCompatible = (effectiveContextFlags & GL30.GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) != 0; effective.robustness = (effectiveContextFlags & ARBRobustness.GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB) != 0; effective.contextResetIsolation = (effectiveContextFlags & GLX_CONTEXT_RESET_ISOLATION_BIT_ARB) != 0; } if (effective.robustness) { int effectiveNotificationStrategy = getInteger(ARBRobustness.GL_RESET_NOTIFICATION_STRATEGY_ARB, glGetIntegerv); effective.loseContextOnReset = (effectiveNotificationStrategy & ARBRobustness.GL_LOSE_CONTEXT_ON_RESET_ARB) != 0; } effective.samples = getInteger(GL13.GL_SAMPLES, glGetIntegerv); } private static int getInteger(int pname, long function) { MemoryStack stack = MemoryStack.stackGet(); int stackPointer = stack.getPointer(); try { IntBuffer params = stack.callocInt(1); JNI.callPV(pname, memAddress(params), function); return params.get(0); } finally { stack.setPointer(stackPointer); } } private static String getString(int pname, long function) { return memUTF8(Checks.check(JNI.callP(pname, function))); } }
// SetUp creates a new LZ4 writer, tar writer and file for // writing bundled compressed bytes to. func (tarBall *FileTarBall) SetUp(crypter crypto.Crypter, names ...string) { if tarBall.tarWriter == nil { name := filepath.Join(tarBall.out, "part_"+fmt.Sprintf("%0.3d", tarBall.number)+".tar.lz4") file, err := os.Create(name) if err != nil { panic(err) } var writeCloser io.WriteCloser if crypter != nil { writeCloser, err = crypter.Encrypt(file) if err != nil { panic(err) } tarBall.writeCloser = &internal.CascadeWriteCloser{ WriteCloser: lz4.NewWriter(file), Underlying: &internal.CascadeWriteCloser{WriteCloser: writeCloser, Underlying: file}, } } else { writeCloser = file tarBall.writeCloser = &internal.CascadeWriteCloser{ WriteCloser: lz4.NewWriter(file), Underlying: writeCloser, } } tarBall.tarWriter = tar.NewWriter(tarBall.writeCloser) } }
Get ready for another round of classroom drama and cover songs, because Glee is coming back for a fourth season this fall! FOX confirmed the news on Monday, adding that the popular comedies Raising Hope and New Girl will also return for a third and second season, respectively. The future of Glee, which returns with all-new episodes Tuesday night at 8 PM, has been in question ever since series creator Ryan Murphy gave a controversial interview to The Hollywood Reporter in 2011, in which he revealed that stars Chris Colfer, Lea Michele and Cory Monteith’s characters would graduate at the end of season 3 and, thus, not be back for a fourth season. “You can keep them on the show for six years and people will criticize you for not being realistic, or you can be really true to life and say when they started the show they were very clearly sophomores and they should graduate at the end of their senior year,” he said at the time. The interview quickly created a media firestorm — and, naturally Murphy quickly back-peddled on his statements, going so far as to bring up the idea of a spinoff for the characters. “We were going to do a spin-off where the three of them were going to go on. They all knew what was happening, they all had approved it, they all said they wanted to do it.” Since then, it has been confirmed that all three actors will be back for season 4. Speaking to The Hollywood Reporter in January, Monteith said, “Yes, I’ll be back. I’m very excited.” Added Michele: “Ryan has come up with a brilliant, ground-breaking idea for how to include us graduating high school seniors into next season and it’s really exciting. We don’t want to give away the new formula but I’m excited and Cory is so excited to be coming back next year. When we heard Ryan’s plan, it really made us even more thrilled.” Colfer also confirmed to The Insider that he will be back as well. “I’m very excited. A lot of people are sad there won’t be a spinoff but I think they’re going to be very very excited to find out what’s in store – I’m very excited by it. Ryan’s idea is kind of revolutionary. It’s the best of both worlds. Everyone is going to like it,” he said in January. And with that, everyone can now breath a heavy sigh of relief! Everyone can also check out these super-hot photos of Lea and Cory while on vacation over the weekend in Cabo. Click through our gallery below!
/** * Icon associadte to the type of the businness data * * @author Ramilafananana Vonjisoa * @mailTo [email protected] * @date 29 janv. 2018 */ public class PeopleThumbPresenter extends CellPresenterImpl implements ModelIconPresenter { private static final String NO_THUMB_H = "/images/avatar/avatar-f.png"; private static final String NO_THUMB_F = "/images/avatar/avatar-h.png"; private static final String NO_THUMB_ALL = "/images/avatar/profile.png"; private final StackPane content = new StackPane(); // needs GetThumbOperation private IOperation getThumbOperation; public PeopleThumbPresenter() { } /** * @{inheritedDoc} */ @Override public Node provideIcon(IJSoaggerController controller, VLViewComponentXML configuration) { return provideIcon(controller, configuration, null); } /** * @{inheritedDoc} */ @Override public Node provideIcon(IJSoaggerController controller, VLViewComponentXML configuration, Object forModel) { OperationData data = (OperationData) forModel; if (data == null) { data = ((AbstractViewController)controller).getOpData(); } final String fullId = (String) data.getAttributes().get("fullId"); String gender = String.valueOf((Double.valueOf(String.valueOf(data.getAttributes().get("gender"))).intValue())); final Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { if (StringUtils.isEmpty(fullId)) { displayEmptyThumb(gender); } if (getThumbOperation == null) { displayEmptyThumb(gender); } else { displayThumb(fullId, gender); } return null; } }; final Thread t = new Thread(task); t.setDaemon(true); t.setName("Thumnail_thread__"); t.start(); return content; } private void displayThumb(String fullId, String gender) { final JsonObject query = new JsonObject(); query.addProperty("fullId", fullId); getThumbOperation.doOperation(query, res -> { if (res == null || res.hasBusinessError()) { displayEmptyThumb(gender); } else { try { final SingleResult sr = (SingleResult) res; final byte[] imgbytes = (byte[]) sr.getMetaData().get("thumb"); if (imgbytes != null && imgbytes.length > 0) { getJavaFXImage(imgbytes, gender); } else { displayEmptyThumb(gender); } } catch (final Exception e) { e.printStackTrace(); displayEmptyThumb(gender); } } }, ex -> { ex.printStackTrace(); displayEmptyThumb(gender); }); } private void displayEmptyThumb(String gender) { Image img = null; if(StringUtils.isEmpty(gender) || "0".equals(gender)) { img = new Image(NO_THUMB_ALL, 80, 80, true, true); } else { img = new Image(NO_THUMB_ALL, 80, 80, true, true); } final ImageView imgView = new ImageView(img); Platform.runLater(() -> { content.getChildren().add(imgView); }); StackPane wrapper = new StackPane(); wrapper.getChildren().add(imgView); wrapper.getStyleClass().add("ep-people-thumb-container"); content.getChildren().add(wrapper); } /** * @{inheritedDoc} */ @Override public Node present(IJSoaggerController controller, VLViewComponentXML configuration, Object forModel) { return provideIcon(controller, configuration, forModel); } public void getJavaFXImage(byte[] rawPixels, String gender) { try { final BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(rawPixels))); final java.awt.Image transistionImg = originalImage.getScaledInstance(60, 60, java.awt.Image.SCALE_SMOOTH); final BufferedImage currentImage = new BufferedImage(60, 60, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = currentImage.createGraphics(); g2d.drawImage(transistionImg, 0, 0, null); final Image image = SwingFXUtils.toFXImage(currentImage, null); final ImageView imageView = new ImageView(image); // set a clip to apply rounded border to the original image. final Rectangle clip = new Rectangle(60, 60); clip.setArcWidth(180); clip.setArcHeight(180); imageView.setClip(clip); // remove the rounding clip so that our effect can show through. // imageView.setClip(null); // store the rounded image in the imageView. imageView.setImage(image); Platform.runLater(() -> { content.getChildren().add(imageView); }); } catch (final Exception ex) { ex.printStackTrace(); displayEmptyThumb(gender); } } }
Consulting Services Need help to upgrade or migrate your site ? Consult our Need help to upgrade or migrate your site ? Consult our fixed price consulting plans to see our rates ! Microsoft has released a new version of SCCM Current Branch. It’s now time to upgrade your environment! This post is a complete step-by-step SCCM 1710 upgrade guide. If you’re looking for a complete SCCM installation guide, see our blog series which covers it all. You won’t be able to install this upgrade if you are running SCCM 2012, the minimum required version is at least SCCM 1702. This version is the latest baseline version. It’s very important to keep your infrastructure up to date. You can benefit from the new features and fixes lots of issues, which some of them are important. It’s also easier to upgrade to the new version since Microsoft has implemented the new model of update servicing. SCCM 1710 New Features and Fixes SCCM 1710 includes lots of new features and enhancements in the adoption of Windows 10 and Office 365 as well in modern management, mobile device management, site infrastructure, compliance settings, application management, software updates, reporting and device protection. You can consult the What’s new in version 1710 of System Center Configuration Manager Technet article for a full list of changes. Here’s our list of favorite features: Co-management for Windows 10 devices Restart computers form the Configuration Manager console Add child task sequences to a task sequence (Woot ! My Last year MVP hackathon project) Improvements for Run Scripts Support for SCCM Current Branch Versions Ensure to apply this update before you fall into an unsupported SCCM version. Read about the support end date of the prior version of the following Technet article. Before you Begin Downloading and installing this update is done entirely from the console. There’s no download link, the update will appear on your console once the Service Connection Point is synchronized. If you’re running a multi-tier hierarchy, start at the top-level site in the hierarchy. After the CAS upgrade, you can begin the upgrade of each child site. Complete the upgrade of each site before you begin to upgrade the next site. Until all sites in your hierarchy are upgraded, your hierarchy operates in a mixed version mode. Before applying this update, we strongly recommend that you go through the upgrade checklist provided on Technet. Most importantly, initiate a site backup before your upgrade. In this post, we will update a stand-alone primary site server, consoles, and clients. Before installing, check if your site is ready for the update: Open the SCCM console Go to Administration \ Updates and Servicing In the State column, ensure that the update Configuration Manager 1710 is Available If it’s not available, right-click Updates and Servicing and select Check for Updates × Warning The SCCM 1710 update is not yet available for everyone. If you need it right away you can run the Fast-Ring script and the update will show up. If the update is not downloading, click on the button Download on the upper node. The update state will change to Downloading You can follow the download in Dmpdownloader.log or by going to Monitoring / Updates and Servicing Status, right-click your Update Name and select Show Status The process will first download the .CAB file and will then extract the file in the EasyPayload folder in your SCCM installation directory. GUID : b56c84cf-f5a1-48d2-b89a-5bac6b2c983b folder in your SCCM installation directory. It can take up to 15 minutes to extract all files. SCCM 1710 Upgrade Guide Step 1 | SCCM 1710 Prerequisite Check [su_note note_color=”#eebebc” radius=”8″]You may experience problems if the downloading status remains for a long time. You can find solutions on the net like the MVP Anoop post . Even though updates are becoming easier to do, this is the most common problem. Please note that starting with SCCM 1706, a reset tool has been included to help you in these situations. MVP Kent Agerlund did a great post about the tool .[/su_note] Before launching the update, we recommend to launch the prerequisite check first: Open the SCCM console Go to Administration \ Updates and Servicing Right-click the Configuration Manager 1710 update and select Run prerequisite check Nothing will happen, the prerequisite check runs in the background and all menu are unavailable during the check One way to see progress is by viewing C:\ConfigMgrPrereq.log You can also monitor prerequisite check by going to Monitoring / Update and Servicing Status, right-click your Update Name and select Show Status When completed the State column will show Prerequisite check passed Step 2 | Launching the SCCM 1710 update We are now ready to launch the SCCM 1710 update. At this point, plan about 45 minutes to install the update. Right-click the Configuration Manager 1710 update and select Install Update Pack On the General tab, click Next On the Features tab, checkboxes on the features you want to enable during the update Don’t worry, if you don’t select one of the features now and want to enable it later, you’ll be able to so by using the console in Administration \ Updates and Servicing \ Features In the Client Update Options , select the desired option for your client update This option allows updating only clients member of a specific collection. Refer to our pre-production client deployment post for more details , select the desired option for your client update On the License Terms tab, accept the license terms and click Next On the Summary tab, review your choices, click Next and close the wizard on the Completion tab The whole process took a minute but the installation begins on the back end. During installation, the State column changes to Installing We suggest you monitor the progress, by navigating to Monitoring / Updates and Servicing Status, right-click your Update Name and select Show Status Unfortunately, the status is not updated in real time. Use the Refresh button to update. Open the SCCM log SCCM Installation Directory\Logs\CMUpdate.log with CMTrace When completed, you’ll notice the message There are no pending update package to be processed in the log file in the log file Monitoring / Updates and Servicing Status, right-click your Update Name and select Show Status, the last step will be Installation Succeeded [su_note note_color=”#eebebc” radius=”8″]We’ve done numerous SCCM upgrades. Some installation start a couple of minutes after you complete the wizard but we’ve seen some installation starts after a 10 minutes delay. Do not reboot or restart any services during this period or your update can be stuck in “Prerequisite check passed” status. There’s actually no officially documented methods by Microsoft to fix that. Patience is the key![/su_note] Refresh the Updates and Servicing node in Administration, the State column will be Installed Updating the Outdated Consoles As a previous Cumulative update, the console has an auto-update feature. At console opening, if you are not running the latest version, you will receive a warning and the update will start automatically. Since all updates operations were initiated from the console, we didn’t close it during the process. We received a warning message when clicking certain objects. You will have the same message when opening a new console Click OK, console update will start automatically Wait for the process to complete. You can follow the progress in C:\ConfigMgrAdminUISetup.log and C:\ConfigMgrAdminUISetupVerbose.log. Once completed, the console will open and you’ll be running the latest version Verification Consoles After setup is completed, verify the build number of the console. If the console upgrade was successful, the build number will be 5.0.8577.1000 and the version is now Version 1710 . Servers Go to Administration \ Site Configuration \ Sites Right-click your site and select Properties Verify the Version and Build number Clients The client version will be updated to 5.00.8577.1003 (after updating, see section below) SCCM 1710 Client Package distribution You’ll see that the 2 client packages are updated: Navigate to Software Library \ Application Management \ Packages Check if the update is successful, otherwise, select both packages and initiate a Distribute Content to your distribution points Boot Images Boot images will automatically update during setup. See our post on upgrade consideration in a large environment to avoid this if you have multiple distribution points. Go to Software Library / Operating Systems / Boot Images Select your boot image and check the last Content Status date. It should match your setup date Updating the Clients Our preferred way to update our clients is by using the Client Upgrade feature: (You can refer to our complete post documenting this feature) Open the SCCM Console Go to Administration / Site Configuration / Sites Click the Hierarchy Settings in the top ribbon in the top ribbon Select Client Upgrade tab tab The Upgrade client automatically when the new client update is available check box is enable check box is enable Review your time frame and adjust it to your needs Monitor SCCM Client Version Number SCCM Reports Client Version You can see our SCCM Client version reports to give detailed information about every client version in your environment. It’s the easiest way to track your client updates. Collections In conclusion, you can create a collection that targets clients without the latest client version because is very useful when it comes to monitoring non-compliant client. Here’s the query to achieve this: (You can also refer to our Set of Operational Collection Powershell Script which contains this collection) select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.ClientVersion != '5.00.8577.1003' Happy updating!!
/** * The Virtual Machine Template Capture Role operation response. */ public class VirtualMachineCaptureVMImageParameters extends OperationResponse { private String operationType; /** * Optional. Required. Must be set to CaptureRoleOperation. * @return The OperationType value. */ public String getOperationType() { return this.operationType; } /** * Optional. Required. Must be set to CaptureRoleOperation. * @param operationTypeValue The OperationType value. */ public void setOperationType(final String operationTypeValue) { this.operationType = operationTypeValue; } private String oSState; /** * Optional. Required. The OS state: Generalized | Specialized. * @return The OSState value. */ public String getOSState() { return this.oSState; } /** * Optional. Required. The OS state: Generalized | Specialized. * @param oSStateValue The OSState value. */ public void setOSState(final String oSStateValue) { this.oSState = oSStateValue; } private String vMImageLabel; /** * Optional. Required. The VM Template Label. * @return The VMImageLabel value. */ public String getVMImageLabel() { return this.vMImageLabel; } /** * Optional. Required. The VM Template Label. * @param vMImageLabelValue The VMImageLabel value. */ public void setVMImageLabel(final String vMImageLabelValue) { this.vMImageLabel = vMImageLabelValue; } private String vMImageName; /** * Optional. Required. The VM Template Name. * @return The VMImageName value. */ public String getVMImageName() { return this.vMImageName; } /** * Optional. Required. The VM Template Name. * @param vMImageNameValue The VMImageName value. */ public void setVMImageName(final String vMImageNameValue) { this.vMImageName = vMImageNameValue; } }
#include<iostream> #include<cstdio> #include <stdio.h> #include<algorithm> #include<cstring> #include <string> #include<cmath> #include<cstdlib> #include<queue> #include<map> #include<vector> #include<bits/stdc++.h> #include <set> #define ll long long #define IO ios::sync_with_stdio(false);cin.tie();cout.tie(0) #define inf 0x3f3f3f3f3f3f #define pi 3.1415926535898 using namespace std; const int N=2e5+10; const int mod=1e9+7; int a[N]; int f[N][3][2];//��ʾ��i��BOSS�����һ��ɱ�˼���BOSS�����ڵ�˭�� int main() { int t; cin>>t; while(t--) { int n; cin>>n; for(int i=1; i<=n; i++) { cin>>a[i]; for(int j=1; j<=2; j++) for(int k=0; k<=1; k++) f[i][j][k]=0x3f3f3f3f; } f[0][2][0]=f[0][1][0]=0x3f3f3f3f; for(int i=1; i<=n; i++)//ö�ٵ�i��BOSS { f[i][1][0]=min(f[i-1][1][1],f[i-1][2][1])+a[i]; if(i>=2) f[i][2][0]=min(f[i-2][1][1],f[i-2][2][1])+a[i]+a[i-1]; f[i][1][1]=min(f[i-1][1][0],f[i-1][2][0]); if(i>=2) f[i][2][1]=min(f[i-2][1][0],f[i-2][2][0]); } int res=0x3f3f3f3f; for(int i=1; i<=2; i++) for(int j=0; j<=1; j++) res=min(res,f[n][i][j]); cout<<res<<endl; } return 0; }
import os import sys import commands import argparse import time import datetime import numpy as np from lxml import etree boolean_dict = \ {'true' : True, '1' : True, 'yes' : True, 'false' : False, '0' : False, 'no' : False, 'none' : False } # ============================================================================= # XML WRAPPERS # ============================================================================= class ExtendableNamespace(argparse.Namespace): def AddNamespace(self, **kwargs): for name in kwargs: att = getattr(self, name, None) if att is None: setattr(self, name, kwargs[name]) else: setattr(self, name, kwargs[name].As(type(att))) return def Add(self, name, value): att = getattr(self, name, None) if att is None: setattr(self, name, value) else: raise AssertionError("Key %s already exists" % name) return value def GenerateTreeDict(tree, element, path='', paths_rel_to=None): if type(element) == etree._Comment: return [], {} # Update path if path == '': if element.tag != paths_rel_to: path += element.tag else: path += '/' + element.tag # Containers for lower levels tag_node = {} nodes = [] # Construct Node xmlnode = XmlNode(element, path) # tree.getpath(element)) nodes.append(xmlnode) if len(element) == 0: tag_node[path] = xmlnode #else: # print "len 0", xmlnode.path # tag_node[path] = xmlnode # Iterate over children for child in element: child_elements, childtag_element = GenerateTreeDict(tree, child, path) nodes = nodes + child_elements for key in childtag_element.keys(): if tag_node.has_key(key): if type(tag_node[key]) != list: tag_node[key] = [ tag_node[key], childtag_element[key] ] else: tag_node[key].append(childtag_element[key]) else: tag_node[key] = childtag_element[key] return nodes, tag_node def NamespaceFromDict(tree_dict): nspace = ExtendableNamespace() for key in tree_dict.keys(): sections = key.split('/') values = [ None for s in sections ] values[-1] = tree_dict[key] add_to_nspace = nspace for s,v in zip(sections, values): if v == None: sub_nspace = ExtendableNamespace() add_to_nspace = add_to_nspace.Add(s, sub_nspace) else: add_to_nspace.Add(s, v) return nspace class XmlTree(list): def __init__(self, xmlfile, paths_rel_to=None): self.xmlfile = xmlfile self.xtree = etree.parse(xmlfile) self.xroot = self.xtree.getroot() self.nodes, self.tag_node = GenerateTreeDict(self.xtree, self.xroot, '', paths_rel_to) self.xspace = NamespaceFromDict(self.tag_node) def SelectByTag(self, tag): selection = [ e for e in self.nodes if e.tag == tag ] return selection def __getitem__(self, key): return self.tag_node[key] def keys(self): return self.tag_node.keys() class XmlNode(object): def __init__(self, element, path): self.path = path self.node = element self.tag = element.tag self.value = element.text self.attributes = element.attrib def As(self, typ): if typ == np.array: sps = self.value.split() return typ([ float(sp) for sp in sps ]) elif typ == bool: return boolean_dict.get(self.value.lower()) else: return typ(self.value) def AsArray(self, typ, sep=' ', rep='\t\n'): for r in rep: self.value = self.value.replace(r, sep) sp = self.value.split(sep) return [ typ(s) for s in sp if str(s) != '' ] def SetNodeValue(self, new_value): self.value = new_value if self.node != None: self.node.firstChild.nodeValue = new_value return def __getitem__(self, key): return self.node.get(key) # ============================================================================= # COMMAND LINE & XML INPUT INTERFACE # ============================================================================= class CLIO_HelpFormatter(argparse.HelpFormatter): def _format_usage(self, usage, action, group, prefix): return "%s : Command Line Interface\n" % sys.argv[0] class OptionsInterface(object): def __init__(self): # COMMAND-LINE ARGUMENTS self.is_connected_to_cmd_ln = False self.cmd_ln_args = None self.cmd_ln_opts = None self.cmd_ln_nicknames = [ '-h' ] self.boolean_translator = boolean_dict self.subtype = str # XML OPTIONS FILE self.is_connected_to_xml = False self.xmlfile = None self.tree = None self.xdict = None self.xspace = None # JOINED OPTIONS self.opts = ExtendableNamespace() def Connect(self, xmlfile=None): self.ConnectToCmdLn() self.ConnectToOptionsFile(xmlfile) def Parse(self, xkey='options'): if self.is_connected_to_cmd_ln: self.ParseCmdLn() if self.is_connected_to_xml: self.ParseOptionsFile(xkey) if self.is_connected_to_cmd_ln and not self.is_connected_to_xml: return self.cmd_ln_opts elif self.is_connected_to_xml and not self.is_connected_to_cmd_ln: return self.xspace else: return self.cmd_ln_opts, self.xspace # COMMAND-LINE CONVENIENCE ================================================ def __call__(self): return self.cmd_ln_opts def ConnectToCmdLn(self, prog=sys.argv[0], descr=None): self.cmd_ln_args = argparse.ArgumentParser(prog=sys.argv[0], formatter_class=lambda prog: CLIO_HelpFormatter(prog,max_help_position=70)) self.is_connected_to_cmd_ln = True return def ParseCmdLn(self): self.cmd_ln_opts = self.cmd_ln_args.parse_args() def InterpretAsBoolean(self, expr): try: return self.boolean_translator.get(expr.lower()) except KeyError: raise ValueError('CLIO does not know how to convert %s into a boolean.' % expr) def InterpretAsNumpyArray(self, expr): print "Interpret", expr array = [ float(e) for e in expr ] array = np.array(array) return array def InterpretAsList(self, expr): array = [ self.subtype(e) for e in expr ] return array def AddArg(self, name, typ=str, nickname=None, default=None, destination=None, help=None): # Sort out <name> (e.g. --time) vs <destination> (e.g., time) if '--' != name[0:2]: dest = name name = '--' + name else: dest = name[2:] # Sort out <default> vs <required> if default == None: required = True else: required = False # Construct default <help> it not given if help == None: help = str(typ) # Construct <nickname> if not given if nickname == None: nickname = '-' for char in dest: nickname += char if not nickname in self.cmd_ln_nicknames: break if nickname in self.cmd_ln_nicknames: raise ValueError('CLIO could not construct nickname from %s option'\ % name) self.cmd_ln_nicknames.append(nickname) # Process type if typ in [int, float, str]: nargs = None elif typ == bool: typ = self.InterpretAsBoolean nargs = None elif typ == np.array: raise NotImplementedError typ = float # self.InterpretAsNumpyArray nargs = 3 elif typ == list: typ = str nargs = '*' elif len(typ) == 2 and typ[0] == list: typ = typ[1] nargs = '*' else: raise NotImplementedError("CLIO does not know how to generate type '%s'"\ % typ) self.cmd_ln_args.add_argument(nickname, name, dest=dest, action='store', nargs=nargs, required=required, type=typ, metavar=dest[0:1].upper(), default=default, help=help) return # COMMAND-LINE CONVENIENCE ================================================ def ConnectToOptionsFile(self, xmlfile): if xmlfile == None or xmlfile == '': return self.xmlfile = xmlfile self.is_connected_to_xml = True return def ParseOptionsFile(self, xkey='options'): if self.xmlfile == None: return self.tree = XmlTree(self.xmlfile, paths_rel_to=xkey) self.xdict = self.tree.tag_node self.xspace = self.tree.xspace return def __getitem__(self, key): try: return self.xspace.__dict__[key] except KeyError: return self.cmd_ln_opts.__dict__[key] except KeyError: raise AttributeError('No such option registered: \'%s\'' % key) return None # ============================================================================= # OS SHELL INTERFACE # ============================================================================= class ShellInterface(object): def __init__(self): # ===================================================================== # PRINTER ATTRIBUTES self.color_dict = { \ 'pp' : '\033[95m', 'mb' : '\033[34m', 'lb' : '\033[1;34m', 'my' : '\033[1;33m', 'mg' : '\033[92m', 'mr' : '\033[91m', 'ww' : '\033[0;1m', 'ok' : '\033[92m', 'xx' : '\033[91m', 'warning' : '\033[93m', 'error' : '\033[95m', 'endcolor' : '\033[0;1m' } self.justify_dict = { \ 'o' : ' o ', '.' : '... ', 'r' : '\r', 'ro' : '\r o '} self.pp = OS_COLOR('pp') self.lb = OS_COLOR('lb') self.mb = OS_COLOR('mb') self.mg = OS_COLOR('mg') self.my = OS_COLOR('my') self.mr = OS_COLOR('mr') self.ww = OS_COLOR('ww') self.ok = OS_COLOR('ok') self.xx = OS_COLOR('xx') self.colors = [ OS_COLOR(c) for c in sorted(self.color_dict.keys()) ] self.item = ' o ' self.iitem = ' - ' self.endl = OS_LINE_CHAR('\n') self.flush = OS_LINE_CHAR('') self.trail = ' ' # CURRENT STYLE SELECTION self.sel_color = None self.sel_justify = None self.sel_header = False self.sel_trim = "=" # EXE ATTRIBUTES self.catch = OS_EXE_CATCH() self.assert_zero = OS_EXE_ASSERT() self.dev = OS_EXE_DEV('') self.nodev = OS_EXE_DEV('') self.devnull = OS_EXE_DEV() self.devfile = OS_EXE_DEV('') self.os_exe_get = False self.os_exe_assert_zero = False self.os_exe_dev = '' self.os_exe_verbose = False # LOGGING self.logfile = None # DIRECTORY HOPPING self.paths_visited = [ os.getcwd() ] self.exe_root_path = self.paths_visited[0] self.N_store_paths_visited = 1+5 def __call__(self, mssg, c=None, j=None, h=False, t="="): # c=color, j=justify, h=header, t=trim, u=upper-case if j: mssg = self.justify_dict[j] + mssg if c != None: mssg = self.color_dict[c] + mssg + self.color_dict['endcolor'] if h: mssg = self.os_generate_header(mssg, t) print mssg # LOGFILE ADAPTOR ========================================================= def ConnectToFile(self, logfile): self.logfile = logfile sys.stdout = open(logfile, 'w') self.devfile = OS_EXE_DEV(' >> {log} 2>> {log}'.format(log=logfile)) return def DisconnectFromFile(self): if self.logfile != None: self.devfile = OS_EXE_DEV('') self.logfile = None sys.stdout = sys.__stdout__ else: pass return # PRINTER METHODS ========================================================= def __lshift__(self, mssg): if type(mssg) == OS_LINE_CHAR: # <LOG MESSAGE HERE> sys.stdout.write(str(mssg)) sys.stdout.flush() self.sel_color = None return self elif type(mssg) == OS_COLOR: self.sel_color = str(mssg) return self mssg = str(mssg) if self.sel_justify != None: mssg = self.justify_dict[j] + mssg mssg += self.trail if self.sel_color != None: mssg = self.color_dict[self.sel_color] \ + mssg + self.color_dict['endcolor'] if self.sel_header: mssg = self.os_generate_header(mssg, self.sel_trim) # <LOG MESSAGE HERE> sys.stdout.write(mssg) return self def os_print(self, mssg, c=None, j=None, h=False, t="="): # c=color, j=justify, h=header, t=trim, u=upper-case if j: mssg = OS_JUSTIFY_DICT[j] + mssg if c != None: mssg = OS_COLOR_DICT[c] + mssg + OS_COLOR_DICT['endcolor'] if h: mssg = os_generate_header(mssg, t) print mssg return def os_print_config(self, c=None, j=None, h=False, t="=", tl=' '): self.sel_color = c self.sel_justify = j self.sel_header = h self.sel_trim = t self.trail = tl return def os_print_reset(self): self.sel_color = None self.sel_justify = None self.sel_header = False self.sel_trim = "=" self.trail = ' ' return def os_generate_header(title, trim="="): try: height, width = os.popen('stty size', 'r').read().split() width = int(width) leftright = int((width - len(title)-2)/2) except ValueError: leftright = 40 return trim*leftright + " " + title + " " + trim*leftright # EXECUTE METHODS ========================================================= def __rshift__(self, cmmd): if type(cmmd) == OS_EXE_CATCH: self.os_exe_get = True return self elif type(cmmd) == OS_EXE_DEV: self.dev = cmmd return self elif type(cmmd) == OS_EXE_ASSERT: self.os_exe_assert_zero = True return self # Redirect command as requested (not applicable if output is asked for) if not self.os_exe_get: if str(self.dev) != '': cmmd += str(self.dev) self.dev = self.nodev else: cmmd += str(self.devfile) # Execute if self.debug: self << self.my << "exe:" << cmmd << endl if self.os_exe_get: output = commands.getoutput(cmmd) self.os_exe_get = False return output else: sign = os.system(cmmd) if self.os_exe_assert_zero: if str(sign) != '0': raise RuntimeError("<OSIO> '%s' returned '%s'" % (cmmd, sign)) self.os_exe_assert_zero = False return sign # EXIT PROTOCOLS ========================================================== def okquit(self, what=''): if what != '': self << self.ok << what << self.endl self.DisconnectFromFile() sys.exit(0) return def xxquit(self, what=''): if what != '': self << self.xx << "ERROR" << what << self.endl self.DisconnectFromFile() sys.exit(1) return # DIRECTORY HOPPING ======================================================= def cd(self, d): # Current working directory, for archiving ... => cwd = os.getcwd() if type(d) == int: # Change to previously visited path os.chdir(self.paths_visited[d]) elif type(d) == str: # Change to path as specified explicitly os.chdir(d) else: raise NotImplementedError # <= ... previous path self.paths_visited.append(cwd) if len(self.paths_visited) > self.N_store_paths_visited: self.paths_visited.pop(1) # 0 stores root if self.debug: self << self.my << "cd: " << os.getcwd() << self.endl return def pwd(self): return self.cwd() def cwd(self): return os.getcwd() def root(self): self.cd(self.exe_root_path) return def abspath(self, file): if not os.path.exists(file): raise IOError("<osio::abspath> No such item in local directory: '%s'" % file) return os.path.join(self.cwd(), file) def mkcd(self, directory): self >> self.assert_zero >> 'mkdir -p %s' % directory self.cd(directory) return directory class OS_EXE_DEV(object): def __init__(self, dev=' > /dev/null 2> /dev/null'): self.dev = dev def __str__(self): return self.dev class OS_EXE_CATCH(object): def __init__(self): self.catch = True class OS_EXE_ASSERT(object): def __init__(self): self.assert_0 = True class OS_COLOR(object): def __init__(self, colstr): self.colstr = colstr def __str__(self): return self.colstr class OS_LINE_CHAR(object): def __init__(self, char): self.char = char def __str__(self): return self.char class OSIO(ShellInterface, OptionsInterface): def __init__(self): self.debug = False ShellInterface.__init__(self) OptionsInterface.__init__(self) return def sleep(self, dt): time.sleep(dt) return def now(self): return str(datetime.datetime.now())[:-7] osio = OSIO() endl = OS_LINE_CHAR('\n') flush = OS_LINE_CHAR('') back = OS_LINE_CHAR('\r') catch = OS_EXE_CATCH() devnull = OS_EXE_DEV()