text:
{-# OPTIONS_GHC -Wall #-}
--
-- Text/Patch.hs - Patch file manipulation module
--
-- Copyright (C) 2008, Hiroki Hattori
-- Licensed under BSD3, see COPYING
--
module Text.Patch (
                   Hunk, Diff, Patch (..),
                   diff, diffFile, formatDiff, readDiff,
--                   mkChangeset,
                  ) where

import Control.Monad ((>=>))
import Data.Maybe
import Data.List (span, partition)
import IO
import System.Directory (doesFileExist)
import Text.Regex

import qualified Data.Diff (Hunk, Diff (..), pathToDiff, hunkOldList, hunkNewList)
import qualified Data.Diff.Algorithm.ONP (genericDiff)

type Hunk = Data.Diff.Hunk String
type Diff = Data.Diff.Diff String

data Patch = Patch {
      patchOldName    :: String,
      patchNewName    :: String,
      patchBody       :: [Diff]
    }

-- | 文字列のリストの間の差分を取得する
diff :: Maybe Int -> [String] -> [String] -> [Diff]
diff cl oldlist newlist =
    Data.Diff.pathToDiff cl oldlist newlist $ Data.Diff.Algorithm.ONP.genericDiff (==) oldlist newlist

-- | ファイル間の差分を取得する
diffFile :: Maybe Int -> FilePath -> FilePath -> IO [Diff]
diffFile cmnlen oldfname newfname =
    do
      withf2 oldfname newfname
                 (\old new -> return $! Data.Diff.pathToDiff cmnlen old new $ Data.Diff.Algorithm.ONP.genericDiff (==) old new)
    where
      withf2 path1 path2 f = withf path1 (\txt1 -> withf path2 (\txt2 -> f txt1 txt2))
      withf path f =
          doesFileExist path >>= (\b -> if b
                                   then bracket (openFile path ReadMode) hClose (hGetContents >=> f .lines)
                                   else f [])

-- | 差分を書式化する
formatDiff :: Diff -> [String]
formatDiff (Data.Diff.Diff n m hunks) =
    (concat [ "@@ -", show $ n + 1, ",", show (sum $ map (length . Data.Diff.hunkOldList) hunks),
                        " +", show $ m + 1, ",", show (sum $ map (length . Data.Diff.hunkNewList) hunks), " @@" ]) : (concatMap f' hunks)
    where
      f' x = case x of
               Right xs      -> map ((:) ' ') xs
               Left (xs, ys) -> map ((:) '-') xs ++ map ((:) '+') ys

-- |
readHunk :: [String] -> Maybe (Hunk, [String])
readHunk xs | not $ null cmn = Just (Right (map tail cmn), xs')
            | not $ null edt = Just (Left ((map tail del), (map tail ins)), xs'')
            | otherwise      = Nothing
    where (cmn, xs') = span ((==) ' ' . head) xs
          (edt, xs'') = span (flip elem "+-" . head) xs'
          (ins, del) = partition ((==) '+' . head) edt

-- | 差分をパースする
readDiff :: [String] -> Maybe (Diff, [String])
readDiff [] = Nothing
readDiff (x:xs') = matchRegex (mkRegex "^@@ -([0-9]+),([0-9]+) \\+([0-9]+),([0-9]+) @@$") x
                   >>= return . map read
                   >>= (\(h1:h2:h3:h4:[]) -> if oldlen == h2 && newlen == h4
                                             then return (Data.Diff.Diff h1 h3 hunks, xs'')
                                             else error "Hunk length missmatch")
    where (xs'', hunks') = readHunks xs' []
          hunks = reverse hunks'
          oldlen = sum $ map (length . Data.Diff.hunkOldList) hunks
          newlen = sum $ map (length . Data.Diff.hunkNewList) hunks
          readHunks xs ys = case readHunk xs of
                              Nothing         -> (xs, ys)
                              Just (hnk, xs''') -> readHunks xs''' $! hnk : ys

redpajama_set_name: RedPajamaGithub


text:
exports.tests = [
    {
        name: 'font size',
        points: 1,
        func: function () {
            return $('#wrapper .menu li a').css('font-size');
        },
        expected: '16px',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'font family',
        points: 1,
        func: function () {
            return $('#wrapper .menu li a').css('font-family');
        },
        expected: "Constantina, Georgia, 'Nimbus Roman No9 L', serif",
        compare: 'equal',
        compareParam: null
    }, {
        name: 'width',
        points: 1,
        func: function () {
            return $('#wrapper').css('width');
        },
        expected: "960px",
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list style',
        points: 1,
        func: function () {
            return $('.menu').css('list-style-type');
        },
        expected: "none",
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list width',
        points: 1,
        func: function () {
            return $('.menu > li').width();
        },
        expected: 150,
        compare: 'equalDiff',
        compareParam: 30
    }, {
        name: 'menu list height',
        points: 1,
        func: function () {
            return $('.menu > li').outerHeight();
        },
        expected: 39,
        compare: 'equalDiff',
        compareParam: 5
    }, {
        name: 'menu list floating left',
        points: 4,
        func: function () {
            var lis = $('.menu > li');
            var values = [];

            for (var i = 0; i < 3; i++) {
                var currentLi = $(lis[i]);
                var top = currentLi.offset().left;
                values.push(top);
            }

            return values[0] == values[1] && values[1] == values[2];
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list floating',
        points: 2,
        func: function () {
            var lis = $('.menu > li');

            return lis.css('float') != 'left' && lis.css('display') != 'inline' && lis.css('display') != 'inline-block';
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list height',
        points: 4,
        func: function () {
            var lis = $('.menu > li');
            var values = [];

            for (var i = 0; i < 3; i++) {
                var currentLi = $(lis[i]);
                var top = currentLi.height();
                values.push(top);
            }

            return values[0] == values[1] && values[1] == values[2];
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list text align',
        points: 5,
        func: function () {
            var lis = $('.menu > li').css('text-align');
            return lis == 'center' || lis == '-webkit-auto';
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list background',
        points: 5,
        func: function () {
            var lis = $('.menu > li').css('background-color');
            return $.xcolor.distance('#B6FF00', lis);
        },
        expected: 0,
        compare: 'equalDiff',
        compareParam: 30
    }, {
        name: 'menu list background',
        points: 5,
        func: function () {
            var lis = $('.menu > li a').css('background-color');
            return $.xcolor.distance('#B6FF00', lis);
        },
        expected: 0,
        compare: 'equalDiff',
        compareParam: 30
    }, {
        name: 'menu list background',
        points: 5,
        func: function () {
            var lis = $('.menu > li').css('position');
            return lis
        },
        expected: 'relative',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list border color',
        points: 3,
        func: function () {
            var leftColor = $('.menu > li').css('border-left-color');
            var rightColor = $('.menu > li').css('border-right-color');
            var topColor = $('.menu > li').css('border-top-color');
            var bottomColor = $('.menu > li').css('border-bottom-color');

            if (leftColor == rightColor && rightColor == topColor && bottomColor == topColor && leftColor == "rgb(0, 0, 0)") {
                return true;
            }
            else {
                return false;
            }
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list border size',
        points: 4,
        func: function () {
            var leftColor = $('.menu > li').css('border-left-width');
            var rightColor = $('.menu > li').css('border-right-width');
            var topColor = $('.menu > li').css('border-top-width');
            var bottomColor = $('.menu > li').css('border-bottom-width');

            if (leftColor == rightColor && rightColor == topColor && bottomColor == topColor && leftColor == "0px") {
                return true;
            }
            else {
                return false;
            }
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list border style',
        points: 4,
        func: function () {
            var leftColor = $('.menu > li').css('border-left-style');
            var rightColor = $('.menu > li').css('border-right-style');
            var topColor = $('.menu > li').css('border-top-style');
            var bottomColor = $('.menu > li').css('border-bottom-style');

            if (leftColor == rightColor && rightColor == topColor && bottomColor == topColor && leftColor == "none") {
                return true;
            }
            else {
                return false;
            }
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list image border radius',
        points: 5,
        func: function () {
            var leftColor = $('.menu > li').css('border-top-left-radius');
            var rightColor = $('.menu > li').css('border-top-right-radius');
            var topColor = $('.menu > li').css('border-bottom-right-radius');
            var bottomColor = $('.menu > li').css('border-bottom-left-radius');

            if (leftColor == rightColor && rightColor == topColor && bottomColor == topColor) {
                return parseInt(leftColor);
            }
            else {
                return false;
            }
        },
        expected: 15,
        compare: 'equalDiff',
        compareParam: 5
    }, {
        name: 'menu list a decoration',
        points: 4,
        func: function () {
            var leftColor = $('.menu li a').css('text-decoration');

            if (leftColor == 'none') {
                return true;
            }
            else {
                return false;
            }
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list content list display',
        points: 3,
        func: function () {
            return $('.menu li .content ul').css('list-style-type');
        },
        expected: 'none',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list content position',
        points: 5,
        func: function () {
            return $('.menu li .content').css('position');
        },
        expected: 'absolute',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list content top',
        points: 4,
        func: function () {
            return parseInt($('.menu li .content').css('top'));
        },
        expected: -10,
        compare: 'equalDiff',
        compareParam: 10
    }, {
        name: 'menu list content left',
        points: 4,
        func: function () {
            return parseInt($('.menu li .content').css('left'));
        },
        expected: 170,
        compare: 'equalDiff',
        compareParam: 20
    }, {
        name: 'menu list content display',
        points: 4,
        func: function () {
            return $('.menu li .content').css('display');
        },
        expected: 'none',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list content .sub-menu li width',
        points: 4,
        func: function () {
            return $('.menu li .content .sub-menu li').width();
        },
        expected: 500,
        compare: 'equal',
        compareParam: 25
    }, {
        name: 'menu list content .sub-menu li color',
        points: 4,
        func: function () {
            var lis = $('.menu li .content .sub-menu li').css('background-color');
            return $.xcolor.distance('#008000', lis);
        },
        expected: 0,
        compare: 'equalDiff',
        compareParam: 10
    }, {
        name: 'menu list content border radius',
        points: 4,
        func: function () {
            var leftColor = $('.menu li .content .sub-menu li').css('border-top-left-radius');
            var rightColor = $('.menu li .content .sub-menu li').css('border-top-right-radius');
            var topColor = $('.menu li .content .sub-menu li').css('border-bottom-right-radius');
            var bottomColor = $('.menu li .content .sub-menu li').css('border-bottom-left-radius');

            if (leftColor == rightColor && rightColor == topColor && bottomColor == topColor) {
                return parseInt(leftColor);
            }
            else {
                return false;
            }
        },
        expected: 10,
        compare: 'equalDiff',
        compareParam: 5
    }, {
        name: 'menu list .content .sub-menu li',
        points: 4,
        func: function () {
            var lis = $('.menu li .content .sub-menu li').outerWidth();
            return lis;
        },
        expected: 540,
        compare: 'equalDiff',
        compareParam: 5
    }, {
        name: 'menu list .content .sub-menu li a color',
        points: 4,
        func: function () {
            var lis = $('.menu li .content .sub-menu li a').css('color');
            return $.xcolor.distance('#FFFFFF', lis);
        },
        expected: 0,
        compare: 'equalDiff',
        compareParam: 10
    }, {
        name: 'menu list hover text',
        points: 3,
        func: function () {
            var el = $('.menu > li');
            el.toggleClass('hover');
            var value = $('.menu li.hover > a').css('text-decoration');
            el.toggleClass('hover');
            return value;
        },
        expected: 'underline',
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list hover content',
        points: 3,
        func: function () {
            var el = $('.menu > li');
            el.toggleClass('hover');
            var value = $('.menu li.hover .content').css('display');
            el.toggleClass('hover');
            return value == 'block' || value == 'initial';
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    }, {
        name: 'menu list hover content',
        points: 3,
        func: function () {
            var el = $('.menu li .content .sub-menu li a');
            el.toggleClass('hover');
            var value = $('.menu li .content .sub-menu li a.hover + img').css('display');
            el.toggleClass('hover');
            return value == 'block' || value == 'initial';
        },
        expected: true,
        compare: 'equal',
        compareParam: null
    },
];


text:
;; Licensed to the .NET Foundation under one or more agreements.
;; The .NET Foundation licenses this file to you under the MIT license.
;; See the LICENSE file in the project root for more information.

include asmmacros.inc

extern RhpReversePInvokeBadTransition : proc

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpWaitForSuspend -- rare path for RhpPInvoke and RhpReversePInvokeReturn
;;
;;
;; INPUT: none
;;
;; TRASHES: none
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NESTED_ENTRY RhpWaitForSuspend, _TEXT
        push_vol_reg    rax
        alloc_stack     60h

        ; save the arg regs in the caller's scratch space
        save_reg_postrsp        rcx, 70h
        save_reg_postrsp        rdx, 78h
        save_reg_postrsp        r8, 80h
        save_reg_postrsp        r9, 88h

        ; save the FP arg regs in our stack frame
        save_xmm128_postrsp     xmm0, (20h + 0*10h)
        save_xmm128_postrsp     xmm1, (20h + 1*10h)
        save_xmm128_postrsp     xmm2, (20h + 2*10h)
        save_xmm128_postrsp     xmm3, (20h + 3*10h)

        END_PROLOGUE

        ; passing Thread pointer in rcx
        INLINE_GETTHREAD rcx, rdx
        call        RhpPInvokeWaitEx

        movdqa      xmm0, [rsp + 20h + 0*10h]
        movdqa      xmm1, [rsp + 20h + 1*10h]
        movdqa      xmm2, [rsp + 20h + 2*10h]
        movdqa      xmm3, [rsp + 20h + 3*10h]

        mov         rcx, [rsp + 70h]
        mov         rdx, [rsp + 78h]
        mov         r8,  [rsp + 80h]
        mov         r9,  [rsp + 88h]

        add         rsp, 60h
        pop         rax
        ret

NESTED_END RhpWaitForSuspend, _TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpWaitForGC -- rare path for RhpPInvokeReturn
;;
;;
;; INPUT: RCX: transition frame
;;
;; TRASHES: RCX, RDX, R8, R9, R10, R11
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NESTED_ENTRY RhpWaitForGC, _TEXT
        push_vol_reg    rax                 ; don't trash the integer return value
        push_nonvol_reg rbx
        alloc_stack     38h
        movdqa          [rsp + 20h], xmm0   ; don't trash the FP return value
        END_PROLOGUE

        mov         rbx, rcx

RetryWaitForGC:
        ; RBX: transition frame
        mov         rcx, [rbx + OFFSETOF__PInvokeTransitionFrame__m_pThread]

        test        dword ptr [rcx + OFFSETOF__Thread__m_ThreadStateFlags], TSF_DoNotTriggerGc
        jnz         Done

        mov         [rcx + OFFSETOF__Thread__m_pTransitionFrame], rbx

        ; passing thread pointer in rcx
        call        RhpPInvokeReturnWaitEx

        mov         rcx, [rbx + OFFSETOF__PInvokeTransitionFrame__m_pThread]
        mov         qword ptr [rcx + OFFSETOF__Thread__m_pTransitionFrame], 0

        cmp         [RhpTrapThreads], 0
        jne         RetryWaitForGC

Done:
        movdqa      xmm0, [rsp + 20h]
        add         rsp, 38h
        pop         rbx
        pop         rax
        ret

NESTED_END RhpWaitForGC, _TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpReversePInvoke2
;;
;; INCOMING: RCX -- address of reverse pinvoke frame
;;
;; This is useful for calling with a standard calling convention for code generators that don't insert this in
;; the prolog.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEAF_ENTRY RhpReversePInvoke2, _TEXT
        mov         rax, rcx
        jmp         RhpReversePInvoke
LEAF_END RhpReversePInvoke2, _TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpReversePInvoke
;;
;;
;; INCOMING:  RAX -- address of reverse pinvoke frame
;;                          0: save slot for previous M->U transition frame
;;                          8: save slot for thread pointer to avoid re-calc in epilog sequence
;;
;; PRESERVES: RCX, RDX, R8, R9 -- need to preserve these because the caller assumes they aren't trashed
;;
;; TRASHES:   RAX, R10, R11
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEAF_ENTRY RhpReversePInvoke, _TEXT
        ;; R10 = GetThread(), TRASHES R11
        INLINE_GETTHREAD r10, r11
        mov         [rax + 8], r10          ; save thread pointer for RhpReversePInvokeReturn

        test        dword ptr [r10 + OFFSETOF__Thread__m_ThreadStateFlags], TSF_Attached
        jz          AttachThread

        ;;
        ;; Check for the correct mode.  This is accessible via various odd things that we cannot completely
        ;; prevent such as :
        ;;     1) Registering a reverse pinvoke entrypoint as a vectored exception handler
        ;;     2) Performing a managed delegate invoke on a reverse pinvoke delegate.
        ;;
        cmp         qword ptr [r10 + OFFSETOF__Thread__m_pTransitionFrame], 0
        jne         ValidTransition

        ;; Allow 'bad transitions' in when the TSF_DoNotTriggerGc mode is set.  This allows us to have
        ;; [NativeCallable] methods that are called via the "restricted GC callouts" as well as from native,
        ;; which is necessary because the methods are CCW vtable methods on interfaces passed to native.
        test        dword ptr [r10 + OFFSETOF__Thread__m_ThreadStateFlags], TSF_DoNotTriggerGc
        jz          BadTransition

ValidTransition:
        ; rax: reverse pinvoke frame
        ; r10: thread

        ; Save previous TransitionFrame prior to making the mode transition so that it is always valid
        ; whenever we might attempt to hijack this thread.
        mov         r11, [r10 + OFFSETOF__Thread__m_pTransitionFrame]
        mov         [rax], r11

        mov         qword ptr [r10 + OFFSETOF__Thread__m_pTransitionFrame], 0
        cmp         [RhpTrapThreads], 0
        jne         TrapThread

        ret

AttachThread:
        mov         r11, 1
        jmp         RhpReversePInvoke_RarePath

BadTransition:
        mov         r11, 2
        jmp         RhpReversePInvoke_RarePath

TrapThread:
        mov         r11, 3
        jmp         RhpReversePInvoke_RarePath

LEAF_END RhpReversePInvoke, _TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpReversePInvoke_RarePath
;;
;;
;; INCOMING:  RAX -- address of reverse pinvoke frame
;;                          0: save slot for previous M->U transition frame
;;                          8: save slot for thread pointer to avoid re-calc in epilog sequence
;;            R10 -- thread pointer
;;            R11 -- reason for entering the rare path {1: attach thread, 2: bad transition, 3: trap thread}
;;
;; PRESERVES: RCX, RDX, R8, R9 -- need to preserve these because the caller assumes they aren't trashed
;;
;; TRASHES:   RAX, R10, R11
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
NESTED_ENTRY RhpReversePInvoke_RarePath, _TEXT
        push_nonvol_reg rbx
        alloc_stack     80h     ; alloc scratch area and frame

        ; save the integer arg regs
        save_reg_postrsp        rcx, (20h + 0*8)
        save_reg_postrsp        rdx, (20h + 1*8)
        save_reg_postrsp        r8,  (20h + 2*8)
        save_reg_postrsp        r9,  (20h + 3*8)

        ; save the FP arg regs
        save_xmm128_postrsp     xmm0, (20h + 4*8 + 0*10h)
        save_xmm128_postrsp     xmm1, (20h + 4*8 + 1*10h)
        save_xmm128_postrsp     xmm2, (20h + 4*8 + 2*10h)
        save_xmm128_postrsp     xmm3, (20h + 4*8 + 3*10h)

        END_PROLOGUE

        mov         rbx, rax    ; RBX <- address of previous frame save slot

        cmp         r11, 1
        je          AttachThread
        cmp         r11, 2
        je          BadTransition
        cmp         r11, 3
        je          TrapThread

        ; error: you called this function incorrectly
        call        PALDEBUGBREAK
        int 3

Retry:
        ; rbx: reverse pinvoke frame

        ;; R10 = GetThread()
        mov         r10, [rbx + 8]

        test        dword ptr [r10 + OFFSETOF__Thread__m_ThreadStateFlags], TSF_Attached
        jz          AttachThread

        ;;
        ;; Check for the correct mode.  This is accessible via various odd things that we cannot completely
        ;; prevent such as :
        ;;     1) Registering a reverse pinvoke entrypoint as a vectored exception handler
        ;;     2) Performing a managed delegate invoke on a reverse pinvoke delegate.
        ;;
        cmp         qword ptr [r10 + OFFSETOF__Thread__m_pTransitionFrame], 0
        je          CheckBadTransition

        ; rbx: previous transition frame save slot
        ; r10: thread

        ; Save previous TransitionFrame prior to making the mode transition so that it is always valid
        ; whenever we might attempt to hijack this thread.
        mov         r11, [r10 + OFFSETOF__Thread__m_pTransitionFrame]
        mov         [rbx], r11

        mov         qword ptr [r10 + OFFSETOF__Thread__m_pTransitionFrame], 0
        cmp         [RhpTrapThreads], 0
        jne         TrapThread

AllDone:
        movdqa      xmm0, [rsp + (20h + 4*8 + 0*10h)]
        movdqa      xmm1, [rsp + (20h + 4*8 + 1*10h)]
        movdqa      xmm2, [rsp + (20h + 4*8 + 2*10h)]
        movdqa      xmm3, [rsp + (20h + 4*8 + 3*10h)]

        mov         rcx, [rsp + (20h + 0*8)]
        mov         rdx, [rsp + (20h + 1*8)]
        mov         r8,  [rsp + (20h + 2*8)]
        mov         r9,  [rsp + (20h + 3*8)]

        ;; epilog
        add         rsp, 80h
        pop         rbx                 ; restore preserved reg
        ret

CheckBadTransition:
        ;; Allow 'bad transitions' in when the TSF_DoNotTriggerGc mode is set.  This allows us to have
        ;; [NativeCallable] methods that are called via the "restricted GC callouts" as well as from native,
        ;; which is necessary because the methods are CCW vtable methods on interfaces passed to native.
        test        dword ptr [r10 + OFFSETOF__Thread__m_ThreadStateFlags], TSF_DoNotTriggerGc
        jz          BadTransition

        ;; RhpTrapThreads will always be set in this case, so we must skip that check.  We must be sure to
        ;; zero-out our 'previous transition frame' state first, however.
        mov         qword ptr [rbx], 0
        jmp         AllDone

AttachThread:
        ;;
        ;; Thread attach is done here to avoid taking the ThreadStore lock while in DllMain.  The lock is
        ;; avoided for DllMain thread attach notifications, but not process attach notifications because
        ;; our managed DllMain does work during process attach, so it needs to reverse pinvoke.
        ;;
        call        THREADSTORE__ATTACHCURRENTTHREAD
        jmp         Retry

TrapThread:
        ; rbx: previous transition frame save slot
        ; r10: thread

        mov         rcx, [rbx]
        mov         [r10 + OFFSETOF__Thread__m_pTransitionFrame], rcx

        mov         rcx, r10    ; passing Thread pointer in rcx
        call        RhpPInvokeReturnWaitEx
        jmp         Retry

BadTransition:
        add         rsp, 80h
        pop         rbx                 ; restore preserved reg
        jmp         RhpReversePInvokeBadTransition

NESTED_END RhpReversePInvoke_RarePath, _TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpReversePInvokeReturn
;;
;; IN:  RCX: address of reverse pinvoke frame
;;
;; TRASHES:  RCX, RDX, R10, R11
;;
;; PRESERVES: RAX (return value)
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEAF_ENTRY RhpReversePInvokeReturn, _TEXT
        mov         rdx, [rcx + 8]  ; get Thread pointer
        mov         rcx, [rcx + 0]  ; get previous M->U transition frame

        mov         [rdx + OFFSETOF__Thread__m_pTransitionFrame], rcx
        cmp         [RhpTrapThreads], 0
        jne         RhpWaitForSuspend
        ret
LEAF_END RhpReversePInvokeReturn, _TEXT

END


text:
"""Provides device automations for ZHA devices that emit events."""

import voluptuous as vol

from homeassistant.components.automation import (
    AutomationActionType,
    AutomationTriggerInfo,
)
from homeassistant.components.device_automation import DEVICE_TRIGGER_BASE_SCHEMA
from homeassistant.components.device_automation.exceptions import (
    InvalidDeviceAutomationConfig,
)
from homeassistant.components.homeassistant.triggers import event as event_trigger
from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.typing import ConfigType

from . import DOMAIN
from .core.const import ZHA_EVENT
from .core.helpers import async_get_zha_device

CONF_SUBTYPE = "subtype"
DEVICE = "device"
DEVICE_IEEE = "device_ieee"

TRIGGER_SCHEMA = DEVICE_TRIGGER_BASE_SCHEMA.extend(
    {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str}
)

async def async_validate_trigger_config(
    hass: HomeAssistant, config: ConfigType
) -> ConfigType:
    """Validate config."""
    config = TRIGGER_SCHEMA(config)

    if "zha" in hass.config.components:
        trigger = (config[CONF_TYPE], config[CONF_SUBTYPE])
        try:
            zha_device = async_get_zha_device(hass, config[CONF_DEVICE_ID])
        except (KeyError, AttributeError) as err:
            raise InvalidDeviceAutomationConfig from err
        if (
            zha_device.device_automation_triggers is None
            or trigger not in zha_device.device_automation_triggers
        ):
            raise InvalidDeviceAutomationConfig

    return config

async def async_attach_trigger(
    hass: HomeAssistant,
    config: ConfigType,
    action: AutomationActionType,
    automation_info: AutomationTriggerInfo,
) -> CALLBACK_TYPE:
    """Listen for state changes based on configuration."""
    trigger_key: tuple[str, str] = (config[CONF_TYPE], config[CONF_SUBTYPE])
    try:
        zha_device = async_get_zha_device(hass, config[CONF_DEVICE_ID])
    except (KeyError, AttributeError) as err:
        raise HomeAssistantError(
            f"Unable to get zha device {config[CONF_DEVICE_ID]}"
        ) from err

    if trigger_key not in zha_device.device_automation_triggers:
        raise HomeAssistantError(f"Unable to find trigger {trigger_key}")

    trigger = zha_device.device_automation_triggers[trigger_key]

    event_config = {
        event_trigger.CONF_PLATFORM: "event",
        event_trigger.CONF_EVENT_TYPE: ZHA_EVENT,
        event_trigger.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger},
    }

    event_config = event_trigger.TRIGGER_SCHEMA(event_config)
    return await event_trigger.async_attach_trigger(
        hass, event_config, action, automation_info, platform_type="device"
    )

async def async_get_triggers(
    hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
    """List device triggers.

    Make sure the device supports device automations and
    if it does return the trigger list.
    """
    zha_device = async_get_zha_device(hass, device_id)

    if not zha_device.device_automation_triggers:
        return []

    triggers = []
    for trigger, subtype in zha_device.device_automation_triggers.keys():
        triggers.append(
            {
                CONF_DEVICE_ID: device_id,
                CONF_DOMAIN: DOMAIN,
                CONF_PLATFORM: DEVICE,
                CONF_TYPE: trigger,
                CONF_SUBTYPE: subtype,
            }
        )

    return triggers


text:
PostgreSQL/PostgREST proxy to Google, Bing and Prompt Translate APIs, with caching and ability to combine multiple text segments in one single request. It allows to work with those Translate APIs right from Postgres or via REST API requests.

[![Build Status](https://circleci.com/gh/NikolayS/postgrest-google-translate.png?style=shield&circle-token=fb58aee6e9f98cf85d08c4d382d5ba3f0f548e08)](https://circleci.com/gh/NikolayS/postgrest-google-translate/tree/master)

This tiny project consists of 2 parts:

1. SQL objects to enable calling Translation APIs right from SQL environment (uses [plsh](https://github.com/petere/plsh) extension)
2. API method (uses [PostgREST](http://postgrest.com))

Part (1) can be used without part (2).

Table `translation_proxy.cache` is used to cache API responses to speedup work and reduce costs.
Also, it is possible to combine multiple phrases in one API request, which provides great advantage (e.g.: for 10 uncached phrases, it will be ~150-200ms for single aggregated request versus 1.5-2 seconds for 10 consequent requests). Currently, Google Translate API accepts up to 128 text segments in a single request.

:warning: Limitations
---
In general, working with external things (even pretty predictable and fast like Google API) might introduce significant limitations to capability to scale for your master. However, this project shows how powerful PostgreSQL is: you don't need to use PHP/Python/Java/Ruby to work with external JSON API.

To make it scalable, one could run PostgREST on multiple slave nodes to avoid this limitations. The ony thing is to think about – writing to `cache` table (TODO: check if it is possible to call master's writing functions from plpgsql code being executed on slave nodes).

To minimize impact on the master node, it is a good idea to combine multiple text segments in a single request (see examples below).

It is worth to mention, that due to use of plsh and curl, a separate process (curl) is invoked on each non-cached request. Alternative approach is discussed in the [Issue #3](https://github.com/NikolayS/postgrest-google-translate/issues/3).

Also, see related notes ["Why This is a Bad Idea"](https://github.com/pramsey/pgsql-http#why-this-is-a-bad-idea).

Dependencies
---
1. cURL
2. [PostgREST](http://postgrest.com) – download the latest version. See `circle.yml` for example of starting/using it.
3. `plsh` – PostgreSQL contrib module, it is NOT included to standard contribs package. To install it on Ubuntu/Debian run: `apt-get install postgresql-X.X-plsh` (where X.X could be 9.5, depending on your Postgres version). For Archlinux use AUR package 'postgresql-plsh'.
4. Ruby for easy installer (optional)

Installation and Configuration
---
Simple method
----
Edit `setup.yml` then execute `setup.rb`. You need to have the ruby interpreter been installed.

Step-by-step method
----
For your database (here we assume that it's called `DBNAME`), install [plsh](https://github.com/petere/plsh) extension and then execute `_core` SQL scripts, after what configure your database settings:
`translation_proxy.promt_api_key`, `translation_proxy.bing_api_key` and
`translation_proxy.google_api_key` (take it from Google Could Platform Console):
```sh
psql DBNAME -c 'create extension if not exists plsh;'
psql DBNAME -f install_core.sql
psql -c "alter database DBNAME set translation_proxy.google_api_key = 'YOUR_GOOGLE_API_KEY';"
psql -c "alter database DBNAME set translation_proxy.google_begin_at = '2000-01-01';"
psql -c "alter database DBNAME set translation_proxy.google_end_at = '2100-01-01';"
```

Alternatively, you can use `ALTER ROLE ... SET translation_proxy.google_api_key = 'YOUR_GOOGLE_API_KEY';` or put this setting to `postgresql.conf` or do `ALTER SYSTEM SET translation_proxy.google_api_key = 'YOUR_GOOGLE_API_KEY';` (in these cases, it will be available cluster-wide).

Parameters `translation_proxy.google_begin_at` and `translation_proxy.google_end_at` are responsible for the period of time, when Google Translate API is allowed to be called. If current time is beyond this timeframe, only the cache table will be used.

To enable REST API proxy, install [PostgREST](http://postgrest.com), launch it (see `cirle.yml` as an example), and initialize API methods with the additional SQL script:
```sh
psql DBNAME -f install_api.sql
```

Uninstallation
---
```sh
psql DBNAME -f uninstall_api.sql
psql DBNAME -f uninstall_core.sql
psql DBNAME -c 'drop extension plsh;'
```

Usage
---
In SQL environment:
```sql
-- Translate from English to Russian
select translation_proxy.google_translate('en', 'ru', 'Hello world');

-- Combine multiple text segments in single query
select * from translation_proxy.google_translate('en', 'ru', array['ok computer', 'show me more','hello world!']);
```

REST API:
```sh
curl -X POST -H "Content-Type: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"source": "en", "target": "ru", "q": "Hello world"}' \
    "http://localhost:3000/rpc/google_translate"
```

```sh
curl -X POST -H "Content-Type: application/json" \
    -H "Cache-Control: no-cache" \
    -d '{"source": "en", "target": "ru", "q": ["ok computer", "hello world", "yet another phrase"]}' \
    "https://localhost:3000/rpc/google_translate_array"
```


text:
'use strict';

var should = require('should'),
    request = require('supertest'),
    angular = require('angular'),
    path = require('path');

describe('SearchService tests', function() {
    var $injector, searchService;

    beforeEach(function() {
        $injector = angular.injector(['core']);
        searchService = $injector.get('SearchService');
    });

    describe('search returns results', function () {
        it('should return results from the search method', function () {

            expect(searchService.search("wheel")).toBe("1");
        });
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnMethods</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            Module
            ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnMethods

/Users/Bonobo/.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb

Methods

B

                bit,

                bit_varying

C

                cidr,

                citext

D

                daterange

H

                hstore

I

                inet,

                int4range,

                int8range

J

                json,

                jsonb

L

                ltree

M

                macaddr,

                money

N

                numrange

P

                point

T

                tsrange,

                tstzrange,

                tsvector

U

                uuid

X

                xml

Instance Public methods

              bit(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 79
def bit(name, options = {})
  column(name, :bit, options)
end

              bit_varying(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 83
def bit_varying(name, options = {})
  column(name, :bit_varying, options)
end

              cidr(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 51
def cidr(name, options = {})
  column(name, :cidr, options)
end

              citext(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 71
def citext(name, options = {})
  column(name, :citext, options)
end

              daterange(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 35
def daterange(name, options = {})
  column(name, :daterange, options)
end

              hstore(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 39
def hstore(name, options = {})
  column(name, :hstore, options)
end

              inet(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 47
def inet(name, options = {})
  column(name, :inet, options)
end

              int4range(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 15
def int4range(name, options = {})
  column(name, :int4range, options)
end

              int8range(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 19
def int8range(name, options = {})
  column(name, :int8range, options)
end

              json(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 63
def json(name, options = {})
  column(name, :json, options)
end

              jsonb(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 67
def jsonb(name, options = {})
  column(name, :jsonb, options)
end

              ltree(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 43
def ltree(name, options = {})
  column(name, :ltree, options)
end

              macaddr(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 55
def macaddr(name, options = {})
  column(name, :macaddr, options)
end

              money(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 87
def money(name, options = {})
  column(name, :money, options)
end

              numrange(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 31
def numrange(name, options = {})
  column(name, :numrange, options)
end

              point(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 75
def point(name, options = {})
  column(name, :point, options)
end

              tsrange(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 23
def tsrange(name, options = {})
  column(name, :tsrange, options)
end

              tstzrange(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 27
def tstzrange(name, options = {})
  column(name, :tstzrange, options)
end

              tsvector(*args)

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 10
def tsvector(*args)
  options = args.extract_options!
  column(args[0], :tsvector, options)
end

              uuid(name, options = {})

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 59
def uuid(name, options = {})
  column(name, :uuid, options)
end

              xml(*args)

            Link

                Source:
                show

# File ../../../../.rvm/gems/ruby-2.2.2/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql/schema_definitions.rb, line 5
def xml(*args)
  options = args.extract_options!
  column(args[0], :xml, options)
end


text:
package com.arjuna.databroker.data.core.jee;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import javax.ejb.Singleton;
import com.arjuna.databroker.data.DataFlow;
import com.arjuna.databroker.data.DataFlowInventory;

@Singleton(name="DataFlowInventory")
public class GlobalDataFlowInventory implements DataFlowInventory
{
    public GlobalDataFlowInventory()
    {
        _inventory = new HashMap<String, DataFlow>();
    }

    @Override
    public Collection<DataFlow> getDataFlows()
    {
        return Collections.unmodifiableCollection(_inventory.values());
    }

    @Override
    public DataFlow getDataFlow(String name)
    {
        return _inventory.get(name);
    }

    @Override
    public void addDataFlow(DataFlow dataFlow)
    {
        _inventory.put(dataFlow.getName(), dataFlow);
    }

    @Override
    public boolean removeDataFlow(String name)
    {
        return _inventory.remove(name) != null;
    }

    @Override
    public boolean removeDataFlow(DataFlow dataFlow)
    {
        return _inventory.remove(dataFlow.getName()) != null;
    }

    private Map<String, DataFlow> _inventory;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Jaffle Pancake</title>
    <description>
The Mad Milliner
</description>
    <link>http://jpanken.github.io/</link>
    <atom:link href="http://jpanken.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 28 Oct 2016 02:33:27 +0000</pubDate>
    <lastBuildDate>Fri, 28 Oct 2016 02:33:27 +0000</lastBuildDate>
    <generator>Jekyll v3.2.1</generator>

      <item>
        <title>Scripts</title>
        <description>
When we started this unit, I thought that scripts were just something that
actors read.  It turns out that they are much more than that.  A script is a
"program or sequence of instructions that is interpreted or carried out by
another program rather than by the computer processor."
source  They
are an easy way to automate tasks that take up time and energy that I just don't
have.

I've already written my thesis, but if I had to do it again, I would consider
using a template and Pandoc. It would have been worth the effort to learn how to
write in markdown and convert it to multiple formats effortlessly.  As it was,
it took me hours to format my dissertation (especially because it had a lot of
images).  If there were going to write another one (never again!), I'll use the
techniques I learned in the class.

In class, I made a Mad Libs script.  It asked for different parts of speech and
assembled some pretty funny sentences.  After writing the Mad Libs, I still had
no idea how to write the commands to convert documents from markdown into
different formats.  I figured it out by looking at the class notes and using the
various tutorials to find out how to designate variables.

My script is very basic, but it works.  I tried to figure out how to use a
template so I could have indented paragraphs, but I didn't have a lot of time to
mess around.  I also tried to color the document titles, but it didn't work.

Unfortunately, I didn't write down the code my professor used when he made a
"Happy Birthday" script.  I tried Googling the information, but the codes I
tried didn't work.  There was probably some weird formatting issue with which
I'm not familiar.

It took me awhile to decide what document to convert, but turning it into
markdown wasn't very hard.  In the end, I converted the beginning of Chapter
Four of my dissertation into markdown. The excerpt discusses the work of
American humanitarians in Turkey after the Armenian Genocide, 1915-1917.  In the
chapter as a whole, I address the creation of publicity photographs and other
materials to raise money from the American public.  I discuss the creation and
use of a particular photograph featuring a female physician, Dr. Mabel Elliott,
and her starving patient.  You can find my converted documents at the
following links:

Chapter 4 in DOCX

Chapter 4 in HTML

Chapter 4 in ODT

Chapter 4 in PDF

</description>
        <pubDate>Thu, 27 Oct 2016 00:00:00 +0000</pubDate>
        <link>http://jpanken.github.io/161/2016/10/27/scripts.html</link>
        <guid isPermaLink="true">http://jpanken.github.io/161/2016/10/27/scripts.html</guid>

        <category>161</category>

      </item>

      <item>
        <title>Reflections on 161</title>
        <description>
I'm a good reader.  I taught myself to read at a young age and never left home without a book in hand.  As an undergrad and graduate student, I learned how to analyze historical monographs so that I could discuss them intelligently.  While studying for my oral exams, I read around five non-fiction books a day for three months straight.  That is my comfort zone.

None of these skills seem applicable to INLS 161.  I am not used to following directions so closely.  It takes all of my concentration to keep up with the class.  If I make a mistake, I get left behind in the dust.

It took me hours of fiddling with hex codes to make the color scheme on my website work.  This was after googling "color schemes for websites" and experimenting to figure out what code controls which text.  In the end, I'm pretty happy with the soothing, muted color scheme.  On the other hand, I wanted to use background images, but I never figured that part out.

I still have a lot of work left on this website.  Ultimately, I want to create a space for sharing my millinery adventures.  This will require a lot of images to document my efforts so I will have to get comfortable with those features.  I'll figure it out; I always do.

</description>
        <pubDate>Mon, 26 Sep 2016 00:00:00 +0000</pubDate>
        <link>http://jpanken.github.io/161/2016/09/26/reflections-on-161.html</link>
        <guid isPermaLink="true">http://jpanken.github.io/161/2016/09/26/reflections-on-161.html</guid>

        <category>161</category>

      </item>

      <item>
        <title>Welcome to Millinery!</title>
        <description>
Millinery is really a form of sculpture.  First and foremost, it requires strong hands to withstand steam and manipulate stiff felt into different positions. It also requires some expensive tools.

Hat blocks are the main expense for any aspiring milliner.  It is the canvas upon which you build your hat.  Unfortunately, hat block making is a dying art and precious few people currently make hat blocks.  If this is your first hat, you should check eBay for a basic block (shaped like a head).  Once you are more established, you might invest more seriously in a modular set. That way you can mix crowns and brims for different looks.

Once you have a block, you need a felt body to block.  Felt bodies (also called hoods or cones) are unblocked hats made out of wool or fur felt.  They come in many different colors and textures.  Wool felt is the cheapest kind of body (under $15), but fur felts (around $30) are much easier to work with.  Fur felts come in a variety of finishes, but flat and velour are the most popular.  Velour (also called peachbloom) has a nap on one or both sides.  The nap gives it a richer texture.  Melusine, on the other hand, has a true furry texture not for the faint of heart.

Hats keep their shape with the help of stiffener, a glue-like spray that can dry quite hard if you aren't careful.  I mix up my own stiffener from hydrolac b5 powder, rubbing alcohol (try for at least 90% alcohol), and a bit of water.  It becomes a clear, slightly yellowish liquid and can be sprayed in light layers on the inside of the body.  Stiffener is also available pre-mixed, but who wants to ship a flammable liquid?  Powder is cheaper and easily shipped.

Steam is a key ingredient for blocking hats.  I use a travel garment steamer to keep my felt pliable and set the stiffener.  Steam burns are a real hazard so be careful!

Pins are necessary to keep the felt in place as it dries.  I use straight pins when I am hand-draping and blocking pins when I am anchoring the body.

Next time, we'll discuss the process of blocking a hat.

 Here's a video of a hand-draping workshop with Jasmin Zorlu, it's supercool!

Intro to 'Freeform Hat Blocking Workshop' with Jasmin Zorlu

</description>
        <pubDate>Sun, 25 Sep 2016 16:31:43 +0000</pubDate>
        <link>http://jpanken.github.io/millinery/2016/09/25/welcome.html</link>
        <guid isPermaLink="true">http://jpanken.github.io/millinery/2016/09/25/welcome.html</guid>

        <category>millinery</category>

      </item>

  </channel>
</rss>


text:
require 'spec_helper'

describe User do

  before(:each) do
    info = mock('facebook info', {:email => "some@guy",
                                  :name => "someguy",
                                  :image => "http://image"})
    cred = mock('facebook cred', {:token => "abc123"})
    @hash = mock('omniauth hash', {:uid => 1,
                                  :info => info,
                                  :credentials => cred})
    @existing_user = mock_model(User)
  end

  it "should create a user given an omniauth hash" do
    User.should_receive(:find_by_facebook_uid).with(@hash.uid).and_return(nil)
    User.should_receive(:create)
    User.find_or_create_from_auth_hash(@hash)
  end

  it "should find a user given an omniauth hash" do
    User.should_receive(:find_by_facebook_uid).with(@hash.uid).and_return(@existing_user)

    User.find_or_create_from_auth_hash(@hash).should == @existing_user
  end
end


text:
#ifndef _CAM_CAM_XPT_H
#define _CAM_CAM_XPT_H 1

/* Forward Declarations */
union ccb;
struct cam_periph;
struct cam_ed;
struct cam_sim;

/*
 * Definition of a CAM path.  Paths are created from bus, target, and lun ids
 * via xpt_create_path and allow for reference to devices without recurring
 * lookups in the edt.
 */
struct cam_path;

/* Path functions */

#ifdef _KERNEL

/*
 * Definition of an async handler callback block.  These are used to add
 * SIMs and peripherals to the async callback lists.
 */
struct async_node {
	SLIST_ENTRY(async_node)	links;
	u_int32_t	event_enable;	/* Async Event enables */
	u_int32_t	event_lock;	/* Take SIM lock for handlers. */
	void		(*callback)(void *arg, u_int32_t code,
				    struct cam_path *path, void *args);
	void		*callback_arg;
};

SLIST_HEAD(async_list, async_node);
SLIST_HEAD(periph_list, cam_periph);

void			xpt_action(union ccb *new_ccb);
void			xpt_action_default(union ccb *new_ccb);
union ccb		*xpt_alloc_ccb(void);
union ccb		*xpt_alloc_ccb_nowait(void);
void			xpt_free_ccb(union ccb *free_ccb);
void			xpt_setup_ccb(struct ccb_hdr *ccb_h,
				      struct cam_path *path,
				      u_int32_t priority);
void			xpt_merge_ccb(union ccb *master_ccb,
				      union ccb *slave_ccb);
cam_status		xpt_create_path(struct cam_path **new_path_ptr,
					struct cam_periph *perph,
					path_id_t path_id,
					target_id_t target_id, lun_id_t lun_id);
cam_status		xpt_create_path_unlocked(struct cam_path **new_path_ptr,
					struct cam_periph *perph,
					path_id_t path_id,
					target_id_t target_id, lun_id_t lun_id);
int			xpt_getattr(char *buf, size_t len, const char *attr,
				    struct cam_path *path);
void			xpt_free_path(struct cam_path *path);
void			xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
					uint32_t *periph_ref, uint32_t *target_ref,
					uint32_t *device_ref);
int			xpt_path_comp(struct cam_path *path1,
				      struct cam_path *path2);
int			xpt_path_comp_dev(struct cam_path *path,
					  struct cam_ed *dev);
void			xpt_print_path(struct cam_path *path);
void			xpt_print_device(struct cam_ed *device);
void			xpt_print(struct cam_path *path, const char *fmt, ...);
int			xpt_path_string(struct cam_path *path, char *str,
					size_t str_len);
path_id_t		xpt_path_path_id(struct cam_path *path);
target_id_t		xpt_path_target_id(struct cam_path *path);
lun_id_t		xpt_path_lun_id(struct cam_path *path);
int			xpt_path_legacy_ata_id(struct cam_path *path);
struct cam_sim		*xpt_path_sim(struct cam_path *path);
struct cam_periph	*xpt_path_periph(struct cam_path *path);
void			xpt_async(u_int32_t async_code, struct cam_path *path,
				  void *async_arg);
void			xpt_rescan(union ccb *ccb);
void			xpt_hold_boot(void);
void			xpt_release_boot(void);
void			xpt_lock_buses(void);
void			xpt_unlock_buses(void);
struct mtx *		xpt_path_mtx(struct cam_path *path);
#define xpt_path_lock(path)	mtx_lock(xpt_path_mtx(path))
#define xpt_path_unlock(path)	mtx_unlock(xpt_path_mtx(path))
#define xpt_path_assert(path, what)	mtx_assert(xpt_path_mtx(path), (what))
#define xpt_path_owned(path)	mtx_owned(xpt_path_mtx(path))
#define xpt_path_sleep(path, chan, priority, wmesg, timo)		\
    msleep((chan), xpt_path_mtx(path), (priority), (wmesg), (timo))
cam_status		xpt_register_async(int event, ac_callback_t *cbfunc,
					   void *cbarg, struct cam_path *path);
cam_status		xpt_compile_path(struct cam_path *new_path,
					 struct cam_periph *perph,
					 path_id_t path_id,
					 target_id_t target_id,
					 lun_id_t lun_id);
cam_status		xpt_clone_path(struct cam_path **new_path,
				      struct cam_path *path);
void			xpt_copy_path(struct cam_path *new_path,
				      struct cam_path *path);

void			xpt_release_path(struct cam_path *path);

#endif /* _KERNEL */

#endif /* _CAM_CAM_XPT_H */


text:
A Ruby gem wrapping the inpay.com merchant API.

## Who should use it?
Any Ruby on Rails developer who wants/needs to work with inpay.

## Usage

### Installation

    gem install inpay

### Configuration

By default the environment is set to test. Add the following line to the environments/production.rb:

    Inpay::Config.mode = :production

You will also need to define the IP (or IPs) you will accept postbacks form. Add a private method in your application controller, something like this:

    private

    def set_inpay_ips
      Inpay::Config.server_ips = 'xxx.xxx.xxx.xxx'
    end

You can also use an array:

    private

    def set_inpay_ips
      Inpay::Config.server_ips = ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx']
    end

In the controller that will process the postback add a before filter:

    before_filter :set_inpay_ips

### The form in your view

Create a form tag and use the inpay_setup method to generate the necessary hidden fields:

    <%= form_tag inpay_flow_url do %>
      <%= raw inpay_setup(amount, options) %>
    <% end %>

The amount can be either a float or a Money object. Options should be passed as a hash with symbolized keys.

These are all required options:

- :order_id
- :merchant_id        _(your merchant id at inpay)_
- :currency           _(defaults to :EUR)_
- :order_text         _(a brief description)_
- :buyer_email
- :secret_key         _(your sectret key from inpay)_
- :flow_layout        _(defaults to :multi_page)_

These are nonmandatory:

- :return_url         _(defaults to the return url set in the inpay admin)_
- :pending_url        _(defaults to the return url set in the inpay admin)_
- :cancel_url         _(defaults to the return url set in the inpay admin)_
- :notify_url         _(defaults to the postback url set in the inpay admin)_
- :country
- :invoice_comment    _(will be attached to the created invoice)_
- :buyer_name
- :buyer_address      _(street, zip code, city, state, country)_
- :buyer_information  _(free text field where you can put information that could be relevant to the customer)_
- :extra_your_param   _(those parameters will be added to the return url without the "extra" prefix)_

### Handling a postback in your controller

An Inpay postback controller might look something like this:

    class InpaysController < ApplicationController
      skip_before_filter :verify_authenticity_token

      def postback
        begin
          @postback = Inpay::Postback.new(request, _your_inpay_secret_key_ )

          if @postback.genuine?
            if @postback.approved?
              ... yay ...
            else
              ... meh ...
            end
          end
        rescue Exception => e
          ... handle the error ...
        end

        render :nothing => true
      end
    end

Important: make sure no errors are thrown when something goes wrong. Logically Inpay will see this as a failure and keep on sending postbacks. Hence the begin/rescue block.

The Inpay::Postback instance has a lot of methods for the result of the transactions:

- genuine? _(verifies the checksum and IP of the server that performed the postback)_
- pending?
- sum_too_low?
- approved?
- cancelled?
- refunded?
- refund_pending?
- error? _(when something went wrong with connection)_

The inpay server will post back the following params:

- :invoice_currency
- :invoice_reference
- :checksum
- :order_id
- :invoice_amount
- :invoice_created_at _(e.g. 2011-02-19 10:41:55)_
- :invoice_status

You might need some of those params to fetch the invoice, status and so on.

## Important

This gem is written for Rails 3. Rails 2 might work but it's not tested.

## Contributing to inpay

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2011 Wout Fierens. See LICENSE.txt for
further details.


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import {SsnValidatorService} from "./ssn-validator.service";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [SsnValidatorService],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
import os

from setuptools import setup

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()

packages = [
    'skosprovider_getty'
]

requires = [
    'skosprovider>=1.1.0',
    'requests',
    'rdflib'
]

setup(
    name='skosprovider_getty',
    version='1.1.0',
    description='Skosprovider implementation of the Getty Vocabularies',
    long_description=README + '\n\n' + CHANGES,
    long_description_content_type='text/x-rst',
    packages=packages,
    include_package_data=True,
    install_requires=requires,
    license='MIT',
    zip_safe=False,
    classifiers=[
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Programming Language :: Python :: 3.10',
    ],
    author='Flanders Heritage Agency',
    author_email='ict@onroerenderfgoed.be',
    url='https://github.com/OnroerendErfgoed/skosprovider_getty',
    keywords='getty skos skosprovider vocabulary AAT TGN ULAN'
)


text:
This guide covers titles and urls in Refinery Pages. After reading it, you should be familiar with:

* Customizing titles shown on pages and menus
* Customizing titles shown in the browser window (the html title tag) for SEO purposes
* Customizing the slugs that are automatically generated by Refinery
* Excluding a route from Refinery's list of reserved words

## Title

A page's title is set by entering text in the "Title" field on the edit page screen. This title is displayed at the top of pages in the default theme and is available via the page_title variable in your custom views. By default, this title is also used in the site's menu and for part of the browser title (html title tag). Additionally, the title is used as the basis for creating a friendly ID or slug for the page. (ex. "Welcome to our site" would be assigned a slug of "welcome-to-our-site").

## Menu Title

In some situations, you may want to have a different title appear in the site menu than on the page itself. For example, you may want to have the menu simply display "Welcome" while the page says "Welcome to our site." Enter the text you want to appear in the menu in the Menu Title field under Advanced Options. Also, setting this option will create a new slug for your page (ex. If Menu Title is set to "Welcome" your slug will be "welcome").

## Browser Title

For SEO purposes, it is sometimes useful to have specific keywords within the html title tag. A custom browser title can be set in the Browser Title field under Advanced Options.

## Custom Slug

Sometimes you might need to change a page's slug from the default that Refinery generates for you. This is useful if you have pages with really long titles, if you need to support a legacy URL schema, if you are writing in a language that doesn't work well with Refinery's standard slug generation, or if you want to have consistent slugs across multiple locales.

To use custom slugs, open `config/initializers/refinery/pages.rb`, uncomment `config.use_custom_slugs = false` and set it to true. This will enable a "Custom slug" field in the Advanced Options section of the page editing screen. If text is entered in this field, it will be used as the basis for your slug instead of the Title or Menu Title.

## Reserved Words

By default, Refinery will scan your routes.rb file and add your routes as reserved words. This prevents Refinery Pages from interfering with your app. If you want to have a Refinery Page that has the same slug as a Rails route, you can add `:allow_slug => true` : `match '/cart', :to => 'cart#index', :allow_slug => true`

This will allow a page with slug 'cart', whereas the default behaviour would result in a page with slug 'cart-page'


text:
import express from 'express';
import colors from 'colors/safe';

import {
    trackController
} from './controllers';

export const router = express.Router();

// API Routes
router.get('/tracks', trackController.getList);