import unittest, os, errno
from ctypes import *
from ctypes.util import find_library
from test import test_support
try:
    import threading
except ImportError:
    threading = None

class Test(unittest.TestCase):
    def test_open(self):
        libc_name = find_library("c")
        if libc_name is None:
            raise unittest.SkipTest("Unable to find C library")
        libc = CDLL(libc_name, use_errno=True)
        if os.name == "nt":
            libc_open = libc._open
        else:
            libc_open = libc.open

        libc_open.argtypes = c_char_p, c_int

        self.assertEqual(libc_open("", 0), -1)
        self.assertEqual(get_errno(), errno.ENOENT)

        self.assertEqual(set_errno(32), errno.ENOENT)
        self.assertEqual(get_errno(), 32)

        if threading:
            def _worker():
                set_errno(0)

                libc = CDLL(libc_name, use_errno=False)
                if os.name == "nt":
                    libc_open = libc._open
                else:
                    libc_open = libc.open
                libc_open.argtypes = c_char_p, c_int
                self.assertEqual(libc_open("", 0), -1)
                self.assertEqual(get_errno(), 0)

            t = threading.Thread(target=_worker)
            t.start()
            t.join()

            self.assertEqual(get_errno(), 32)
            set_errno(0)

    @unittest.skipUnless(os.name == "nt", 'Test specific to Windows')
    def test_GetLastError(self):
        dll = WinDLL("kernel32", use_last_error=True)
        GetModuleHandle = dll.GetModuleHandleA
        GetModuleHandle.argtypes = [c_wchar_p]

        self.assertEqual(0, GetModuleHandle("foo"))
        self.assertEqual(get_last_error(), 126)

        self.assertEqual(set_last_error(32), 126)
        self.assertEqual(get_last_error(), 32)

        def _worker():
            set_last_error(0)

            dll = WinDLL("kernel32", use_last_error=False)
            GetModuleHandle = dll.GetModuleHandleW
            GetModuleHandle.argtypes = [c_wchar_p]
            GetModuleHandle("bar")

            self.assertEqual(get_last_error(), 0)

        t = threading.Thread(target=_worker)
        t.start()
        t.join()

        self.assertEqual(get_last_error(), 32)

        set_last_error(0)

if __name__ == "__main__":
    unittest.main()


i start to feel emotional


i believe feeling duality suffering soul growth tells of an ending or a decline or a change of direction often one associated with emotions and it offers one possible response to that decline or change moving on


i hostage negotiator on her case has her feeling hopeful about her future


im feeling a little dirty


i can cope with his presence without feeling distressed if i can force myself into a quiet and resigned friendship


i had the feeling that it might not have been taken as the truthful and sincere compliment it would have been


i asked some girls what it meant to them to be valued and for the most part the response was that they felt valued when the people around them made them feel valued and treated them in a loving and caring manner


i feel if i completely hated things i d exercise my democratic right speak my mind in what ever ways possible and try to enact a change


i could almost feel her gentle touch in the moonbeam she sent to shine over me he added touching his face dreamily


i woke up very early this morning feeling joyful


early 2006 a probable date


If you are going to post something that has a link to the original author, why not just post the original instead of someone's copy?


Microsoft hates it's own products?
Who knew?


this looks interesting, but it's already aired, and it's not like there's streaming video, so what's the point?


I have nothing but good things to say about Dell Tech Support. Many a time I've called in a faulty part and had the replacement at the front door in two days with a box to ship the old one back. First class service if you ask me.


And by "Microsoft" you mean 4 employees out of 60,000 or so...


This is exactly the same behavior as the very early lisp dialects: they had dynamic scoping in the interpreter and lexical scoping in the interpreter.  I wonder if they knew about the history, or not?


[deleted]


Because this one is different and I like it better.  Here's your sign.


ok


illustrative embodiments of the invention will be described below in the context of a battery . however , it is to be understood that the encapsulation techniques and mechanisms described herein are more generally applicable to any power source for which it would be desirable to prevent harmful chemical leakage , reduce harm caused by ingestion , and / or other related harms caused by the power source and its components . fig1 illustrates an encapsulated battery system 100 . the system 100 includes a power source 102 having a set of power terminals 103 - 1 and 103 - 2 . in this embodiment , the power source 102 is a battery , by way of example only , a button or cylindrical type battery such as , but not limited to , a lithium cell battery . the power source 102 can also be a disposable battery or a rechargeable battery . in this example , power terminal 103 - 1 is the positively charged electrode of the battery or anode , while power terminal 103 - 2 is the negatively charged electrode of the battery or cathode . however , the power terminals can be reversed in alternate embodiments . furthermore , the power terminals do not have to be located on opposite sides of the battery as illustrated in fig1 but rather can be located in other locations on the battery . as further shown in the system 100 of fig1 , a cover 104 encapsulates the power source 102 as well as the set of power terminals 103 - 1 and 103 - 2 , thus sealing the power source 102 and the set of power terminals 103 - 1 and 103 - 2 within the cover 104 . in one embodiment , the material used for the cover 104 to encapsulate and seal the power source 102 and the set of power terminals 103 - 1 and 103 - 2 is a natural elastomer such as natural rubber or other natural polymer . in another embodiment , the cover material is a synthetic elastomer such as a synthetic rubber or other synthetic polymer . for example , the material is a rubber material or silicone gel material in certain illustrative embodiments . some of the advantages of elastomer materials include , but are not limited to , prevention of leakage of the battery chemicals into nature when they are thrown away instead of being recycled , as well as when they are ingested by a human or animal . the cover 104 can also be formed with a silk material that can be ingested without harm to the human or animal that ingests it . as is known , silk can be processed into various forms such as gels and films . as such , a gel or film - like silk material can be used to encapsulate and seal the power source 102 and the set of power terminals 103 - 1 and 103 - 2 . still further , the cover can be formed with an electrical conducting material that is harmless if swallowed by humans or animals , e . g ., gold , platinum or silver . in this case , the cover 104 could also have insulating material surrounding the power terminals 103 - 1 and 103 - 2 of the power source 102 or otherwise electrically separating the two terminals to prevent shorting of the anode and the cathode . as further shown in the system 100 of fig1 , a set of conductive contacts 106 - 1 and 106 - 2 are configured to pass through the cover 104 and contact the set of power terminals 103 - 1 and 103 - 2 , respectively , thus providing conductive access to the set of power terminals of the power source 102 from outside the cover without allowing exposure of the power source or the power terminals to an environment outside the cover 104 . this means that none of the harmful chemicals of the power source 102 are able to escape from the cover 104 when the power source leaks . note that the set of conductive contacts are made of an electrical conducting material , and are configured to be removable from the cover 104 without allowing exposure of the power source 102 or the set of power terminals 103 - 1 and 103 - 2 to the outside environment . in the embodiment shown in fig1 , the conductive contacts 106 - 1 and 106 - 2 are pin - shaped ( but can be pointed in shape in some other manner ) such that they penetrate the cover 104 but allow the cover to re - seal upon removal of one or more of the contacts . while two pin - shaped structures for each conductive contact are shown penetrating the cover 104 and contacting each of the power terminals ( 103 - 1 and 103 - 2 ), it is to be understood that more or less pin - shaped structures can be used to form each conductive contact . while the set of conductive contacts 106 - 1 and 106 - 2 are preferably removable from the system 100 , in an alternative embodiment , the conductive contacts are integrally - formed with the cover 104 . fig2 illustrates a conductive contact for an encapsulated battery system , according to an embodiment of the invention . recall that the system 100 of fig1 illustrates a set of conductive contacts 106 - 1 and 106 - 2 that are pin - shaped in form . in an alternate embodiment of a conductive contact 200 shown in fig2 , the conductive contact also includes an electrically conductive spring 201 in the form of an adjustable spiral structure . the spring 201 allows for compressive pressure to be put on the conductive contact and the corresponding power terminal ( 106 - 1 or 106 - 2 ) of the power source 102 in order to make a better electrical connection between the conductive contact 200 and the corresponding power terminal of the power source . the spring 201 is also configured to be able to penetrate the cover 104 , if needed for a given configuration , without exposing the power source or power terminals to the outside environment , both while installed and after being removed from the cover . fig3 illustrates an encapsulation structure for an encapsulated battery system , according to an embodiment of the invention . recall that the system 100 of fig1 illustrates a cover 104 that encapsulates the power source 102 as well as the set of power terminals 103 - 1 and 103 - 2 , thus sealing the power source 102 and the set of power terminals 103 - 1 and 103 - 2 within the cover . in one embodiment , a cover 300 is shown in fig3 . as mentioned , the cover can be made of various materials including , in one or more embodiments , a rubber material that encapsulates the power source and power terminals so as to seal the power source and power terminals from exposure to the outside environment . in one embodiment as shown in fig3 , a tyer 301 is included as part of the cover 300 . in this embodiment , the tyer 301 is an integral part of the cover structure that securely attaches the cover 300 to the power source . the tyer 301 , in one example , is made from the same rubber material as the cover with adhesive material on the portion of the tyer that comes into contact with the body of the power source . other tyer configurations are possible within the scope of alternate embodiment . whether or not the cover includes a tyer structure , it is to be appreciated that the power source and power terminals remain sealed from exposure to the outside environment once the power source is encapsulated within the cover . fig4 illustrates a methodology for forming and installing an encapsulated battery system , according to an embodiment of the invention . as shown in a methodology 400 , a battery ( one example of a power source and its power terminals ) is encapsulated in a rubber cover , in step 402 . one of ordinary skill in the art will realize various known rubber application processes for encapsulating and sealing a component such as a battery . it is assumed the conductive contacts ( e . g ., contacts such as shown as 200 in fig2 ) are installed by pressing the pin structures of the contact through the rubber cover in the vicinity of the power terminals of the battery . in step 404 , the contacts ( pins ) are adjusted to place the encapsulated battery in a compartment . the compartment may be , for example , the battery compartment of an electronic device that requires battery power for operation . in step 406 , the encapsulated battery is placed in the compartment . it is to be understood that when the conductive contacts each include a spring ( 201 in fig2 ), the springs are compressed on each side of the battery ( e . g ., contacts are compressed between the fingers of the installer ) so that the encapsulated battery can fit into the compartment . in step 408 , the contacts ( pins ) are released so that the contacts respectively connect with the electrical contacts of the electronic device ( located inside the compartment ). in step 410 , a check is made to verify that the battery is properly installed and sufficiently contacting the contacts of the electronic device . this may be verified by checking whether or not current is flowing through the battery , i . e ., check to see that the electronic device is getting the power it needs to operate . if yes , then the methodology ends at block 412 . however , if the electronic device is not getting the needed power from the battery , in step 414 , the encapsulated battery is removed and the penetration of the pins of the conductive contacts is increased through the rubber cover . this is to ensure that there is more sufficient contact between the conductive contacts and the power terminals of the battery sealed inside the rubber cover . once this is done , the methodology 400 returns to step 404 and repeats . it will be appreciated and should be understood that the exemplary embodiments of the invention described above can be implemented in a number of different fashions . given the teachings of the invention provided herein , one of ordinary skill in the related art will be able to contemplate other implementations of the invention . indeed , although illustrative embodiments of the present invention have been described herein with reference to the accompanying drawings , it is to be understood that the invention is not limited to those precise embodiments , and that various other changes and modifications may be made by one skilled in the art without departing from the scope or spirit of the invention .

a method comprising the steps of encapsulating a power source including a set of power terminals in a cover and sealing the power source including the set of power terminals within the cover and inserting a set of conductive contacts through the cover to contact the set of power terminals and provide conductive access to the set of power terminals of the power source from outside the cover without allowing exposure of the power source to an environment outside the cover .


fig1 schematically shows a longitudinal cross - sectional view of a portion of a pipe assembly 10 according to a preferred embodiment of the present invention . fig2 , 3 and 4 schematically show perspective views of pipe assembly 10 , with fig2 and 3 showing cut - away perspective views of the two longitudinal halves of pipe assembly 10 and fig4 showing an upstream view of pipe assembly 10 . pipe assembly 10 may transport fluids , such as steam flowing from a nuclear reactor . pipe assembly 10 includes a main pipe 12 , a standpipe 14 , a relief valve 16 ( omitted from fig2 to 4 for clarity ) and a scoop insert 18 . a first end 61 of standpipe 14 is coupled to main pipe 12 at an intersection 44 and a second end 62 of standpipe 14 is coupled to relief valve 16 . during normal operation , when a pressure in pipe assembly 10 is below a predetermined threshold of relief valve 16 and relief valve 16 is closed , steam in main pipe 12 flows from upstream of standpipe 14 to downstream of standpipe 14 . scoop insert 18 is arranged to extend into main pipe 12 and drive a small portion of steam flowing through main pipe 12 upward into standpipe 14 to closed relief valve 16 and back into main pipe 12 . the upwardly directed steam then recirculates back into the main pipe 12 , thereby disrupting vortex shedding past the inlet of standpipe 14 . scoop insert 18 includes a coupling portion 20 , which may be flange 20 , a body portion 22 , which in this embodiment has semi - cylindrical shape , and a scoop 24 . flange 20 may be fixed in between a flange 30 of standpipe 14 and a flange 32 of relief valve 16 . body portion 22 extends downwardly from flange 20 against an inner circumference 41 of standpipe 14 and connects scoop 24 to flange 20 , which couples scoop 24 to second end 62 of standpipe 14 . scoop 24 is positioned with a top end 34 of scoop 24 in standpipe 14 and a bottom end 36 of scoop 24 in main pipe 12 , so that scoop 24 is located at intersection 44 of standpipe 14 and main pipe 12 on an upstream side of standpipe 14 with respect to main pipe 12 and extends from within standpipe 14 into main pipe 12 . scoop 24 may include a front face 26 extending downward from body portion 22 having an opening 40 formed therein . in this embodiment , front face 26 is integral and flush with body portion 22 . scoop 24 also includes a channeling face 28 opposite of front face 26 extending from within standpipe 14 into main pipe 12 . channeling face 28 is positioned to channel steam flowing through main pipe 12 into standpipe 14 . channeling face 28 is substantially parallel with standpipe 14 at top end 34 and is angled with respect to standpipe 14 at bottom end 36 , so scoop 24 redirects steam flowing through main pipe 12 by approximately ninety degrees . in this embodiment , front face 26 has a semi - cylindrical shape and channeling face 28 has a semi - cylindrical shape at top end 34 . thus , at top end 34 , front face 26 has a convex shape with respect to channeling face 28 and channeling face 28 has a concave shape with respect to front face 26 . scoop 24 may also include channeling sides 27 , 29 connecting front face 26 and channeling face 28 that assist in directing steam from main pipe 12 to standpipe 14 . in a preferred embodiment , standpipe 14 is six inches in diameter and main pipe 12 is twenty - four inches in diameter . in alternative embodiment , flange 20 and body portion 22 may be omitted and scoop 24 may be directly coupled to at least one of main pipe 12 and standpipe 14 , for example by welding . fig5 and 6 show a downstream perspective view and side perspective view , respectively , of scoop insert 18 . flange 20 has evenly spaced holes 38 formed therein . fasteners such as bolts may be passed through holes 38 to secure flange 20 to at least one of standpipe 14 ( fig1 to 4 ) or relief valve 16 ( fig1 ). front face 26 extends downward from body portion 22 and has opening 40 defined therein for steam to enter and be directed upwards by channeling face 28 towards body portion 22 and flange 20 . channeling face 28 is parallel to body portion 22 at top end 34 , but extends downward and curves towards front face 26 at bottom end 36 . fig7 and 8 show a perspective upstream view and a perspective downstream view of a scoop insert 118 according to another embodiment of the present invention . scoop insert 118 may be inserted in standpipe 14 ( fig1 to 4 ) to direct steam from main pipe 12 ( fig1 to 4 ) into standpipe 14 in substantially the same manner as scoop insert 18 ( fig1 to 6 ). scoop insert 118 includes a flange 120 , a body portion 122 and a scoop 124 . scoop 124 includes a front face 126 , a channeling face 128 and channeling sides 127 , 129 . channeling sides 127 , 129 connect front face 126 and channeling face 128 and assist in directing steam from main pipe 12 ( fig1 to 4 ) to standpipe 14 ( fig1 to 4 ). body portion 122 extends downward from flange 120 to front face 126 at a top end 134 of scoop 124 , which curves away from body portion 122 at a bottom end 136 and protrudes past body portion 122 upstream in main pipe 12 ( fig1 to 4 ). at bottom end 136 , at least a portion of front face 126 may contact an inner circumference of main pipe 14 ( fig1 to 4 ). channeling sides 127 , 129 extend inwardly from front face 126 , connecting front face 126 with channeling face 128 . front face 126 , channeling face 128 and channeling sides 127 , 129 define an opening 140 for steam to flow through , which scoop 124 directs towards body portion 122 and flange 120 . at both ends 134 , 136 , opening 140 has a semi - annular shape . fig9 shows a top view of scoop insert 118 . top end 134 of scoop 124 is shown , with channeling sides 127 , 129 extending radially inward from front face 126 towards channeling face 128 . front face 126 has a convex shape with respect to channeling face 128 and channeling face 128 has a concave shape with respect to front face 126 . in the preceding specification , the invention has been described with reference to specific exemplary embodiments and examples thereof it will , however , be evident that various modifications and changes may be made thereto without departing from the broader spirit and scope of invention as set forth in the claims that follow . the specification and drawings are accordingly to be regarded in an illustrative manner rather than a restrictive sense .

a piping assembly for directing fluid and mitigating acoustic and vortex coupled resonance is provided that includes a main pipe delivering fluid in a first direction ; a standpipe coupled to the main pipe at an intersection ; and a scoop positioned at the intersection directing the fluid towards the standpipe . a scooping insert and a method for disrupting vortex shedding in a piping assembly are also provided .


an overall block diagram of a preferred embodiment of the present invention is shown in fig1 . the major components are an integrated circuit chip 110 , an external if filter 111 , a filter coefficient adjustment circuit 112 , an operating cycle timer 113 , and configuration changing gates 113a . the integrated circuit chip 110 includes thereon a radio receiver 110a , an on - chip filter 110c and a signal comparator 110b . the blocks shown in fig1 are not meant to show the actual layout of the components on the chip 110 since the layout of the chip can be conventional and it forms no part of this invention . the details of the radio receiver 110a and its associated external components are shown in fig6 and they will be explained in detail later . it is noted that what is generally termed an fm radio receiver includes if filters . herein for the sake of convenience the parts of the radio receiver on integrated chip 110 , that is , the radio receiver minus the if filter , is called a radio receiver . a key aspect of the present invention is that it reduces the number of external or off - chip components required . the invention is applicable to a receiver system that includes two if filters . with the present invention one of these filters , namely filter 110a , is implemented on - chip and the second filter 111 is an off - chip component . as will be explained later , the on - chip filter is made to conform to the off - chip filter prior to the activation of the receiver . while the on - chip filter may drift out of the acceptable range of specifications in a relatively short time , the receiver is only activated for a short period and during this period the on - chip filter 110a operates appropriately . the radio receiver 110a is designed for operation in a time slot paging system such as that shown in u . s . pat . no . 4 , 713 , 808 ( gaskill ) wherein the receiver is only active for very short periods , each active period being followed by a relative long period of inactivity . since the receiver is only active for very short periods , it uses relatively little power . this is important in applications such as where the radio receiver is part of a wristwatch where there are very severe power limitations . with the present invention the system operates with an operating cycle which has three portions : second : the receiver 110a is turned on for a short period . fig2 shows the relative length of the three portions of the operating cycle . key to the present invention is the fact that the first and second portions of the operating cycle are relatively short with respect to the third portion of the operating cycle . the length of the various portions of the operating cycle is shown in fig2 . the components within the system are connected in a different manner during the first and second portion of the operating cycle . fig3 shows how the components in the system are connected during the first portion of each operating cycle . fig4 shows how the components are connected during the second portion of each operating cycle . as shown in fig3 during the first portion of each operating cycle , the circuit is connected so that the on - chip filter 110c can be adjusted . during the first portion of each operating cycle , the frequency characteristics of on chip filter 110c are made to match the frequency characteristics of external filter 111 . this portion of the cycle requires approximately 4 . 3 milliseconds . after the first portion of each operating cycle , the on - chip filter 110c and the off - chip filter 111 are connected in series as shown in fig4 and the receiver is activated for approximately 33 milliseconds . as explained in the above referenced gaskill patent , while the receiver is only active for a short period of time , this is time enough to span one time slot in a time slot protocol . in the third , and relatively long portion of each operating cycle , the receiver is deactivated . fig5 shows the details of the on - chip filter 110c . on - chip filter 110c is a two pole filter which includes two coupled resonators 550a and 550b . the two resonators 550a and 550b are connected by a series coupling capacitor 550c . resonator 550a includes on - chip capacitors 501a and 502a , gyrator 503a , and variable resistor 504a . resonator 550b includes on - chip capacitors 501b and 502b , gyrator 503b and variable resistor 504b . the on - chip components shown in fig5 are connected in a conventional fashion to form a band pass filter . such filters are well know ; however , it is also well known that such on - chip gyrators working at 10 . 7 mhz are relatively unstable . that is , once they are adjusted to certain parameters , they will retain those values for only a short period of time . the present invention takes advantage of the fact that the receiver 110a is only active for a very short period , that is , for 33 milliseconds . thus , the parameters are adjusted during the first portion of each cycle and they only need retain their value for the 33 milliseconds that the receiver is active during the second portion of each cycle . unique to the invention is the fact that the parameters are automatically adjusted each time that the receiver 110 is activated . the particular adaptive algorithm used to adjust the parameters or gyrators 503a and 503b is not relevant to the present invention and such adjustment algorithms are known in the art . for example the algorithm shown in a paper by d . a . johns , w . m . snelgrove , and a . s . sedra entitled &# 34 ; continuous - time analog adaptive recursive filters &# 34 ; published in iscas 1989 pages 667 - 669 . as shown in fig3 during the first or &# 34 ; adjustment &# 34 ; portion of each operating cycle the antenna 116 is removed and the rf amplifier 22 is connected to a fixed voltage . mixer 28 and if amplifier 34 are connected in series , thus providing a &# 34 ; white noise &# 34 ; signal input to filters 110c and 111 . the output of filters 110c and 111 are compared by comparator 110b , and if they are not equal a signal is sent to adjustment circuit 112 . the adjustment process continues until both filters 110 and 111 produce the same output signal . at this point the on - chip filter 110c has the same frequency response as does external filter 111 and the first portion of each operating cycle ends . next the components are connected as shown in fig4 . the gates 113a for switching the connections are not specifically shown in fig3 and 4 since such gates can be conventional . the switching gates 113a are activated by cycle timer 13a as shown in fig1 . as shown in fig4 during the receive portion of each cycle , the components are connected as a receiver such as that shown in the previously referenced patent application . this connection will be explained in detail with reference to fig6 . the details of how receiver 110 is connected into the system during the second or &# 34 ; receive &# 34 ; portion of each cycle are shown in fig6 . the system as shown in fig6 includes an rf stage 10 , an if stage 12 and a baseband stage 14 . the rf stage 10 includes an antenna 116 which may be fabricated into the wristband 17 of the wristwatch 19 in which the receiver 8 is mounted . ( a suitable wristwatch enclosure is described in the gaskill et al patent ). the antenna 116 provides rf signals to an antenna tuner stage 18 . antenna tuner stage 18 is a conventional varactor controlled bandpass filter which also performs limited impedance match functions . a tuning voltage is applied to a tune voltage port 20 from a microprocessor based control system not shown earlier . such a microprocessor system is discussed in gaskill et al . the voltage supplied via port 20 tunes a voltage - variable capacitor in tuner 18 . the antenna tuner 18 also serves a limited impedance transformation function . the antenna 116 is typically a very small loop and consequently has a very small impedance . receiver performance and noise figure are optimized if this impedance is transformed up to more closely match the input impedance of the following rf amplifier stage 22 . rf amplifier stage 22 is a low noise broadband amplifier tuned for maximum gain in the fm broadcast band ( 88 - 108 megahertz ). the maximum gain of rf amplifier stage 22 is approximately 10 db . the actual gain is controlled by an agc control circuit discussed below . a receiver mixer stage 26 is provided with a wide band of amplified input signals . to minimize the effect of image signals which pass the tuner stage 18 , mixer stage 26 is configured in an image canceling topology . two individual quad mixers 28 and 30 are driven with quadrature local oscillator signals on lines 27 and 29 from a local oscillator synthesizer 31 . high side injection is used , so the local oscillator tunes the 98 . 7 to 118 . 7 megahertz range to yield a 10 . 7 megahertz intermediate frequency . the output of the mixer 28 driven from local oscillator line 27 is delayed 90 degrees and is combined with the output of the mixer 30 that is driven from the delayed local oscillator line 29 . the combination of these signals cancels any image response while reinforcing the desired signal response . mixer 26 has a conversion gain at the desired signal frequency of approximately 7 db . the output of mixer stage 26 is provided to an if chain 32 comprised of two if amplifiers 34 and 36 and ceramic band pass filters 111 and adaptive filter 110a . as shown in the previously referenced patent applied the filter 110 is of chip construction and may be of the sfec 10 . 7 series manufactured by murata . in accordance with the present invention only filter 40 is implemented using an ic chip . if amplifiers 34 and 36 have gains of approximately 20 db each and filters 38 and 49 have about 6 db each of loss . the if amplifiers 34 and 35 can be gain controlled , to optimize noise figure . the output of if chain 32 is provided to a synchronous , or coherent detector comprised of a mixer 49 injected with a 10 . 7 megahertz local oscillator signal . the synchronous detection process adds the side band signal voltage and the side band noise powers , resulting in a 3 db improvement in signal - to noise ratio . the technique also permits detection at a much lower signal level than would be possible if a limiter stage was employed . consequently , the if stage gain can be lower than would normally be the case , thereby reducing the risk of feedback . the local oscillator 48 which provides the 10 . 7 megahertz signal is locked to the frequency of the if by a feedback circuit 71 , discussed below . a 90 degree phase shift of the local oscillator signal by a phase shifter 47 causes the signal output by mixer 49 to an output line 51 to be proportional to the frequency of the signal modulating the 10 . 7 megahertz if . this baseband frequency modulated signal is fed to a low pass filter 52 and then to a baseband amplifier 53 . baseband amplifier 53 has a break point of about five kilohertz for discrimination against the left plus right fm stereo channel . the breakpoint also minimizes distortion caused by the main audio channel bleeding into the subcarrier channel . the high end rolloff breakpoint is at about 150 kilohertz . the output of the baseband amplifier 53 is provided to conventional decoder circuitry , as disclosed in the gaskill et al . patent . a second synchronous detector is also driven by the if chain 32 and provides an agc signal for application to the rf and if gain stages . this second synchronous detector again includes a mixer 60 , this one driven in phase with the 10 . 7 megahertz local oscillator signal . the output of this mixer 60 is thus related to the amplitude of the if signal and can be used to gain control preceding stages . the limiting stages found in most fm receivers were found disadvantageous in the present system . limiting does not benefit the receiver &# 39 ; s signal - to noise or signal - to - interference ratio due to the low modulation index of the subcarrier being decoded . consequently , the automatic gain control technique was employed . the agc circuitry 24 employed in the preferred embodiment of the present invention is disclosed in pending u . s . patent application ser . no . 07 / 146 , 446 of suter entitled &# 34 ; agc delay on an integrated circuit ,&# 34 ; the disclosure of which is incorporated herein by reference . an agc loop filter 70 is a single rc stage with a break point at about one kilohertz . all other bypassing of agc points is done with much higher break points so that the one pole is clearly dominant . radio receiver as shown herein is afc controlled in a relatively continual manner . afc is effected by a dc component on the feedback loop 71 produced by a synchronous detector 49 . an amplifier 74 is included to insure that the loop gain is high enough to control local oscillator drift . the afc loop controls two local oscillators : the synthesized local oscillator 31 used for high side rf injection and the 10 . 7 megahertz local oscillator 48 used by the synchronous detectors 49 and 60 . both oscillators respond to any dc component on the feedback loop 71 to adjust their frequencies to minimize the resulting dc output from synchronous detector 49 . the afc feature is included here not for threshold extension ( which is not viable with a low modulation index ), but to reduce cross - modulation of entertainment energy into the receiver &# 39 ; s subspectrum due to distortion in the filters 111 and 110b . afc of the synthesizer 31 can be disabled by a switch 72 , which can be operated to apply a fixed reference voltage to the synthesizer 31 instead of the afc signal . further details concerning the operation and system organization of the receiver shown in fig6 can be found in the previously referenced co - pending patent application . while the invention has been described with reference to a preferred embodiment thereof , it will be understood by those skilled in the art that various changes in form and details may be made without departing from the scope of the invention .

the present invention provides an improved single chip radio receiver which has less external components than do previous similar receivers . with the present invention the integrated circuit which includes the radio receiver also has an on - chip adaptive filter . the radio receiver is designed for use in a radio pager which is only active for a very short time slot during a relative long repeat cycle . thus the adaptive filter only need remain stable for a short period after its coefficients are adjusted to the desired values . the radio receiver includes an external filter which has the same frequency response as desired from the adaptive filter . immediately prior to activating the radio receiver , the circuit is activated to adjust the parameters of the adaptive filter so that the adaptive filter matches the external filter . the radio receiver is then activated using both filters in series thereby producing the desired radio reception . the adaptive filter quickly changes characteristics ; however , since the radio receiver is only active for a short period of time , operation of the system is not affected .


the following description of the preferred embodiment is merely exemplary in nature and is in no way intended to limit the invention , its application , or uses . referencing fig1 , a passenger compartment 10 of a golf car 12 is shown . the passenger compartment 10 includes a seat 14 , a floor 16 , and a dash panel 18 , steering wheel 20 , a brake pedal 22 , and an accelerator pedal 24 . a non - skid floor mat 30 , designed in accordance with the principles of the present invention , covers the floor 16 of the passenger compartment 10 . with particular reference to fig2 , 3 and 3 a , the non - skid floor mat 30 will be discussed in detail . the non - skid floor mat 30 is formed of an elastomeric material 32 having an outer perimeter 34 shaped to conform with the floor 16 of the passenger compartment 10 . the floor mate 30 has the advantages of which are discussed in further detail herein below , but may also be formed of alternate materials . the non - skid floor mat 30 may include a steering wheel aperture 36 , a brake pedal aperture 38 , and an accelerator pedal aperture 40 . a series of attachment apertures 42 are positioned about the perimeter 34 for enabling fixed attachment of the non - skid floor mat 30 to the floor 16 . the non - skid floor mat 30 further includes a first section 44 having a flat surface 46 and a second section 48 having a flat surface 50 with a plurality of protrusions , or nibs 52 , extending upward therefrom . it is anticipated , however , that the flat surfaces 46 , 50 are textured of either or both of the first and second sections 44 , 48 may be rough , or otherwise textured . as best seen in fig3 a , the nibs 52 are generally semi - spherical in form with a sufficient radius . however , it is anticipated that the nibs 52 may take any one of a number of forms including , but not limited to , conical , frusto - conical , pyramid , truncated , cylindrical and the like at the bottom . as discussed in further detail below , each nib 52 is formed to fit within recesses of a soft spike . with particular reference to fig4 through 6 , a typical soft spike 60 of a golf shoe is shown engaging the nibs 52 of the non - skid floor mat 30 . soft spike 60 described herein is one of a number of soft spike configurations known in the art . the soft spike 60 generally includes a conical body 62 having a threaded post 64 extending upward therefrom , for threaded attachment with a golf shoe sole 66 . a series of ribs 68 extend downward from a conical face 70 of the soft spike 60 , thereby forming recesses 72 . as the soft spike 60 contacts the non - skid floor mat 30 , the nibs 52 are received into the recesses 72 of the soft spike 60 , as seen in fig5 and 6 , and as shown in phantom in fig4 . in this manner , the non - skid floor mat 30 provides traction for the soft spikes 60 , promoting passenger safety and comfort . it should further be noted that application of sufficient downward force through the soft spike 60 ( e . g . when passenger is standing ) enables the ribs 68 to contact the flat surface 50 between the nibs 52 concurrent to the nibs 52 engaging the recesses 72 . in this manner , improved traction is provided . as discussed briefly above , the nibs 52 are preferably semi - spherical in form for efficiently fitting within the recesses 72 . however , it is anticipated that other forms of the nibs 52 would suffice to fit within the recesses 72 for providing traction . for example , as shown in fig6 , partially frusto - conical nibs 52 are one possibility . more importantly , however , the size and spacing of the nibs 52 must be appropriate for enabling sufficient engagement between the nibs 52 and soft spike 60 , provide clearance to prevent a tripping hazard , and providing clearance for cleanability . additionally , spacing of the nibs 52 must be appropriate to enable hard spikes ( not shown ) to contact the flat surface 50 . in this manner , the non - skid floor mat 30 provides traction for both hard spike and soft spike golf shoes . to that end , the nibs 52 have a center - to center distance no greater than 0 . 80 inches . the center - to - center distance ensures that at least two nibs 52 , and optionally four nibs 52 , engage the recesses 72 of the soft spike 60 . additionally , the center - to - center distance ensures that a hard spike may pass between the nibs 52 for contacting the flat surface 50 , as well as enabling easy cleaning of the non - skid floor mat 30 . for example , if the nibs 52 were positioned too close together it would be difficult to remove dirt and debris deposited therebetween . further , the nibs 52 preferably have a height within the range of 0 . 12 to 0 . 19 inches . this height range ensures that there is adequate engagement between the soft spike recesses 72 and the nibs 52 . if the nibs 52 are too low , the non - skid floor mat 30 would fail to provide adequate traction . on the other hand , if the nibs 52 are too high , a soft spike may not move smoothly over the enon 0 skid floor mater 30 . similarly to the center - to - center distance , the height of the nibs 52 influences the cleanability of the non - skid floor mat 30 . if the nibs 52 are too high , removal of dirt and debris from between the nibs 52 is hindered . both the height and spacing of the nibs 52 are limited to prevent grabbing of the passenger &# 39 ; s golf shoe . as mentioned above , the non - skid floor mat 30 is formed using an elastomer component . the elastomeric material 32 provides toughness and wear resistance to extend the service life of the non - skid floor mat 30 . as an elastomer , the non - skid floor mat 30 is resilient and deformable for enabling improved traction . in the case of a hard spike , the tip of the hard spike may engage the flat surface 50 between the nibs , thereby gripping the non - skid floor mat 30 to provide traction for the passenger . if , however , the hard spike contacts a nib 52 , the hard spike can similarly project into the nib 52 , providing traction regardless of whether direct contact with the flat surface 50 is achieved . with regard to a typical soft spike 60 , as the recesses 72 engage the nibs 52 , the nibs 52 are able to slightly deform under the applied force of the passenger , thereby increasing the contact surface between the soft spikes 60 and the nibs 52 , thus increasing the traction . additionally , nib deformation enables the soft spike 60 to engage the nibs 52 and concurrently contact the flat surface 50 . the description of the invention is merely exemplary in nature and , thus , variations that do not depart from the gist of the invention are intended to be within the scope of the invention . such variations are not to be regarded as a departure from the spirit and scope of the invention .

a non - skid floor mat for use in a golf car is provided to enable traction with one of a hard spike and a soft spike of a golf shoe . the non - skid floor mat includes a sheet of elastomeric material and nibs in the wall area of the mat . the nibs are sufficiently spaced from one another to enable one of direct contact of the hard spike with the sheet and contact of the soft spike with both the nibs and the sheet . preferably , the nibs have a height between 0 . 12 and 0 . 19 inches , and are offset from one another by a center to center distance of between 0 . 5 and 0 . 8 inches .


@_carmeloneto
Os 'cumpanhero' quebraram todas as regras.


@_iglira bom dia macaco branco haha


@_Ioen imagino...  ow mandei fazer um body opressor pra Duda! hahahaha


@_jujuba_lima E o sono... rs. Cheiros. Tb adorei!


Magnolia flower and leaf drawing illustration with line art on white backgrounds. Design decor for card, save the date, wedding invitation cards, poster royalty free illustration


A stretch of Diamond Lake Road collapsed Friday where Indian Creek flows under the pavement. The road remains closed between Gilmer Road and Route 83 in Long Grove.


Smack Apparel Milwaukee Baseball Fans. A Drinking Town with A Baseball Problem Navy T-Shirt (Sm-5X)


Calgary-based Canadian Pacific Railway said in a letter to Norfolk Southern's CEO that under the amended bid, his company's shareholders would own 47 per cent of the newly merged company, up from 41 per cent.


Top 100 Most-Creative Acrylic Nail Art Designs and Tutorials I remember when I was growing up that there wasn't a whole lot that women did with their nails. Usually you just painted on some conservative shade of polish for a clean look, and that Pretty Nail Designs, Colorful Nail Designs, Acrylic Nail Designs, Nail Art Designs, Summer Nail Designs, Peacock Nail Designs, Peacock Nails, Colorful Nails, Pink Gold Nails


A kitchen or kitchenette at Casa Viva


Line Tracking for an amount of time In this section you will modify the code for line tracking so it will go for a set amount of time.


Children reading books in the room vector


Juncos Racing's <PERSON> (32) rounds turn two during practice for the IndyCar Grand Prix at the Indianapolis Motor Speedway on Friday, May 11, 2018.


Craft The World screenshot, No-1


Shiels Jewellers inception 01 January 1945

Shiels Jewellers is an Australian jewellery retailer and was founded by Jack Shiels in Adelaide in 1945.


Assassin 's Creed II Roger Craig Smith character role Ezio Auditore da Firenze, Nolan North character role Desmond Miles

The framing story is set in the 21st century and follows Desmond Miles as Assassin 's Creed II relives the genetic memories of his ancestor Ezio Auditore da Firenze.


Cyclopites is a genus of aglaspidid arthropods that lived in shallow seas in what is now Wisconsin during Late Cambrian times.


Confessions from the David Galaxy Affair instance of Film

Dors performed the film's theme song over the opening titles.


The Planets ( 1999 TV series ) publication date 01 January 1999, narrator Samuel West

The series featured appearances from famous pioneering space scientists and explorers, and was narrated by Samuel West in the original 1999 edition, and Mark Halliley in the 2004 remastered edition.


Manny Diaz ( California politician ) occupation Politician, position held member of the California State Assembly, date of birth 04 July 1953

Manolo J. Diaz (born July 4, 1953 in San Francisco, California) is an American engineer and politician who served as a member of the California State Assembly from 2000 to 2004, representing the 23rd District.


Battle Magic ( novel ) follows Street Magic, genre Novel

The book follows Pierce's characters Briar Moss, Evumeimei Dingzai (nicknamed Evvy), and Rosethorn after the events of Battle Magic ( novel )'s 2001 novel Street Magic.


Ty Cobb (born 1950) is an American lawyer.


Peter Kelland educated at University of Cambridge

After two years in the Marines Peter Kelland began his studies at the University of Cambridge.


Autumn: u sewn anything?
Autumn: show me show me!! :D
Autumn: <file_gif>
Israel: no :(
Israel: haven't had the time yet  ;(
Autumn: ooh :(
Autumn: u need to have pririorities in life!
Autumn: like me - i haven't checked the tests for a month because the dress wouldn't sew itself :D
Israel: you've sewn a dres??
Israel: you didn't show it to me
Autumn: oh didn't i?
Autumn: there will be some photos on the site soon so you'll see it:)
Israel: sure will! can't wait!:D
Autumn: <file_other>
Autumn: haven't i showed you this?
Israel: noo!! it's wonderful!!
Autumn: thanks :)
Israel: can't wait to see the whole dress! :)


Joe: This job is wearing me up
Tim: Oh no! I thought you love it
Joe: I do, but because of it they give me more work
Sam: Shit, this sucks man, don't let it burn you out
Tim: Exactly, like my friend Terry
Joe: What did he do?
Tim: Quit eventually, but he had trouble sleeping, constantly tired, and turned out to have an ulcer
Joe: Fuck! I gotta slow down

Joe's job is wearing him up. Tim's friend Terry quit his job because he was burned out.


Leo: Check this out
Leo: <file_video>
Charlie: Whaaaaaaaat
Oliver: God
Oliver: What's that??
Leo: Seems like prank
Leo: But actually I dunno xD
Oliver: 03:24
Oliver: WTF
Leo: Hahahah, my fav part
Leo: Of that random crap
Oliver: People are so weird sometimes
Leo: I knew you'd like it xD
Charlie: Wellllllll I have mixed feelings :D:D
Leo: Hahahahah, wait till 05:24
Charlie: Omg, too much for me
Charlie: My eyes!!
Leo: Hahahahahah
Leo: xDDDDDD

Leo, Charlie and Oliver are watching a video with a bizarre prank. Charlie has ambivalent feelings. Leo and Oliver enjoy the video's weirdness very much especially moments 3:24 and 5:24.


Julie: hey guys... could you just talk to me for a bit? I just watched this Japanese horror movie and I'm home alone and a little uneasy (aka scared shitless)
Rose: Jesus, why on earth would you watch a Japanese horror, home alone at this hour?
Julie: Cause I'm a fucking moron?
Rose: Cause you're a fuckin moron.
Paula: 5 point for Gryffindor, my friend. But in your defense, I always thought you were quite unaffected by horror movies.
Julie: That's what I thought too!
Paula: So what kinda movie was it?
Julie: <file_other>
Rose: seems pretty generic
Julie: It's scarier than it looks.
Rose: you know that japanese horror are the worst ones, right?
Julie: I know that now.
Paula: If... you want me to come over I can.
Julie: omg really? <3
Paula: Yeah, sure, it's like 20 minutes by bike to your house, we can drink cocoa and watch "when harry met Sally" until we fall asleep ;)
Julie: Omg Thank you so much, I love you!
Rose: I wish I lived in your neighborhood :(
Paula: We can chip in for an Uber for you :D
Julie: Let's have a spontaneous sleepover :D
Rose: Oh, man it's late, but why the hell not.
Rose: I'll bring cookies for the cocoa :D
Julie: yay :D

Julie has just watched a Japanese horror. She's alone at home and really scared. Paula and Rose are going to come to her place for a spontaneous sleepover. They'll drink cocoa and watch "When Harry met Sally." Rose will bring cookies.


Kayla: what time are you going to bring her?
Kayla: was it 11am?
Katherine: hey, i guess so.
Katherine: i'll have to ask dad and get back to you later ok?
Kayla: ok
Katherine: why, is there a problem?
Kayla: noooo
Kayla: i'm just making sure:)
Kayla: it turned out i finish at 11
Kayla: so it will be even less problematic ;)
Katherine: ok :)
Katherine: yeah dad just texted me
Katherine: it's around 11
Kayla: ok

Katherine will bring her to Kayla around 11.


Jack: Cocktails later?
May: YES!!!
May: You read my mind...
Jack: Possibly a little tightly strung today?
May: Sigh... without question.
Jack: Thought so.
May: A little drink will help!
Jack: Maybe two!

Jack and May will drink cocktails later.


Lily: I need to rent a pop corn machine
Daniel: :D
Lily: for our office Christmas party
Daniel: very Christmasy
Lily: We will screen Love Actually :P
Daniel: oh I get it now
Lily: Do you know someone who rents them?
Daniel: I'll check!

Daniel will find out who rents a pop corn machines on Lily's request.


Jacob Zachar is an American actor whose roles include Russell "Rusty" Cartwright on the ABC Family TV Series Greek.


Frank Zagarino is an American actor, star of low budget action movies.


John Zaremba was an American actor most noted for supporting roles on science fiction films and television series.


Michael Zarnock is an American writer of collector guides and articles about Hot Wheels toy cars and accessories.


Adrian Zaw is an American actor best known for his role of Syrus Primoris on the SyFy channel television series The Resistance on the SyFy channel.


Terrance Zdunich  is an American artist,

Terrance Zdunich  is an American artist, singer, actor, writer, composer, producer, illustrator and storyboard artist.


Alfred Zeisler was an American-born German film producer, director, actor and screenwriter.


Enzo Zelocchi is an Italian/American, Hollywood film producer, actor and businessman.


John Zenda was an American actor who starred in films and on television.


John Zibell is an independent actor/writer/director who has worked in New York City and Regional Theater and film.


Which Family Guy episodes contain Doctor Who references?

Who executive producer Russell T. Davies), the character of Vince was portrayed as an avid Doctor Who fan, with references appearing many times throughout in the form of clips from the programme.


Without Luther's backing for the uprising, many rebels laid down their weapons; others felt betrayed.


The event was held on February 1, 2016 at SAP Center in San Jose.


Among whom was Genghis Khan's empire split after his death?

As a result, Genghis Khan and his empire have a fearsome reputation in local histories.


Which rival of the Mongols is suspected of inventing the story that Genghis Khan was murdered by a captured princess?

One chronicle from the early 17th century even relates the legend that the princess hid a small dagger and stabbed him, though some Mongol authors have doubted this version and suspected it to be an invention by the rival Oirads.


What is the translation of Siebengebirge?

This "Germanic Heroic Age" is reflected in medieval legend, such as the Nibelungenlied which tells of the hero Siegfried killing a dragon on the Drachenfels (Siebengebirge) ("dragons rock"), near Bonn at the Rhine and of the Burgundians and their court at Worms, at the Rhine and Kriemhild's golden treasure, which was thrown into the Rhine by Hagen.


Underbids happen when builders ask for too little money to complete the project.


What financial issue is notoriously prevalent in the construction field?

Fraud is a problem in many fields, but is notoriously prevalent in the construction field.


High in the halls of the kings who are gone
Jenny would dance with her ghosts
The ones she had lost and the ones she had found
And the ones who had loved her the most
The ones whod been gone for so very long
She couldnt remember their names
They spun her around on the damp old stone
Spun away all her sorrow and pain
And she never wanted to leave, never wanted to leave
Never wanted to leave, never wanted to leave
They danced through the day and into the night
Through the snow that swept through the hall
From winter to summer and winter again
Til the walls did crumble and fall
And she never wanted to leave, never wanted to leave
Never wanted to leave, never wanted to leave
And she never wanted to leave, never wanted to leave
Never wanted to leave, never wanted to leave
High in the halls of the kings who are gone
Jenny would dance with her ghosts
The ones she had lost and the ones she had found
And the ones who had loved her the most


Happiness hit her like a train on a track
Coming towards her, stuck still no turning back
She hid around corners, and she hid under beds
She killed it with kisses, and from it she fled
With every bubble she sank with a drink
And washed it away down the kitchen sink
The dog days are over
The dog days are done
The horses are coming
So you better run
Run fast for your mother, run fast for your father
Run for your children, for your sisters and brothers
Leave all your love and your longing behind
You cant carry it with you if you want to survive
The dog days are over
The dog days are done
Can you hear the horses?
Cause here they come
And I never wanted anything from you
Except everything you had
And what was left after that too, oh
Happiness hit her like a bullet in the back
Struck from a great height
By someone who should have known better than that
The dog days are over
The dog days are done
Can you hear the horses?
Cause here they come
Run fast for your mother, run fast for your father
Run for your children, for your sisters and brothers
Leave all your love and your longing behind
You cant carry it with you if you want to survive
The dog days are over
The dog days are done
Can you hear the horses?
Cause here they come
The dog days are over
The dog days are done
Can you hear the horses?
Cause here they come
The dog days are over
The dog days are gone
Can you hear the horses?
Cause here they come


Ooh, ooh, ooh, ooh-ooh, ooh
Ooh, ooh, ooh, ooh-ooh, ooh
Ooh, ooh, ooh, ooh-ooh, ooh
Ooh, ooh, ooh, ooh-ooh, ooh
At seventeen I started to starve myself
I thought that love was a kind of emptiness
And at least I understood then the hunger I felt
And I didnt have to call it loneliness
We all have a hunger
We all have a hunger
We all have a hunger
We all have a hunger
Tell me what you need
Oh, you look so free
The way you use your body, baby
Come on and work it for me
Dont let them get you down
Youre the best thing Ive seen
We never found the answer
But we knew one thing
We all have a hunger
We all have a hunger
We all have a hunger
We all have a hunger
And its Friday night and its kicking in
In that pink dress, theyre gonna crucify me
Oh and you in all your vibrant youth
How could anything bad ever happen to you?
You make a fool of death with your beauty
And for a moment
I thought that love was in the drugs
But the more I took, the more it took away
And I could never get enough
I thought that love was on the stage, give yourself to strangers
You dont have to be afraid
Then it tries to find a home
With people or when Im alone
Picking it apart
And staring at your phone
We all have a hunger
We all have a hunger
We all have a hunger
We all have a hunger
Tell me what you need
Oh, you look so free
The way you use your body, baby
Come on and work it for me
Dont let them get you down
Youre the best thing Ive seen
We never found the answer
But we knew one thing
We all have a hunger
We all have a hunger
We all have a hunger
We all have a hunger
And its Friday night and its kicking in
In that pink dress, theyre gonna crucify me
Oh and you in all your vibrant youth
How could anything bad ever happen to you?
You make a fool of death with your beauty
And for a moment I forget to worry


Regrets collect like old friends
Here to relive your darkest moments
I can see no way, I can see no way
And all of the ghouls come out to play
And every demon wants his pound of flesh
But I like to keep some things to myself
I like to keep my issues drawn
Its always darkest before the dawn
And Ive been a fool and Ive been blind
I can never leave the past behind
I can see no way, I can see no way
Im always dragging that horse around
All of his questions, such a mournful sound
Tonight Im gonna bury that horse in the ground
Cause I like to keep my issues drawn
But its always darkest before the dawn
Shake it out, shake it out
Shake it out, shake it out, oh whoa
Shake it out, shake it out
Shake it out, shake it out, oh whoa
And its hard to dance with a devil on your back
So shake him off, oh-whoa
And I am done with my graceless heart
So tonight Im gonna cut it out and then restart
Cause I like to keep my issues drawn
Its always darkest before the dawn
Shake it out, shake it out
Shake it out, shake it out, oh whoa
Shake it out, shake it out
Shake it out, shake it out, oh whoa
And its hard to dance with a devil on your back
So shake him off, oh whoa
And its hard to dance
With a devil on your back
And given half the chance
Would I take any of it back?
Its a fine romance
But its left me so undone
 Its always darkest before the dawn
Oh whoa
Oh whoa
And Im damned if I do and Im damned if I dont
So heres to drinks in the dark at the end of my rope
And Im ready to suffer and Im ready to hope
Its a shot in the dark aimed right at my throat
Cause looking for heaven, found the devil in me
Looking for heaven, found the devil in me
But, what the hell, Im gonna let it happen to me, yeah
Shake it out, shake it out
Shake it out, shake it out, oh whoa
Shake it out, shake it out
Shake it out, shake it out, oh whoa
And its hard to dance with a devil on your back
So shake him off, oh whoa
Shake it out, shake it out
Shake it out, shake it out, oh whoa
Shake it out, shake it out
Shake it out, shake it out, oh whoa
And its hard to dance with a devil on your back
So shake him off, oh whoa
 Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-oh-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-woah-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-oh-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-woah-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-oh-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-woah-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-oh-oh
Oh-oh-oh-oh
Oh-oh-oh-oh, oh-oh-oh-woah-oh


Drifting through the halls with the sunrise
Climbing up the walls for that flashing light
Cause Im gonna be free and Im gonna be fine
Cause Im gonna be free and Im gonna be fine
Now the sun is up and Im going blind
Another drink just to pass the time
Cause Im gonna be free and Im gonna be fine
Cause Im gonna be free and Im gonna be fine
Its a different kind of danger
And the bells are ringing out
And Im calling for my mother
As I pull the pillars down
Its a different kind of danger
And my feet are spinning round
Never knew I was a dancer
Til Delilah showed me how
Too fast for freedom
Sometimes it all falls down
These chains never leave me
I keep dragging them around
Now Im dancing with Delilah and her vision is mine
A different kind of danger in the daylight
Took anything to cut you, I can find
A different kind of a danger in the daylight
Now its one more boy and its one more line
Taking the pills just to pass the time
Cause Im gonna be free and Im gonna be fine
Cause Im gonna be free and Im gonna be fine
But maybe not tonight
Its a different kind of danger
And the bells are ringing out
And Im calling for my mother
As I pull the pillars down
Its a different kind of danger
And my feet are spinning round
Never knew I was a dancer
Til Delilah showed me how
Now Im dancing with Delilah and her vision is mine
A different kind of danger in the daylight
Took anything to cut you, I can find
A different kind of a danger in the daylight
Strung up, strung out for your love
Hanging, hung up, its so rough
Im wrung and wringing out
Why cant you let me know?
Strung up, strung out for your love
Hanging, hung up, its so rough
Im wrung and wringing out
Why cant you let me know?
Its a different kind of danger
And the bells are ringing out
And Im calling for my mother
As I pull the pillars down
Its a different kind of danger
And my feet are spinning round
Never knew I was a dancer
Til Delilah showed me how
Its a different kind of danger
And the bells are ringing out
And Im calling for my mother
As I pull the pillars down
Its a different kind of danger
And my feet are spinning around
Never knew I was a dancer
Til Delilah showed me how
Too fast for freedom
Sometimes it all falls down
These chains never leave me
I keep dragging them around
Too fast for freedom
Sometimes it all falls down
These chains never leave me
I keep dragging them around


How deeply are you sleeping or are you still awake?
A good friend told me youve been staying out so late
Be careful, oh, my darling, oh, be careful what it takes
From what Ive seen so far, the good ones always seem to break
And I was screaming at my father and you were screaming at me
And I can feel your anger from way across the sea
And I was kissing strangers, I was causing such a scene
Oh, the heart it hides such unimaginable things
Grab me by my ankles, Ive been flying for too long
I couldnt hide from the thunder in a sky full of song
And I want you so badly, but you could be anyone
I couldnt hide from the thunder in a sky full of song
Hold me down, Im so tired now
Aim your arrow at the sky
Take me down, Im too tired now
Leave me where I lie
And I can tell that Im in trouble when that music starts to play
In a city without seasons, it keeps raining in LA
I feel like Im about to fall, the room begins to sway
And I can hear the sirens but I cannot walk away
Grab me by my ankles, Ive been flying for too long
I couldnt hide from the thunder in a sky full of song
And I want you so badly, but you could be anyone
I couldnt hide from the thunder in a sky full of song
Hold me down, Im so tired now
Aim your arrow at the sky
Take me down, Im too tired now
Leave me where I lie
I thought I was flying but maybe Im dying tonight
I thought I was flying but maybe Im dying tonight
And I thought I was flying but maybe Im dying tonight
And I thought I was flying but maybe Im dying tonight
Hold me down, Im so tired now
Aim your arrow at the sky
Take me down, Im too tired now
Leave me where I lie
Hold me down, Im too tired now
Aim your arrow at the sky
And take me down, Im too tired now
Leave me where I lie


You need a big god
Big enough to hold your love
You need a big god
Big enough to fill you up
You keep me up at night
To my messages, you do not reply
You know I still like you the most
The best of the best and the worst of the worst
Well, you can never know
The places that I go
I still like you the most
Youll always be my favourite ghost
You need a big god
Big enough to hold your love
You need a big god
Big enough to fill you up
Sometimes I think its getting better
And then it gets much worse
Is it just part of the process?
Jesus Christ, it hurts
Though I know I should know better
Well, I can make this work
Is it just part of the process?
Jesus Christ, Jesus Christ, it hurts
You need a big god
Big enough to hold your love
You need a big god
Big enough to fill you up
Shower your affection, let it rain on me
Pull down the mountain, drag your cities to the sea
Shower your affection, let it rain on me
Dont leave me on this white cliff
Let it slide down to the, slide down to the sea
Slide down to the, slide down to the sea


Looking up from underneath
Fractured moonlight on the sea
Reflections still look the same to me
As before I went under
And its peaceful in the deep
Cathedral where you cannot breathe
No need to pray, no need to speak
Now I am under all
And its breaking over me
A thousand miles down to the sea bed
Found the place to rest my head
Never let me go, never let me go
Never let me go, never let me go
And the arms of the ocean are carrying me
And all this devotion was rushing out of me
And the crashes are heaven, for a sinner like me
But the arms of the ocean delivered me
Though the pressures hard to take
Its the only way I can escape
It seems a heavy choice to make
And now I am under, oh
And its breaking over me
A thousand miles down to the sea bed
Found the place to rest my head
Never let me go, never let me go
Never let me go, never let me go
And the arms of the ocean are carrying me
And all this devotion was rushing out of me
And the crashes are heaven, for a sinner like me
But the arms of the ocean delivered me
And its over and Im going under
But Im not giving up, Im just giving in
Im slipping underneath
So cold and so sweet
And the arms of the ocean so sweet and so cold
And all this devotion I never knew at all
And the crashes are heaven for a sinner released
And the arms of the ocean delivered me
Never let me go, never let me go
Never let me go, never let me go
Delivered me
Never let me go, never let me go
Never let me go, never let me go
Delivered me
Never let me go, never let me go
Never let me go, never let me go
Delivered me
Never let me go, never let me go
Never let me go, never let me go
And its over and Im going under
But Im not giving up, Im just giving in
Im slipping underneath
So cold and so sweet


A falling star fell from your heart and landed in my eyes
I screamed aloud, as it tore through them
And now its left me blind
The stars, the moon, they have all been blown out
You left me in the dark
No dawn, no day, Im always in this twilight
In the shadow of your heart
And in the dark, I can hear your heartbeat
I tried to find the sound
But then it stopped, and I was in the darkness
So darkness I became
The stars, the moon, they have all been blown out
You left me in the dark
No dawn, no day, Im always in this twilight
In the shadow of your heart
I took the stars from our eyes, and then I made a map
And knew that somehow I could find my way back
Then I heard your heart beating, you were in the darkness too
So I stayed in the darkness with you
The stars, the moon, they have all been blown out
You left me in the dark
No dawn, no day, Im always in this twilight
In the shadow of your heart
The stars, the moon, they have all been blown out
You left me in the dark
No dawn, no day, Im always in this twilight
In the shadow of your heart


I tried to leave it all behind me
But I woke up and there they were beside me
And I dont believe it but I guess its true
Some feelings, they can travel too
Oh there it is again, sitting on my chest
Makes it hard to catch my breath
I scramble for the light of change
Youre always on my mind
Youre always on my mind
And I never minded being on my own
Then something broke in me and I wanted to go home
To be where you are
But even closer to you, you seem so very far
And now Im reaching out with every note I sing
And I hope it gets to you on some pacific wind
Wraps itself around you and whispers in your ear
Tells you that I miss you and I wish that you were here
And if I stay, oh, I dont know
Therell be so much that Ill have to let go
Youre disappearing all the time
But I still see you in the light
For you, the shadows fight
And its beautiful but theres that tug inside
I must stop time traveling, youre always on my mind
Youre always on my mind
Youre always on my mind
And I never minded being on my own
Then something broke in me and I wanted to go home
To be where you are
But even closer to you, you seem so very far
And now Im reaching out with every note I sing
And I hope it gets to you on some pacific wind
Wraps itself around you and whispers in your ear
Tells you that I miss you and I wish that you were here
We all need something watching over us
Be it the falcons, the clouds or the cross
And then the sea swept in and left us all speechless
Speechless
And I never minded being on my own
Then something broke in me and I wanted to go home
To be where you are
But even closer to you, you seem so very far
And now Im reaching out with every note I sing
And I hope it gets to you on some pacific wind
Wraps itself around you and whispers in your ear
Tells you that I miss you and I wish that you were here
Wish that you were here
Wish that you were here
Wish that you were here
I wish that you...


/*
 * Copyright (C) 2011 by Nelson Elhage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <termios.h>
#include <signal.h>

#include "reptyr.h"

#ifndef __linux__
#error reptyr is currently Linux-only.
#endif

static int verbose = 0;

void _debug(const char *pfx, const char *msg, va_list ap) {

    if (pfx)
        fprintf(stderr, "%s", pfx);
    vfprintf(stderr, msg, ap);
    fprintf(stderr, "\n");
}

void die(const char *msg, ...) {
    va_list ap;
    va_start(ap, msg);
    _debug("[!] ", msg, ap);
    va_end(ap);

    exit(1);
}

void debug(const char *msg, ...) {

    va_list ap;

    if (!verbose)
        return;

    va_start(ap, msg);
    _debug("[+] ", msg, ap);
    va_end(ap);
}

void error(const char *msg, ...) {
    va_list ap;
    va_start(ap, msg);
    _debug("[-] ", msg, ap);
    va_end(ap);
}

void setup_raw(struct termios *save) {
    struct termios set;
    if (tcgetattr(0, save) < 0)
        die("Unable to read terminal attributes: %m");
    set = *save;
    cfmakeraw(&set);
    if (tcsetattr(0, TCSANOW, &set) < 0)
        die("Unable to set terminal attributes: %m");
}

void resize_pty(int pty) {
    struct winsize sz;
    if (ioctl(0, TIOCGWINSZ, &sz) < 0)
        return;
    ioctl(pty, TIOCSWINSZ, &sz);
}

int writeall(int fd, const void *buf, ssize_t count) {
    ssize_t rv;
    while (count > 0) {
        rv = write(fd, buf, count);
        if (rv < 0) {
            if (errno == EINTR)
                continue;
            return rv;
        }
        count -= rv;
        buf += rv;
    }
    return 0;
}

volatile sig_atomic_t winch_happened = 0;

void do_winch(int signal) {
    winch_happened = 1;
}

void do_proxy(int pty) {
    char buf[4096];
    ssize_t count;
    fd_set set;
    while (1) {
        if (winch_happened) {
            winch_happened = 0;
            /*
             * FIXME: If a signal comes in after this point but before
             * select(), the resize will be delayed until we get more
             * input. signalfd() is probably the cleanest solution.
             */
            resize_pty(pty);
        }
        FD_ZERO(&set);
        FD_SET(0, &set);
        FD_SET(pty, &set);
        if (select(pty+1, &set, NULL, NULL, NULL) < 0) {
            if (errno == EINTR)
                continue;
            fprintf(stderr, "select: %m");
            return;
        }
        if (FD_ISSET(0, &set)) {
            count = read(0, buf, sizeof buf);
            if (count < 0)
                return;
            writeall(pty, buf, count);
        }
        if (FD_ISSET(pty, &set)) {
            count = read(pty, buf, sizeof buf);
            if (count < 0)
                return;
            writeall(1, buf, count);
        }
    }
}

void usage(char *me) {
    fprintf(stderr, "Usage: %s [-s] PID\n", me);
    fprintf(stderr, "       %s -l|-L [COMMAND [ARGS]]\n", me);
    fprintf(stderr, "  -l    Create a new pty pair and print the name of the slave.\n");
    fprintf(stderr, "           if there are command-line arguments after -l\n");
    fprintf(stderr, "           they are executed with REPTYR_PTY set to path of pty.\n");
    fprintf(stderr, "  -L    Like '-l', but also redirect the child's stdio to the slave.\n");
    fprintf(stderr, "  -s    Attach fds 0-2 on the target, even if it is not attached to a tty.\n");
    fprintf(stderr, "  -h    Print this help message and exit.\n");
    fprintf(stderr, "  -v    Print the version number and exit.\n");
    fprintf(stderr, "  -V    Print verbose debug output.\n");
}

void check_yama_ptrace_scope(void) {
    int fd = open("/proc/sys/kernel/yama/ptrace_scope", O_RDONLY);
    if (fd >= 0) {
        char buf[256];
        int n;
        n = read(fd, buf, sizeof buf);
        close(fd);
        if (n > 0) {
            if (!atoi(buf)) {
                return;
            }
        }
    } else if (errno == ENOENT)
        return;
    fprintf(stderr, "The kernel denied permission while attaching. If your uid matches\n");
    fprintf(stderr, "the target's, check the value of /proc/sys/kernel/yama/ptrace_scope.\n");
    fprintf(stderr, "For more information, see /etc/sysctl.d/10-ptrace.conf\n");
}

int main(int argc, char **argv) {
    struct termios saved_termios;
    struct sigaction act;
    int pty;
    int arg = 1;
    int do_attach = 1;
    int force_stdio = 0;
    int unattached_script_redirection = 0;

    if (argc < 2) {
        usage(argv[0]);
        return 2;
    }
    if (argv[arg][0] == '-') {
        switch(argv[arg][1]) {
        case 'h':
            usage(argv[0]);
            return 0;
        case 'l':
            do_attach = 0;
            break;
        case 'L':
            do_attach = 0;
            unattached_script_redirection = 1;
            break;
        case 's':
            arg++;
            force_stdio = 1;
            break;
        case 'v':
            printf("This is reptyr version %s.\n", REPTYR_VERSION);
            printf(" by Nelson Elhage <nelhage@nelhage.com>\n");
            printf("http://github.com/nelhage/reptyr/\n");
            return 0;
        case 'V':
            arg++;
            verbose = 1;
            break;
        default:
            usage(argv[0]);
            return 1;
        }
    }

    if (do_attach && arg >= argc) {
        fprintf(stderr, "%s: No pid specified to attach\n", argv[0]);
        usage(argv[0]);
        return 1;
    }

    if ((pty = open("/dev/ptmx", O_RDWR|O_NOCTTY)) < 0)
        die("Unable to open /dev/ptmx: %m");
    if (unlockpt(pty) < 0)
        die("Unable to unlockpt: %m");
    if (grantpt(pty) < 0)
        die("Unable to grantpt: %m");

    if (do_attach) {
        pid_t child = atoi(argv[arg]);
        int err;
        if ((err = attach_child(child, ptsname(pty), force_stdio))) {
            fprintf(stderr, "Unable to attach to pid %d: %s\n", child, strerror(err));
            if (err == EPERM) {
                check_yama_ptrace_scope();
            }
            return 1;
        }
    } else {
        printf("Opened a new pty: %s\n", ptsname(pty));
        fflush(stdout);
        if (argc > 2) {
            if(!fork()) {
                setenv("REPTYR_PTY", ptsname(pty), 1);
                if (unattached_script_redirection) {
                    int f;
                    setpgid(0, getppid());
                    setsid();
                    f = open(ptsname(pty), O_RDONLY, 0); dup2(f, 0);            close(f);
                    f = open(ptsname(pty), O_WRONLY, 0); dup2(f, 1); dup2(f,2); close(f);
                }
                close(pty);
                execvp(argv[2], argv+2);
                exit(1);
            }
        }
    }

    setup_raw(&saved_termios);
    memset(&act, 0, sizeof act);
    act.sa_handler = do_winch;
    act.sa_flags   = 0;
    sigaction(SIGWINCH, &act, NULL);
    resize_pty(pty);
    do_proxy(pty);
    tcsetattr(0, TCSANOW, &saved_termios);

    return 0;
}


/*
 * Copyright (C) 2011 by Nelson Elhage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <sys/types.h>
#include <dirent.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <signal.h>
#include <limits.h>
#include <time.h>
#include <sys/time.h>
#include <sys/stat.h>

#include "ptrace.h"
#include "reptyr.h"

#define TASK_COMM_LENGTH 16
struct proc_stat {
    pid_t pid;
    char comm[TASK_COMM_LENGTH+1];
    char state;
    pid_t ppid, sid, pgid;
    dev_t ctty;
};

#define do_syscall(child, name, a0, a1, a2, a3, a4, a5) \
    ptrace_remote_syscall((child), ptrace_syscall_numbers((child))->nr_##name, \
                          a0, a1, a2, a3, a4, a5)

int parse_proc_stat(int statfd, struct proc_stat *out) {
    char buf[1024];
    int n;
    unsigned dev;
    lseek(statfd, 0, SEEK_SET);
    if (read(statfd, buf, sizeof buf) < 0)
        return errno;
    n = sscanf(buf, "%d (%16[^)]) %c %d %d %d %u",
               &out->pid, out->comm,
               &out->state, &out->ppid, &out->sid,
               &out->pgid, &dev);
    if (n == EOF)
        return errno;
    if (n != 7) {
        return EINVAL;
    }
    out->ctty = dev;
    return 0;
}

int read_proc_stat(pid_t pid, struct proc_stat *out) {
    char stat_path[PATH_MAX];
    int statfd;
    int err;

    snprintf(stat_path, sizeof stat_path, "/proc/%d/stat", pid);
    statfd = open(stat_path, O_RDONLY);
    if (statfd < 0) {
        error("Unable to open %s: %s", stat_path, strerror(errno));
        return -statfd;
    }

    err = parse_proc_stat(statfd, out);
    close(statfd);
    return err;
}

static void do_unmap(struct ptrace_child *child, child_addr_t addr, unsigned long len) {
    if (addr == (unsigned long)-1)
        return;
    do_syscall(child, munmap, addr, len, 0, 0, 0, 0);
}

int *get_child_tty_fds(struct ptrace_child *child, int statfd, int *count) {
    struct proc_stat child_status;
    struct stat tty_st, st;
    char buf[PATH_MAX];
    int n = 0, allocated = 0;
    int *fds = NULL;
    DIR *dir;
    struct dirent *d;
    int *tmp = NULL;

    debug("Looking up fds for tty in child.");
    if ((child->error = parse_proc_stat(statfd, &child_status)))
        return NULL;

    debug("Resolved child tty: %x", (unsigned)child_status.ctty);

    if (stat("/dev/tty", &tty_st) < 0) {
        child->error = errno;
        error("Unable to stat /dev/tty");
        return NULL;
    }

    snprintf(buf, sizeof buf, "/proc/%d/fd/", child->pid);
    if ((dir = opendir(buf)) == NULL)
        return NULL;
    while ((d = readdir(dir)) != NULL) {
        if (d->d_name[0] == '.') continue;
        snprintf(buf, sizeof buf, "/proc/%d/fd/%s", child->pid, d->d_name);
        if (stat(buf, &st) < 0)
            continue;

        if (st.st_rdev == child_status.ctty
            || st.st_rdev == tty_st.st_rdev) {
            if (n == allocated) {
                allocated = allocated ? 2 * allocated : 2;
                tmp = realloc(fds, allocated * sizeof *tmp);
                if (tmp == NULL) {
                  child->error = errno;
                  error("Unable to allocate memory for fd array.");
                  free(fds);
                  fds = NULL;
                  goto out;
                }
                fds = tmp;
            }
            debug("Found an alias for the tty: %s", d->d_name);
            fds[n++] = atoi(d->d_name);
        }
    }
 out:
    *count = n;
    closedir(dir);
    return fds;
}

void move_process_group(struct ptrace_child *child, pid_t from, pid_t to) {
    DIR *dir;
    struct dirent *d;
    pid_t pid;
    char *p;
    int err;

    if ((dir = opendir("/proc/")) == NULL)
        return;

    while ((d = readdir(dir)) != NULL) {
        if (d->d_name[0] == '.') continue;
        pid = strtol(d->d_name, &p, 10);
        if (*p) continue;
        if (getpgid(pid) == from) {
            debug("Change pgid for pid %d", pid);
            err = do_syscall(child, setpgid, pid, to, 0, 0, 0, 0);
            if (err < 0)
                error(" failed: %s", strerror(-err));
        }
    }
    closedir(dir);
}

int do_setsid(struct ptrace_child *child) {
    int err = 0;
    struct ptrace_child dummy;

    err = do_syscall(child, fork, 0, 0, 0, 0, 0, 0);
    if (err < 0)
        return err;

    debug("Forked a child: %ld", child->forked_pid);

    err = ptrace_finish_attach(&dummy, child->forked_pid);
    if (err < 0)
        goto out_kill;

    dummy.state = ptrace_after_syscall;
    memcpy(&dummy.user, &child->user, sizeof child->user);
    if (ptrace_restore_regs(&dummy)) {
        err = dummy.error;
        goto out_kill;
    }

    err = do_syscall(&dummy, setpgid, 0, 0, 0, 0, 0, 0);
    if (err < 0) {
        error("Failed to setpgid: %s", strerror(-err));
        goto out_kill;
    }

    move_process_group(child, child->pid, dummy.pid);

    err = do_syscall(child, setsid, 0, 0, 0, 0, 0, 0);
    if (err < 0) {
        error("Failed to setsid: %s", strerror(-err));
        move_process_group(child, dummy.pid, child->pid);
        goto out_kill;
    }

    debug("Did setsid()");

 out_kill:
    kill(dummy.pid, SIGKILL);
    ptrace_detach_child(&dummy);
    ptrace_wait(&dummy);
    do_syscall(child, wait4, dummy.pid, 0, WNOHANG, 0, 0, 0);
    return err;
}

int ignore_hup(struct ptrace_child *child, unsigned long scratch_page) {
    int err;
    if (ptrace_syscall_numbers(child)->nr_signal != -1) {
        err = do_syscall(child, signal, SIGHUP, (unsigned long)SIG_IGN, 0, 0, 0, 0);
    } else {
        struct sigaction act = {
            .sa_handler = SIG_IGN,
        };
        err = ptrace_memcpy_to_child(child, scratch_page,
                                     &act, sizeof act);
        if (err < 0)
            return err;
        err = do_syscall(child, rt_sigaction,
                         SIGHUP, scratch_page,
                         0, 8, 0, 0);
    }
    return err;
}

/*
 * Wait for the specific pid to enter state 'T', or stopped. We have to pull the
 * /proc file rather than attaching with ptrace() and doing a wait() because
 * half the point of this exercise is for the process's real parent (the shell)
 * to see the TSTP.
 *
 * In case the process is masking or ignoring SIGTSTP, we time out after a
 * second and continue with the attach -- it'll still work mostly right, you
 * just won't get the old shell back.
 */
void wait_for_stop(pid_t pid, int fd) {
    struct timeval start, now;
    struct timespec sleep;
    struct proc_stat st;

    gettimeofday(&start, NULL);
    while (1) {
        gettimeofday(&now, NULL);
        if ((now.tv_sec > start.tv_sec && now.tv_usec > start.tv_usec)
            || (now.tv_sec - start.tv_sec > 1)) {
            error("Timed out waiting for child stop.");
            break;
        }
        /*
         * If anything goes wrong reading or parsing the stat node, just give
         * up.
         */
        if (parse_proc_stat(fd, &st))
            break;
        if (st.state == 'T')
            break;

        sleep.tv_sec  = 0;
        sleep.tv_nsec = 10000000;
        nanosleep(&sleep, NULL);
    }
}

int copy_tty_state(pid_t pid, const char *pty) {
    char buf[PATH_MAX];
    int fd, err = EINVAL;
    struct termios tio;
    int i;

    for (i = 0; i < 3 && err; i++) {
        err = 0;
        snprintf(buf, sizeof buf, "/proc/%d/fd/%d", pid, i);

        if ((fd = open(buf, O_RDONLY)) < 0) {
            err = -fd;
            continue;
        }

        if (!isatty(fd)) {
            err = ENOTTY;
            goto retry;
        }

        if (tcgetattr(fd, &tio) < 0) {
            err = -errno;
        }
    retry:
        close(fd);
    }

    if (err)
        return err;

    if ((fd = open(pty, O_RDONLY)) < 0)
        return -errno;

    if (tcsetattr(fd, TCSANOW, &tio) < 0)
        err = errno;
    close(fd);
    return -err;
}

int check_pgroup(pid_t target) {
    pid_t pg;
    DIR *dir;
    struct dirent *d;
    pid_t pid;
    char *p;
    int err = 0;
    struct proc_stat pid_stat;

    debug("Checking for problematic process group members...");

    pg = getpgid(target);
    if (pg < 0) {
        error("Unable to get pgid (does process %d exist?)", (int)target);
        return pg;
    }

    if ((dir = opendir("/proc/")) == NULL)
        return errno;

    while ((d = readdir(dir)) != NULL) {
        if (d->d_name[0] == '.') continue;
        pid = strtol(d->d_name, &p, 10);
        if (*p) continue;
        if (pid == target) continue;
        if (getpgid(pid) == pg) {
            /*
             * We are actually being somewhat overly-conservative here
             * -- if pid is a child of target, and has not yet called
             * execve(), reptyr's setpgid() strategy may suffice. That
             * is a fairly rare case, and annoying to check for, so
             * for now let's just bail out.
             */
            if ((err = read_proc_stat(pid, &pid_stat))) {
                memcpy(pid_stat.comm, "???", 4);
            }
            error("Process %d (%.*s) shares %d's process group. Unable to attach.\n"
                  "(This most commonly means that %d has a suprocesses).",
                  (int)pid, TASK_COMM_LENGTH, pid_stat.comm, (int)target, (int)target);
            err = EINVAL;
            goto out;
        }
    }
 out:
    closedir(dir);
    return err;
}

int attach_child(pid_t pid, const char *pty, int force_stdio) {
    struct ptrace_child child;
    unsigned long scratch_page = -1;
    int *child_tty_fds = NULL, n_fds, child_fd, statfd;
    int i;
    int err = 0;
    long page_size = sysconf(_SC_PAGE_SIZE);
    char stat_path[PATH_MAX];
    long mmap_syscall;

    if ((err = check_pgroup(pid))) {
        return err;
    }

    if ((err = copy_tty_state(pid, pty))) {
        if (err == ENOTTY && !force_stdio) {
            error("Target is not connected to a terminal.\n"
                  "    Use -s to force attaching anyways.");
            return err;
        }
    }

    snprintf(stat_path, sizeof stat_path, "/proc/%d/stat", pid);
    statfd = open(stat_path, O_RDONLY);
    if (statfd < 0) {
        error("Unable to open %s: %s", stat_path, strerror(errno));
        return -statfd;
    }

    kill(pid, SIGTSTP);
    wait_for_stop(pid, statfd);

    if (ptrace_attach_child(&child, pid)) {
        err = child.error;
        goto out_cont;
    }

    if (ptrace_advance_to_state(&child, ptrace_at_syscall)) {
        err = child.error;
        goto out_detach;
    }
    if (ptrace_save_regs(&child)) {
        err = child.error;
        goto out_detach;
    }

    mmap_syscall = ptrace_syscall_numbers(&child)->nr_mmap2;
    if (mmap_syscall == -1)
        mmap_syscall = ptrace_syscall_numbers(&child)->nr_mmap;
    scratch_page = ptrace_remote_syscall(&child, mmap_syscall, 0,
                                         page_size, PROT_READ|PROT_WRITE,
                                         MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);

    if (scratch_page > (unsigned long)-1000) {
        err = -(signed long)scratch_page;
        goto out_unmap;
    }

    debug("Allocated scratch page: %lx", scratch_page);

    if (force_stdio) {
        child_tty_fds = malloc(3 * sizeof(int));
        if (!child_tty_fds) {
            err = ENOMEM;
            goto out_unmap;
        }
        n_fds = 3;
        child_tty_fds[0] = 0;
        child_tty_fds[1] = 1;
        child_tty_fds[2] = 2;
    } else {
        child_tty_fds = get_child_tty_fds(&child, statfd, &n_fds);
        if (!child_tty_fds) {
            err = child.error;
            goto out_unmap;
        }
    }

    if (ptrace_memcpy_to_child(&child, scratch_page, pty, strlen(pty)+1)) {
        err = child.error;
        error("Unable to memcpy the pty path to child.");
        goto out_free_fds;
    }

    child_fd = do_syscall(&child, open,
                          scratch_page, O_RDWR|O_NOCTTY,
                          0, 0, 0, 0);
    if (child_fd < 0) {
        err = child_fd;
        error("Unable to open the tty in the child.");
        goto out_free_fds;
    }

    debug("Opened the new tty in the child: %d", child_fd);

    err = ignore_hup(&child, scratch_page);
    if (err < 0)
        goto out_close;

    err = do_syscall(&child, getsid, 0, 0, 0, 0, 0, 0);
    if (err != child.pid) {
        debug("Target is not a session leader, attempting to setsid.");
        err = do_setsid(&child);
    } else {
        do_syscall(&child, ioctl, child_tty_fds[0], TIOCNOTTY, 0, 0, 0, 0);
    }
    if (err < 0)
        goto out_close;

    err = do_syscall(&child, ioctl, child_fd, TIOCSCTTY, 0, 0, 0, 0);
    if (err < 0) {
        error("Unable to set controlling terminal.");
        goto out_close;
    }

    debug("Set the controlling tty");

    for (i = 0; i < n_fds; i++)
        do_syscall(&child, dup2, child_fd, child_tty_fds[i], 0, 0, 0, 0);

    err = 0;

 out_close:
    do_syscall(&child, close, child_fd, 0, 0, 0, 0, 0);
 out_free_fds:
    free(child_tty_fds);

 out_unmap:
    do_unmap(&child, scratch_page, page_size);

    ptrace_restore_regs(&child);
 out_detach:
    ptrace_detach_child(&child);

    if (err == 0) {
        kill(child.pid, SIGSTOP);
        wait_for_stop(child.pid, statfd);
    }
    kill(child.pid, SIGWINCH);
 out_cont:
    kill(child.pid, SIGCONT);
    close(statfd);

    return err < 0 ? -err : err;
}