text:
package main

import (
    "time"
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "github.com/mrjones/oauth"
    "github.com/nsf/termbox-go"
)

var debug bool = false

var trello_url      string = "https://api.trello.com/1"
var oauth_file_name string = ".trello_oauth.json"

type OauthData struct {
    ApiKey      string
    AccessToken oauth.AccessToken
}

var oauth_data OauthData
var consumer   *oauth.Consumer

type TrelloCard struct {
    card map[string]interface{}
}

type TrelloList struct {
    list          map[string]interface{}
    cards_fetched bool
    cards         []*TrelloCard
}

type TrelloBoard struct {
    board         map[string]interface{}
    lists_fetched bool
    lists         []*TrelloList
}

var all_boards []*TrelloBoard

type CursorPosition struct {
    line    int
    column  int
}

const (
    PageTypeAllBoards int = iota
    PageTypeBoard
    PageTypeList
    PageTypeCard
    PageTypeHelp
)

type Page struct {
    // if this struct changes, update push_page_on_stack()
    cursor     CursorPosition
    cells      []termbox.Cell
    ptype      int // PageType
    start_line int
    board      *TrelloBoard
    list       *TrelloList
    card       *TrelloCard
}

var current_page *Page
var page_stack   []*Page

func (page *Page) set_cursor(line     int,
                             column   int,
                             absolute bool) {
    if absolute {
        page.cursor.line   = line
        page.cursor.column = column
    } else {
        page.cursor.line   += line
        page.cursor.column += column
    }
    //termbox.SetCursor(cursor.line, cursor.column)
    termbox.HideCursor()
}

func dump_json(json_data interface{}) {
    data_indent, err := json.MarshalIndent(json_data, "", "    ")
    if err != nil {
        log.Fatal(err)
    }

    os.Stdout.Write(data_indent)
    fmt.Print("\n")
}

func FileExists(name string) bool {
    _, err := os.Stat(name)
    return !os.IsNotExist(err)
}

func do_oauth() {
    var oauth_file = os.ExpandEnv("$HOME") + "/" + oauth_file_name
    var request_token_url string = "https://trello.com/1/OAuthGetRequestToken"
    var authorize_url string = "https://trello.com/1/OAuthAuthorizeToken"
    var access_token_url string = "https://trello.com/1/OAuthGetAccessToken"

    if FileExists(oauth_file) {
        oauth_json_data, err := ioutil.ReadFile(oauth_file)
        if err != nil {
            log.Fatal(err)
        }

        err = json.Unmarshal(oauth_json_data, &oauth_data)
        if err != nil {
            log.Fatal(err)
        }

        if ((oauth_data.ApiKey == "") ||
            (oauth_data.AccessToken.Token == "") ||
            (oauth_data.AccessToken.Secret == "")) {
            log.Fatal("Invalid oauth data!")
        }

        consumer = oauth.NewConsumer(oauth_data.ApiKey,
                                     oauth_data.AccessToken.Secret,
                                     oauth.ServiceProvider{})
        if consumer == nil {
            log.Fatal("Invalid consumer")
        }

        return
    }

    fmt.Print("Go here to get your keys: https://trello.com/app-key\n")

    fmt.Print("Your Trello API key: ")
    api_key := ""
    fmt.Scanln(&api_key)

    fmt.Print("Your Trello API secret: ")
    api_secret := ""
    fmt.Scanln(&api_secret)

    fmt.Print("Expiration [30days]: ")
    expiration := ""
    fmt.Scanln(&expiration)
    if expiration == "" {
        expiration = "30days"
    }

    scope := "read,write"

    c := oauth.NewConsumer(
        api_key,
        api_secret,
        oauth.ServiceProvider{
            RequestTokenUrl:   request_token_url,
            AuthorizeTokenUrl: authorize_url,
            AccessTokenUrl:    access_token_url,
        })

    c.AdditionalAuthorizationUrlParams = map[string]string{
        "name":       "Trello CLI",
        "scope":      scope,
        "expiration": expiration,
    }

    //c.Debug(true)

    requestToken, url, err := c.GetRequestTokenAndUrl("")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Print("Go here to perform the authorization:\n")
    fmt.Print(url, "\n")

    fmt.Print("Did you accept the authorization? [y|n] ")
    yes_no := ""
    fmt.Scanln(&yes_no)
    if (yes_no != "y") && (yes_no != "Y") &&
        (yes_no != "yes") && (yes_no != "YES") &&
        (yes_no != "Yes") {
        return
    }

    fmt.Print("Verification code: ")
    verificationCode := ""
    fmt.Scanln(&verificationCode)

    accessToken, err := c.AuthorizeToken(requestToken, verificationCode)
    if err != nil {
        log.Fatal(err)
    }

    oauth_data.ApiKey = api_key
    oauth_data.AccessToken = *accessToken

    oauth_json_data, err := json.Marshal(oauth_data)
    if err != nil {
        log.Fatal(err)
    }

    err = ioutil.WriteFile(oauth_file, oauth_json_data, 0600)
    if err != nil {
        log.Fatal(err)
    }

    consumer = oauth.NewConsumer(oauth_data.ApiKey,
                                 oauth_data.AccessToken.Secret,
                                 oauth.ServiceProvider{})
    if consumer == nil {
        log.Fatal("Invalid consumer")
    }
}

func trello_get(url string) interface{} {
    var data interface{}
    response, err := consumer.Get(url, map[string]string{}, &oauth_data.AccessToken)
    if err != nil {
        log.Fatal(err)
    }

    defer response.Body.Close()

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }

    json.Unmarshal(body, &data)

    return data
}

func get_list_cards(tl *TrelloList) {
    var url string = trello_url + "/lists/" + tl.list["id"].(string) + "/cards"
    var cards []interface{}

    cards = trello_get(url).([]interface{})
    for _, c := range cards {
        if c.(map[string]interface{})["closed"] == true {
            continue
        }

        tc := new(TrelloCard)
        tc.card = c.(map[string]interface{})

        tl.cards = append(tl.cards, tc)

        if debug {
            fmt.Printf("        %s\n", tc.card["name"])
        }
    }
}

func get_board_lists(recurse bool,
                     tb *TrelloBoard) {
    var url string = trello_url + "/boards/" + tb.board["id"].(string) + "/lists"
    var lists []interface{}

    lists = trello_get(url).([]interface{})
    for _, l := range lists {
        if l.(map[string]interface{})["closed"] == true {
            continue
        }

        tl := new(TrelloList)
        tl.list          = l.(map[string]interface{})
        tl.cards_fetched = false
        tl.cards         = make([]*TrelloCard, 0)

        tb.lists = append(tb.lists, tl)

        if debug {
            fmt.Printf("    %s\n", tl.list["name"])
        }

        if recurse == true {
            get_list_cards(tl)
            tl.cards_fetched = true
        }
    }
}

func get_boards(recurse bool) {
    var url string = trello_url + "/members/me/boards"
    var boards []interface{}

    all_boards = make([]*TrelloBoard, 0)

    boards = trello_get(url).([]interface{})
    for _, b := range boards {
        if b.(map[string]interface{})["closed"] == true {
            continue
        }

        tb := new(TrelloBoard)
        tb.board         = b.(map[string]interface{})
        tb.lists_fetched = false
        tb.lists         = make([]*TrelloList, 0)

        all_boards = append(all_boards, tb)

        if debug {
            fmt.Printf("%s\n", tb.board["name"])
        }

        if recurse == true {
            get_board_lists(recurse, tb)
            tb.lists_fetched = true
        }
    }
}

type board_func func(tb *TrelloBoard)
type list_func  func(tb *TrelloBoard, tl *TrelloList)
type card_func  func(tb *TrelloBoard, tl *TrelloList, tc *TrelloCard)

func iter_boards(fn board_func) {
    for _, b := range all_boards {
        fn(b)
    }
}

func iter_lists(tb *TrelloBoard,
                fn list_func) {
    for _, l := range tb.lists {
        fn(tb, l)
    }
}

func iter_cards(tb *TrelloBoard,
                tl *TrelloList,
                fn card_func) {
    for _, c := range tl.cards {
        fn(tb, tl, c)
    }
}

func print_board_info(tb *TrelloBoard) {
    fmt.Printf("[B] %s -> %s\n",
               tb.board["name"], tb.board["shortUrl"])
}

func print_list_info(tb *TrelloBoard,
                     tl *TrelloList) {
    fmt.Printf("[L] %s -> %s\n",
               tb.board["name"], tl.list["name"])
}

func print_card_info(tb *TrelloBoard,
                     tl *TrelloList,
                     tc *TrelloCard) {
    fmt.Printf("[C] %s -> %s -> %s -> %s\n",
               tb.board["name"], tl.list["name"], tc.card["name"], tc.card["shortUrl"])
}

func recurse_boards() {
    for _, tb := range all_boards {
        print_board_info(tb)
        for _, tl := range tb.lists {
            print_list_info(tb, tl)
            for _, tc := range tl.cards {
                print_card_info(tb, tl, tc)
            }
        }
    }
}

func tbprint(x   int,
             y   int,
             fg  termbox.Attribute,
             bg  termbox.Attribute,
             msg string) {
	for _, c := range msg {
		termbox.SetCell(x, y, c, fg, bg)
        if c == '\n' {
            x = 0
            y++
        } else {
            x++
        }
	}
}

func tbprint_reverse(x   int,
                     y   int,
                     fg  termbox.Attribute,
                     bg  termbox.Attribute,
                     msg string) {
    for i := len(msg)-1; i >= 0; i-- {
		termbox.SetCell(x, y, rune(msg[i]), fg, bg)
		x--
	}
}

func tbprint_width(y   int,
                   fg  termbox.Attribute,
                   bg  termbox.Attribute,
                   msg string) {
	w, _ := termbox.Size()
    x := 0
	for _, c := range msg {
		termbox.SetCell(x, y, c, fg, bg)
		x++
	}
    for x < w {
		termbox.SetCell(x, y, ' ', fg, bg)
		x++
    }
}

func tbprint_width_reverse(y   int,
                           fg  termbox.Attribute,
                           bg  termbox.Attribute,
                           msg string) {
	w, _ := termbox.Size()
    x := w-1
    for i := len(msg)-1; i >= 0; i-- {
		termbox.SetCell(x, y, rune(msg[i]), fg, bg)
		x--
	}
    for x >= 0 {
		termbox.SetCell(x, y, ' ', fg, bg)
		x--
    }
}

func idx_str(cur_idx  int,
             num_elem int) (string) {
    return fmt.Sprintf("(%d/%d)", cur_idx, num_elem)
}

func clear_screen() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
}

func draw_screen() {
	termbox.Flush()
}

func alloc_new_page(ptype int) (*Page) {
    page := new(Page)
    page.ptype = ptype
    switch ptype {
    case PageTypeAllBoards:
        page.start_line = 1
    case PageTypeBoard:
        page.start_line = 1
    case PageTypeList:
        page.start_line = 2
    case PageTypeCard:
        page.start_line = 3
    case PageTypeHelp:
        page.start_line = 1
    }
    page.board = nil
    page.list  = nil
    page.card  = nil
    return page
}

func draw_all_boards_page() {
    // first page shown... page stack is empty
    // this page will be pushed on the stack when the page changes

    page := alloc_new_page(PageTypeAllBoards)
    page.set_cursor(page.start_line, 0, true)

    current_page = page

    clear_screen()
	//w, _ := termbox.Size()

    title := fmt.Sprintf("BOARDS")
    tbprint_width(0,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    /*
    tbprint_reverse(w-1, 0,
                    termbox.ColorDefault,
                    termbox.ColorDefault | termbox.AttrReverse,
                    idx_str(1, len(all_boards)))
    */

    v := 1
    for i, tb := range all_boards {
        fg := termbox.ColorDefault
        bg := termbox.ColorDefault
        if i == 0 {
            fg = termbox.ColorYellow
            bg = termbox.ColorDefault | termbox.AttrBold
        }
        tbprint(0, v, fg, bg, tb.board["name"].(string))
        v++
    }

    draw_screen()
}

func print_message(msg string) {
    _, h := termbox.Size()
    tbprint_width(h-1,
                  termbox.ColorYellow,
                  termbox.ColorBlack | termbox.AttrReverse,
                  msg)
}

func draw_new_board_page() {
    push_page_on_stack()
    clear_screen()

    page := alloc_new_page(PageTypeBoard)
    page.board = all_boards[current_page.cursor.line-current_page.start_line]
    page.set_cursor(page.start_line, 0, true)

    current_page = page

    if page.board.lists_fetched == false {
        get_board_lists(false, page.board)
        page.board.lists_fetched = true
    }

	//w, _ := termbox.Size()

    title := fmt.Sprintf("BOARD: %s", page.board.board["name"])
    tbprint_width(0,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    /*
    tbprint_reverse(w-1, 0,
                    termbox.ColorDefault,
                    termbox.ColorDefault | termbox.AttrReverse,
                    idx_str(1, len(page.board.lists)))
    */

    v := 1
    for i, tl := range page.board.lists {
        fg := termbox.ColorDefault
        bg := termbox.ColorDefault
        if i == 0 {
            fg = termbox.ColorYellow
            bg = termbox.ColorDefault | termbox.AttrBold
        }
        tbprint(0, v, fg, bg, tl.list["name"].(string))
        v++
    }

    draw_screen()
}

func draw_new_list_page() {
    push_page_on_stack()
    clear_screen()

    page := alloc_new_page(PageTypeList)
    page.board = current_page.board
    page.list  = current_page.board.lists[current_page.cursor.line-current_page.start_line]
    page.set_cursor(page.start_line, 0, true)

    current_page = page

    if page.list.cards_fetched == false {
        get_list_cards(page.list)
        page.list.cards_fetched = true
    }

	//w, _ := termbox.Size()

    title := fmt.Sprintf("BOARD: %s", page.board.board["name"])
    tbprint_width(0,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    title = fmt.Sprintf("  LIST: %s", page.list.list["name"])
    tbprint_width(1,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    /*
    tbprint_reverse(w-1, 0,
                    termbox.ColorDefault,
                    termbox.ColorDefault | termbox.AttrReverse,
                    idx_str(1, len(page.list.cards)))
    */

    v := 2
    for i, tc := range page.list.cards {
        fg := termbox.ColorDefault
        bg := termbox.ColorDefault
        if i == 0 {
            fg = termbox.ColorYellow
            bg = termbox.ColorDefault | termbox.AttrBold
        }
        tbprint(0, v, fg, bg, tc.card["name"].(string))
        v++
    }

    draw_screen()
}

func draw_new_card_page() {
    push_page_on_stack()
    clear_screen()

    page := alloc_new_page(PageTypeCard)
    page.board = current_page.board
    page.list  = current_page.list
    page.card  = current_page.list.cards[current_page.cursor.line-current_page.start_line]
    page.set_cursor(page.start_line, 0, true)

    current_page = page

    title := fmt.Sprintf("BOARD: %s", page.board.board["name"])
    tbprint_width(0,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    title = fmt.Sprintf("  LIST: %s", page.list.list["name"])
    tbprint_width(1,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    title = fmt.Sprintf("    CARD: %s", page.card.card["name"])
    tbprint_width(2,
                  termbox.ColorDefault,
                  termbox.ColorDefault | termbox.AttrReverse,
                  title)

    v := 3

    fg := termbox.ColorDefault
    bg := termbox.ColorDefault

    tbprint(0, v, fg, bg, page.card.card["desc"].(string))

    // XXX get checklists

    draw_screen()
}

func draw_new_page() {
    switch current_page.ptype {
    case PageTypeAllBoards:
        draw_new_board_page()
    case PageTypeBoard:
        draw_new_list_page()
    case PageTypeList:
        draw_new_card_page()
    default:
        return
    }
}

func set_line_attr(line int,
                   fg termbox.Attribute,
                   bg termbox.Attribute) {
	w, _ := termbox.Size()

    cells := termbox.CellBuffer()

    for i := 0; i < w; i++ {
        cell := (line * w) + i
        cells[cell].Fg = fg
        cells[cell].Bg = bg
    }
}

func move_cursor(dir int) {
    new_line := current_page.cursor.line+dir

    set_line_attr(current_page.cursor.line,
                  termbox.ColorDefault,
                  termbox.ColorDefault)
    if current_page.ptype != PageTypeCard {
        set_line_attr(new_line,
                      termbox.ColorYellow,
                      termbox.ColorDefault | termbox.AttrBold)
    } else {
        set_line_attr(new_line,
                      termbox.ColorDefault,
                      termbox.ColorDefault)
    }

    current_page.set_cursor(new_line, current_page.cursor.column, true)

    draw_screen()
}

func move_cursor_down() {
    var max_len int
    ok := true

    switch current_page.ptype {
    case PageTypeAllBoards:
        max_len = len(all_boards)
    case PageTypeBoard:
        max_len = len(current_page.board.lists)
    case PageTypeList:
        max_len = len(current_page.list.cards)
    case PageTypeCard:
        max_len = 50 // XXX
    case PageTypeHelp:
        max_len = 50 // XXX
    default:
        ok = false
    }

    max_len += (current_page.start_line - 1)

    if ok && current_page.cursor.line < max_len {
        move_cursor(1)
    }
}

func move_cursor_up() {
    if current_page.cursor.line > current_page.start_line {
        move_cursor(-1)
    }
}

func push_page_on_stack() {
    page := termbox.CellBuffer()
    copy_page := new(Page)
    copy_page.cursor     = current_page.cursor
    copy_page.cells      = make([]termbox.Cell, len(page))
    copy_page.ptype      = current_page.ptype
    copy_page.start_line = current_page.start_line
    copy_page.board      = current_page.board
    copy_page.list       = current_page.list
    copy_page.card       = current_page.card

    for i, c := range page {
        copy_page.cells[i] = c
    }

    page_stack = append(page_stack, copy_page)
}

func pop_page_from_stack() {
    var page *Page
    page, page_stack = page_stack[len(page_stack)-1], page_stack[:len(page_stack)-1]

	w, _ := termbox.Size()

    clear_screen()

    for i, c := range page.cells {
        termbox.SetCell(i%w, i/w, c.Ch, c.Fg, c.Bg)
    }

    current_page = page

    draw_screen()
}

func main() {
    flag.Parse()

    do_oauth()

    err := termbox.Init()
    if err != nil {
        log.Fatal(err)
    }

    defer termbox.Close()
    termbox.SetInputMode(termbox.InputEsc)

    get_boards(false)

    page_stack = make([]*Page, 0)

    draw_all_boards_page()
    time.Sleep(1 * time.Second)

mainloop:
    for {
        ev := termbox.PollEvent()
        switch ev.Type {
        case termbox.EventKey:
            switch ev.Key {
            /*
            case termbox.KeyEsc:
                break mainloop
            */
            case termbox.KeyEnter:
                draw_new_page()
            default:
                switch ev.Ch {
                case 'Q':
                    break mainloop
                case 'q':
                    if len(page_stack) == 0 {
                        break mainloop
                    } else {
                        pop_page_from_stack()
                    }
                case 'j':
                    move_cursor_down()
                case 'k':
                    move_cursor_up()
                }
            }
        case termbox.EventError:
            log.Fatal(ev.Err)
        }
    }
}


text:
<?php
$currentPage = "abe";
$pageTitle = "Civil Rights Movement | ABE Lab";
$pageDesc = "Distance learning activities about the Civil Rights Movement for Adult Basic Education students.";
$activityCount = 0;
$refCount = 0;
require_once("config.php");
require_once(LIBRARY_PATH . "/activityListFunctions.php");

ob_start();
?>

WebLearn

<a href="<?php echo $abeRoutes['abeHome']; ?>">ABE Lab

<a href="<?php echo $abeRoutes['socialStudies']['civilRights']; ?>">Civil Rights Movement

<?php
$pageBreadbrumbs = ob_get_contents();
ob_get_clean();

ob_start();
?>

ABE Lab

        Springfield Adult Learning Center

Civil Rights Movement

        <?php preMediaBlock(); ?>

<a href="<?php echo $abeRoutes['socialStudies']['majorEvents']; ?>" class="alt-link-color"><?php echo ++$activityCount . ". "; ?>The Civil Rights Movement: Major Events

A brief introduction to some of the major events of the Civil Rights movement.

                <img src="<?php echo $config['paths']['img']['content'] . '/crm-major-events.jpg'; ?>" alt="The Civil Rights Movement: Major Events">

<a href="<?php echo $abeRoutes['socialStudies']['majorEvents']; ?>" class="btn btn-primary" role="button">Open

<?php echo ++$activityCount . ". "; ?>Brown v. Board of Education

Read about the Brown v. Board of Education Supreme Court case, which challenged the lawfulness of racial segregation in public schools.

                <img src="<?php echo $config['paths']['img']['content'] . '/brown-board-of-education.png'; ?>" alt="Brown v. Board of Education">

Open

<?php echo ++$activityCount . ". "; ?>The Montgomery Bus Boycott

Read about how the 1955 arrest of Rosa Parks led to the Montgomery Bus Boycott.

                <img src="<?php echo $config['paths']['img']['content'] . '/the-montgomery-bus-boycott.png'; ?>" alt="The Montgomery Bus Boycott">

Open

<?php echo ++$activityCount . ". "; ?>The Little Rock Nine

Read about the Little Rock Nine and the desegregation of Little Rock Central High School.

                <img src="<?php echo $config['paths']['img']['content'] . '/the-little-rock-nine.png'; ?>" alt="The Little Rock Nine">

Open

<?php echo ++$activityCount . ". "; ?>The Sit-In Movement

Read about how "sit-ins" were used as a nonviolent strategy to gain awareness about civil rights issues.

                <img src="<?php echo $config['paths']['img']['content'] . '/the-sit-in-movement.png'; ?>" alt="The Sit-In Movement">

Open

<?php echo ++$activityCount . ". "; ?>Martin Luther King Jr.

Read about one of the most recognizable advocates of nonviolent action in the Civil Rights Movement, Dr. Martin Luther King Jr.

                <img src="<?php echo $config['paths']['img']['content'] . '/martin-luther-king-jr.png'; ?>" alt="Martin Luther King Jr.">

Open

<?php echo ++$activityCount . ". "; ?>Malcolm X

Read about Malcolm X and the Nation of Islam.

                <img src="<?php echo $config['paths']['img']['content'] . '/malcolm-x.png'; ?>" alt="Malcolm X">

Open

<?php echo ++$activityCount . ". "; ?>Black Power

Read about the Black Power Movement and then answer the multiple choice questions located below the text.

                <img src="<?php echo $config['paths']['img']['content'] . '/black-power.png'; ?>" alt="Black Power">

Open

<?php echo ++$activityCount . ". "; ?>Civil Rights Act of 1964

Watch a video and then read an article about the Civil Rights Act of 1964.

                <img src="<?php echo $config['paths']['img']['content'] . '/civil-rights-act-1964.png'; ?>" alt="Civil Rights Act of 1964">

Open

<?php echo ++$activityCount . ". "; ?>Voting Rights Act of 1965

Read an article about the Voting Rights Act of 1965.

                <img src="<?php echo $config['paths']['img']['content'] . '/voting-rights-act-1965.png'; ?>" alt="Voting Rights Act of 1965">

Open

<?php echo ++$activityCount . ". "; ?>Interactive Civil Rights Timeline

Explore this interactive timeline of important events that affected the struggle for obtaining civil rights.

The timeline begins when the first slaves were brought to the New World from Africa in 1502 and ends in the year 2000.

Click on a specific date to view the events that took place. Click "next" to view the next event on the timeline.

                <img src="<?php echo $config['paths']['img']['content'] . '/interactive-civil-rights-timeline.png'; ?>" alt="Interactive Civil Rights Timeline">

Open

Credits:

<?php echo ++$refCount . ". "; ?>WatchMojo.

<?php echo ++$refCount . ". "; ?>history.com.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>U.S. History: Pre-Columbian to the New Millennium.

<?php echo ++$refCount . ". "; ?>history.com.

<?php echo ++$refCount . ". "; ?>history.com.

<?php echo ++$refCount . ". "; ?>Yale: Interactive Civil Rights Chronology.

        <?php postMediaBlock(); ?>

<?php
$activityItems = ob_get_contents();
ob_get_clean();

$variables = array(
    "pageBreadbrumbs" => $pageBreadbrumbs,
    "activityItems" => $activityItems
);
renderActivityListLayout("/activityList.php", $variables);
?>

redpajama_set_name: RedPajamaGithub


text: module.exports.DEV = 'development';


text:
@interface ARFairMapPreview : ARAnnotatedMapView

- (id)initWithFairMap:(Map *)map andFrame:(CGRect)frame;

- (void)addHighlightedShow:(PartnerShow *)show animated:(BOOL)animated;
- (void)addShows:(NSArray *)shows animated:(BOOL)animated;

@end


text:
<?php
/**
 * Seeder example
 *
 * @package StealThisTracker
 * @author  StealThisShow <info@stealthisshow.com>
 * @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause
 */

use \StealThisShow\StealThisTracker\Persistence\Pdo;
use \StealThisShow\StealThisTracker\Seeder\Peer;
use \StealThisShow\StealThisTracker\Seeder\Server;
use \StealThisShow\StealThisTracker\Logger\File;

// --------------------------------------
// This is how to start a seeding server.
// --------------------------------------

// [!] Run this file in CLI only!
// /usr/bin/php example_seeder.php

// Composer autoloader
require dirname(__FILE__) . '/../vendor/autoload.php';

// Persistence object implementing PersistenceInterface.
// We use Pdo here.
$persistence = new Pdo('sqlite:sqlite_example.db');

// Setting up seeder peer. This will listen to connections and serve files.
$peer = new Peer($persistence);
$peer
    // Private address of the seeder server.
    // (Optional parameter for IP to open socket on if differs from external.)
    ->setInternalAddress('192.168.2.123')
    // Public address of the seeder server.
    // This will be used for announcements (ie. sent to the clients).
    ->setExternalAddress('192.168.2.123')
    // Don't forget the firewall!
    ->setPort(6881)
    // Number telling how many processes
    // should be forked to listen to incoming connections.
    ->setPeerForks(10)
    // If specified, gives a number of outsider seeders to make self-seeding stop.
    // This saves you bandwidth - once your
    // file is seeded by others, you can stop serving it.
    // Number of seeders is permanently checked,
    // but probably 1 is too few if you want your file to be available always.
    ->setSeedersStopSeeding(5)
    // Initializing file logger with default
    // file path (/var/log/stealthistracker.log).
    ->setLogger(new File());

// We set up a seeding server which starts the seeding peer, and makes regular
// announcements to the database adding itself to the peer list for all
// active torrents.
$server = new Server($peer, $persistence);
// Initializing file logger with default file path (/var/log/stealthistracker.log).
$server->setLogger(new File());

// Starting "detached" means that process
// will unrelate from terminal and run as daemon.
// To run in terminal, you can use start().
// Detached running requires php-posix.
$server->startDetached();


text:
#pragma once
#include <aws/inspector/Inspector_EXPORTS.h>
#include <aws/inspector/InspectorRequest.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Inspector
{
namespace Model
{

  /**
   */
  class AWS_INSPECTOR_API DescribeResourceGroupsRequest : public InspectorRequest
  {
  public:
    DescribeResourceGroupsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeResourceGroups"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline const Aws::Vector<Aws::String>& GetResourceGroupArns() const{ return m_resourceGroupArns; }

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline void SetResourceGroupArns(const Aws::Vector<Aws::String>& value) { m_resourceGroupArnsHasBeenSet = true; m_resourceGroupArns = value; }

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline void SetResourceGroupArns(Aws::Vector<Aws::String>&& value) { m_resourceGroupArnsHasBeenSet = true; m_resourceGroupArns = std::move(value); }

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline DescribeResourceGroupsRequest& WithResourceGroupArns(const Aws::Vector<Aws::String>& value) { SetResourceGroupArns(value); return *this;}

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline DescribeResourceGroupsRequest& WithResourceGroupArns(Aws::Vector<Aws::String>&& value) { SetResourceGroupArns(std::move(value)); return *this;}

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline DescribeResourceGroupsRequest& AddResourceGroupArns(const Aws::String& value) { m_resourceGroupArnsHasBeenSet = true; m_resourceGroupArns.push_back(value); return *this; }

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline DescribeResourceGroupsRequest& AddResourceGroupArns(Aws::String&& value) { m_resourceGroupArnsHasBeenSet = true; m_resourceGroupArns.push_back(std::move(value)); return *this; }

    /**
     *
The ARN that specifies the resource group that you want to describe.

     */
    inline DescribeResourceGroupsRequest& AddResourceGroupArns(const char* value) { m_resourceGroupArnsHasBeenSet = true; m_resourceGroupArns.push_back(value); return *this; }

  private:

    Aws::Vector<Aws::String> m_resourceGroupArns;
    bool m_resourceGroupArnsHasBeenSet;
  };

} // namespace Model
} // namespace Inspector
} // namespace Aws


text:
<!DOCTYPE HTML>

<title>PathStepType (Library-of-Gongolierium 4.0.7 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-02-24">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

Package com.thegongoliers.paths

Enum PathStepType

java.lang.Object

java.lang.Enum<PathStepType>

com.thegongoliers.paths.PathStepType

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<PathStepType>

public enum PathStepType
extends java.lang.Enum<PathStepType>

Enum Constant Summary

Enum Constants

Enum Constant
Description

ROTATION

STRAIGHT_AWAY

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method
Description

static PathStepType
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static PathStepType[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ROTATION

public static final PathStepType ROTATION

STRAIGHT_AWAY

public static final PathStepType STRAIGHT_AWAY

Method Detail

values

public static PathStepType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:

for (PathStepType c : PathStepType.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static PathStepType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".UserDetailsActivity"
    android:background="@color/colorPrimary"
    android:padding="20sp">

    <de.hdodenhof.circleimageview.CircleImageView

        android:layout_width="140sp"
        android:layout_height="140sp"
        android:layout_gravity="center"
        android:id="@+id/profileimage"
        android:layout_margin="30dp"/>

    <TextView
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:textSize="18sp"
        android:textStyle="bold"
        android:hint=""
        android:layout_marginBottom="20sp"/>

    <TextView
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/company"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:textSize="18sp"
        android:textStyle="bold"
        android:hint=""
        android:layout_marginBottom="20sp"/>

    <TextView
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:textSize="18sp"
        android:textStyle="bold"
        android:hint=""
        android:layout_marginBottom="20sp"/>

    <TextView
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/doj"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:textSize="18sp"
        android:textStyle="bold"
        android:hint=""
        android:layout_marginBottom="20sp"/>

    <Button
        android:layout_margin="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/github"
        android:textColor="@color/colorPrimary"
        android:textSize="18sp"
        android:textStyle="bold"
        android:text="Github"/>

</LinearLayout>


text:
import React, { FC, ReactNode, useState } from 'react';
import { css, cx } from 'emotion';
import { GrafanaTheme } from '@savantly/sprout-api';
import { useStyles } from '../../themes';
import { Icon } from '..';

export interface Props {
  label: string;
  isOpen: boolean;
  children: ReactNode;
}

export const CollapsableSection: FC<Props> = ({ label, isOpen, children }) => {
  const [open, toggleOpen] = useState<boolean>(isOpen);
  const styles = useStyles(collapsableSectionStyles);
  const headerClass = cx({
    [styles.header]: true,
    [styles.headerCollapsed]: !open,
  });

  const tooltip = `Click to ${open ? 'collapse' : 'expand'}`;

  return (

 toggleOpen(!open)} className={headerClass} title={tooltip}>
        {label}
        <Icon name={open ? 'angle-down' : 'angle-right'} size="xl" className={styles.icon} />

      {open &&
{children}
}

  );
};

const collapsableSectionStyles = (theme: GrafanaTheme) => {
  return {
    header: css`
      display: flex;
      justify-content: space-between;
      font-size: ${theme.typography.size.lg};
      cursor: pointer;
    `,
    headerCollapsed: css`
      border-bottom: 1px solid ${theme.colors.border2};
    `,
    icon: css`
      color: ${theme.colors.textWeak};
    `,
    content: css`
      padding: ${theme.spacing.md} 0;
    `,
  };
};


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Threading.Tasks;
using System.Threading;
using Windows.UI.Core;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.System.Threading;
using System.Diagnostics;
using Buffalo.WiFiDirect;

namespace ShareWith
{
    public sealed partial class MainPage : Page
    {
        int BLOCK_SIZE = 1024;
        internal async Task SendFileToPeerAsync(StreamSocket socket, StorageFile selectedFile)
        {
            byte[] buff = new byte[BLOCK_SIZE];
            var prop = await selectedFile.GetBasicPropertiesAsync();
            using (var dw = new DataWriter(socket.OutputStream))
            {

                // 1. Send the filename length
                dw.WriteInt32(selectedFile.Name.Length); // filename length is fixed
                // 2. Send the filename
                dw.WriteString(selectedFile.Name);
                // 3. Send the file length
                dw.WriteUInt64(prop.Size);
                // 4. Send the file
                var fileStream = await selectedFile.OpenStreamForReadAsync();
                while (fileStream.Position < (long)prop.Size)
                {
                    var rlen = await fileStream.ReadAsync(buff, 0, buff.Length);
                    dw.WriteBytes(buff);
                }

                await dw.FlushAsync();
                await dw.StoreAsync();

                await socket.OutputStream.FlushAsync();
            }
        }

        internal async Task<string> ReceiveFileFomPeer(StreamSocket socket, StorageFolder folder, string outputFilename = null)
        {
            StorageFile file;
            using (var rw = new DataReader(socket.InputStream))
            {
                // 1. Read the filename length
                await rw.LoadAsync(sizeof(Int32));
                var filenameLength = (uint)rw.ReadInt32();
                // 2. Read the filename
                await rw.LoadAsync(filenameLength);
                var originalFilename = rw.ReadString(filenameLength);
                if (outputFilename == null)
                {
                    outputFilename = originalFilename;
                }
                //3. Read the file length
                await rw.LoadAsync(sizeof(UInt64));
                var fileLength = rw.ReadUInt64();

                // 4. Reading file
                using (var memStream = await DownloadFile(rw, fileLength))
                {

                    file = await folder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting);
                    using (var fileStream1 = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await RandomAccessStream.CopyAndCloseAsync(memStream.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0));
                    }

                    rw.DetachStream();
                }
            }

            return file.Path;
        }

        internal async Task<InMemoryRandomAccessStream> DownloadFile(DataReader rw, ulong fileLength)
        {
            var memStream = new InMemoryRandomAccessStream();

            // Download the file
            while (memStream.Position < fileLength)
            {
                var lenToRead = Math.Min(BLOCK_SIZE, (float)(fileLength - memStream.Position));
                await rw.LoadAsync((uint)lenToRead);
                var tempBuff = rw.ReadBuffer((uint)lenToRead);
                await memStream.WriteAsync(tempBuff);
            }

            return memStream;
        }

        internal async Task<StorageFile> FileChooser()
        {

            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.ViewMode = PickerViewMode.List;
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add("*");

            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                return file;
            }
            else
            {
                throw new FileNotFoundException("없지로오옹~ > <");
            }
        }
    }
}


text:
<?php

/* Hi5EvaluatieQuestion Fixture generated on: 2011-04-15 15:04:32 : 1302873152 */
class Hi5EvaluatieQuestionFixture extends CakeTestFixture
{
    public $name = 'Hi5EvaluatieQuestion';
    public $import = array('model' => 'Hi5EvaluatieQuestion', 'records' => true);
}


text:
package main

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"

	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

const (
	projectOwner = "golang"
	projectRepo  = "go"
)

var githubClient *github.Client

// GitHub personal access token, from https://github.com/settings/applications.
var githubAuthToken string

func loadGithubAuth() {
	const short = ".github-issue-token"
	filename := filepath.Clean(os.Getenv("HOME") + "/" + short)
	shortFilename := filepath.Clean("$HOME/" + short)
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatal("reading token: ", err, "\n\n"+
			"Please create a personal access token at https://github.com/settings/tokens/new\n"+
			"and write it to ", shortFilename, " to use this program.\n"+
			"The token only needs the repo scope, or private_repo if you want to\n"+
			"view or edit issues for private repositories.\n"+
			"The benefit of using a personal access token over using your GitHub\n"+
			"password directly is that you can limit its use and revoke it at any time.\n\n")
	}
	fi, err := os.Stat(filename)
	if fi.Mode()&0077 != 0 {
		log.Fatalf("reading token: %s mode is %#o, want %#o", shortFilename, fi.Mode()&0777, fi.Mode()&0700)
	}
	githubAuthToken = strings.TrimSpace(string(data))
	t := &oauth2.Transport{
		Source: &tokenSource{AccessToken: githubAuthToken},
	}
	githubClient = github.NewClient(&http.Client{Transport: t})
}

// releaseStatusTitle returns the title of the release status issue
// for the given milestone.
// If you change this function, releasebot will not be able to find an
// existing tracking issue using the old name and will create a new one.
func releaseStatusTitle(m *github.Milestone) string {
	return "all: " + strings.Replace(m.GetTitle(), "Go", "Go ", -1) + " release status"
}

type tokenSource oauth2.Token

func (t *tokenSource) Token() (*oauth2.Token, error) {
	return (*oauth2.Token)(t), nil
}

func loadMilestones() ([]*github.Milestone, error) {
	// NOTE(rsc): There appears to be no paging possible.
	all, _, err := githubClient.Issues.ListMilestones(context.TODO(), projectOwner, projectRepo, &github.MilestoneListOptions{
		State: "open",
	})
	if err != nil {
		return nil, err
	}
	if all == nil {
		all = []*github.Milestone{}
	}
	return all, nil
}

// findIssues finds all the issues for the given milestone and
// categorizes them into approved cherry-picks (w.Picks)
// and other issues (w.OtherIssues).
// It also finds the release summary issue (w.ReleaseIssue).
func (w *Work) findIssues() {
	issues, err := listRepoIssues(github.IssueListByRepoOptions{
		Milestone: fmt.Sprint(w.Milestone.GetNumber()),
	})
	if err != nil {
		w.log.Panic(err)
	}

	for _, issue := range issues {
		if issue.GetTitle() == releaseStatusTitle(w.Milestone) {
			if w.ReleaseIssue != nil {
				w.log.Printf("**warning**: multiple release issues: #%d and #%d\n", w.ReleaseIssue.GetNumber(), issue.GetNumber())
				continue
			}
			w.ReleaseIssue = issue
			continue
		}
		if hasLabel(issue, "cherry-pick-approved") {
			w.Picks = append(w.Picks, issue)
			continue
		}
		w.OtherIssues = append(w.OtherIssues, issue)
	}
	sort.Slice(w.Picks, func(i, j int) bool { return w.Picks[i].GetNumber() < w.Picks[j].GetNumber() })

	if w.ReleaseIssue == nil {
		title := releaseStatusTitle(w.Milestone)
		body := wrapStatus(w.Milestone, "Nothing yet.")
		req := &github.IssueRequest{
			Title:     &title,
			Body:      &body,
			Milestone: w.Milestone.Number,
		}
		issue, _, err := githubClient.Issues.Create(context.TODO(), projectOwner, projectRepo, req)
		if err != nil {
			w.log.Panic(err)
		}
		w.ReleaseIssue = issue
	}
}

// listRepoIssues wraps Issues.ListByRepo to deal with paging.
func listRepoIssues(opt github.IssueListByRepoOptions) ([]*github.Issue, error) {
	var all []*github.Issue
	for page := 1; ; {
		xopt := opt
		xopt.ListOptions = github.ListOptions{
			Page:    page,
			PerPage: 100,
		}
		list, resp, err := githubClient.Issues.ListByRepo(context.TODO(), projectOwner, projectRepo, &xopt)
		all = append(all, list...)
		if err != nil {
			return all, err
		}
		if resp.NextPage < page {
			break
		}
		page = resp.NextPage
	}
	return all, nil
}

// hasLabel reports whether issue has the given label.
func hasLabel(issue *github.Issue, label string) bool {
	for _, l := range issue.Labels {
		if l.GetName() == label {
			return true
		}
	}
	return false
}

var clOK = regexp.MustCompile(`(?i)^CL (\d+) OK(( for Go \d+\.\d+\.\d+)?.*)`)
var afterCL = regexp.MustCompile(`(?i)after CL (\d+)`)

// listIssueComments wraps Issues.ListComments to deal with paging.
func listIssueComments(number int) ([]*github.IssueComment, error) {
	var all []*github.IssueComment
	for page := 1; ; {
		list, resp, err := githubClient.Issues.ListComments(context.TODO(), projectOwner, projectRepo, number, &github.IssueListCommentsOptions{
			ListOptions: github.ListOptions{
				Page:    page,
				PerPage: 100,
			},
		})
		all = append(all, list...)
		if err != nil {
			return all, err
		}
		if resp.NextPage < page {
			break
		}
		page = resp.NextPage
	}
	return all, nil
}

func (w *Work) findCLs() {
	// Preload all CLs in parallel.
	type comments struct {
		list []*github.IssueComment
		err  error
	}
	preload := make([]comments, len(w.Picks))
	var wg sync.WaitGroup
	for i, pick := range w.Picks {
		i := i
		number := pick.GetNumber()
		wg.Add(1)
		go func() {
			defer wg.Done()
			list, err := listIssueComments(number)
			preload[i] = comments{list, err}
		}()
	}
	wg.Wait()

	var cls []*CL
	for i, pick := range w.Picks {
		number := pick.GetNumber()
		fmt.Printf("load #%d\n", number)
		found := false
		list, err := preload[i].list, preload[i].err
		if err != nil {
			w.log.Panic(err)
		}
		var last *CL
		for _, com := range list {
			user := com.User.GetLogin()
			text := com.GetBody()
			for _, line := range strings.Split(text, "\n") {
				if m := clOK.FindStringSubmatch(line); m != nil {
					if m[3] != " for Go "+strings.TrimPrefix(w.Milestone.GetTitle(), "Go") {
						w.log.Printf("#%d: %s: wrong milestone: %s\n", number, user, line)
						continue
					}
					if !githubCherryPickApprovers[user] {
						w.log.Printf("#%d: %s: not an approver: %s\n", number, user, line)
						continue
					}
					n, err := strconv.Atoi(m[1])
					if err != nil {
						w.log.Printf("#%d: %s: invalid CL number: %s\n", number, user, line)
						continue
					}
					cl := &CL{Num: n, Approver: user, Issues: []int{number}}
					if last != nil {
						cl.Prereq = []int{last.Num}
					}
					for _, am := range afterCL.FindAllStringSubmatch(m[2], -1) {
						n, err := strconv.Atoi(am[1])
						if err != nil {
							w.log.Printf("#%d: %s: invalid after CL number: %s\n", number, user, line)
							continue
						}
						cl.Prereq = append(cl.Prereq, n)
					}
					cls = append(cls, cl)
					found = true
					last = cl
				}
			}
		}
		if !found {
			log.Printf("#%d: has cherry-pick-approved label but no approvals found", number)
		}
	}

	sort.Slice(cls, func(i, j int) bool {
		return cls[i].Num < cls[j].Num || cls[i].Num == cls[j].Num && cls[i].Approver < cls[j].Approver
	})

	out := cls[:0]
	var last CL
	for _, cl := range cls {
		if cl.Num == last.Num {
			end := out[len(out)-1]
			if cl.Approver != last.Approver {
				end.Approver += "," + cl.Approver
			}
			end.Issues = append(end.Issues, cl.Issues...)
			end.Prereq = append(end.Prereq, cl.Prereq...)
		} else {
			out = append(out, cl)
		}
		last = *cl
	}
	w.CLs = out
}

func (w *Work) closeIssues() {
	all := append(w.Picks[:len(w.Picks):len(w.Picks)], w.ReleaseIssue)
	for _, issue := range all {
		if issue.GetState() == "closed" {
			continue
		}
		number := issue.GetNumber()
		var md bytes.Buffer
		fmt.Fprintf(&md, "%s has been packaged and includes:\n\n", w.Version)
		for _, cl := range w.CLs {
			match := issue == w.ReleaseIssue
			for _, n := range cl.Issues {
				if n == number {
					match = true
					break
				}
			}
			if match {
				fmt.Fprintf(&md, "  - %s %s\n", mdChangeLink(cl.Num), mdEscape(cl.Title))
			}
		}
		fmt.Fprintf(&md, "\nThe release is posted at [golang.org/dl](https://golang.org/dl).\n")
		md.WriteString(signature())
		postGithubComment(number, md.String())
		closed := "closed"
		_, _, err := githubClient.Issues.Edit(context.TODO(), projectOwner, projectRepo, number, &github.IssueRequest{
			State: &closed,
		})
		if err != nil {
			w.logError(nil, fmt.Sprintf("closing #%d: %v", number, err))
		}
	}
}

func (w *Work) closeMilestone() {
	closed := "closed"
	_, _, err := githubClient.Issues.EditMilestone(context.TODO(), projectOwner, projectRepo, w.Milestone.GetNumber(), &github.Milestone{
		State: &closed,
	})
	if err != nil {
		w.logError(nil, fmt.Sprintf("closing milestone: %v", err))
	}

}

func findGithubComment(number int, prefix string) *github.IssueComment {
	list, _ := listIssueComments(number)
	for _, com := range list {
		if strings.HasPrefix(com.GetBody(), prefix) {
			return com
		}
	}
	return nil
}

func updateGithubComment(number int, com *github.IssueComment, body string) error {
	_, _, err := githubClient.Issues.EditComment(context.TODO(), projectOwner, projectRepo, number, &github.IssueComment{
		ID:   com.ID,
		Body: &body,
	})
	return err
}

func postGithubComment(number int, body string) error {
	_, _, err := githubClient.Issues.CreateComment(context.TODO(), projectOwner, projectRepo, number, &github.IssueComment{
		Body: &body,
	})
	return err
}


text:
<?php
$old_password = array(
	'name'	=> 'old_password',
	'id'	=> 'old_password',
	'value' => set_value('old_password'),
	'size' 	=> 30,
);
$new_password = array(
	'name'	=> 'new_password',
	'id'	=> 'new_password',
	'maxlength'	=> $this->config->item('password_max_length', 'tank_auth'),
	'size'	=> 30,
);
$confirm_new_password = array(
	'name'	=> 'confirm_new_password',
	'id'	=> 'confirm_new_password',
	'maxlength'	=> $this->config->item('password_max_length', 'tank_auth'),
	'size' 	=> 30,
);
 /* ?>

<title><?php echo $this->lang->line('change_password').$this->lang->line('title_universal');?></title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/jquery.dataTables.css">

  <?php
  if($role_id==1){
		     $this->load->view ('inc/top_bar');
		  }elseif($role_id==2){
		     $this->load->view ('inc/clinic_top_bar');
		  }elseif($role_id==3){
		      $this->load->view ('inc/practitioner_top_bar');
		  }elseif($role_id==4){
		      $this->load->view ('inc/patient_top_bar');
		  }else{
		      $this->load->view ('inc/clinic_top_bar');
		  }
  ?>

          <?php
          if($role_id==1){
		     $this->load->view ('inc/admin_left_nav');
		  }elseif($role_id==2){
		     $this->load->view ('inc/clinic_left_nav');
		  }elseif($role_id==3){
		      $this->load->view ('inc/practitioner_left_nav');
		  }elseif($role_id==4){
		      $this->load->view ('inc/patient_left_nav');
		  }else{
		      $this->load->view ('inc/clinic_location_left_nav');
		  }
          ?>

			<?php if($this->session->flashdata('display_message')) { ?>

 <?php echo $this->session->flashdata('display_message');?>

			<?php } ?>

Change Password

      <?php */ ?>

              <?php echo form_open($this->uri->uri_string(),array('class' => 'form-horizontal form_health','id' => 'change_password')); ?>
                <fieldset>
                  <legend><?php echo $this->lang->line('general_info');?></legend>

                    Old Password*

						<?php echo form_password($old_password,'',"class='form-control'"); ?>
						<?php echo form_error($old_password['name']); ?>

                    New Password*

					     <?php echo form_password($new_password,'',"class='form-control'"); ?>
						 <?php echo form_error($new_password['name']); ?>

                    Confirm New Password*

						<?php echo form_password($confirm_new_password,'',"class='form-control'"); ?>
						<?php echo form_error($confirm_new_password['name']); ?>

                      <?php //echo form_hidden('action', $action);
					  echo form_submit('change', 'Change Password',"class='btn btn-primary btn-block'"); ?>

                  <?php echo form_close();?>

                </fieldset>

        <?php /* ?>

 <button type="button" style="display:none;" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"></button>

<?php $this->load->view ('inc/footer');?>

*
<?php */?>


text:
layout: post
microblog: true
date: 2007-12-21 03:00 +0300
guid: http://desparoz.micro.blog/2007/12/21/t520423682.html
---
Going to see Billy Elliot musical tonight


text:
require('babel/register')({
  // Only compile test files
  only: /-test.js$/
});


text:
require 'active_model/validator'

class BicValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors.add(attribute, :invalid) unless Bank::BIC.valid?(value)
  end
end


text:
package com.google.api.gax.grpc;

import static org.junit.Assert.assertEquals;

import com.google.api.gax.batching.BatchingSettings;
import com.google.api.gax.core.CredentialsProvider;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.paging.PagedListResponse;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.BatchingDescriptor;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.FixedWatchdogProvider;
import com.google.api.gax.rpc.NoHeaderProvider;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.mtls.MtlsProvider;
import com.google.auth.Credentials;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.truth.Truth;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import org.threeten.bp.Duration;

@RunWith(JUnit4.class)
public class SettingsTest {

  interface FakePagedListResponse extends PagedListResponse<Integer> {}

  private static class FakeStubSettings extends StubSettings<FakeStubSettings> {

    @SuppressWarnings("unchecked")
    private static final PagedListResponseFactory<Integer, Integer, FakePagedListResponse>
        fakePagedListResponseFactory = Mockito.mock(PagedListResponseFactory.class);

    @SuppressWarnings("unchecked")
    private static final BatchingDescriptor<Integer, Integer> FAKE_BATCHING_DESCRIPTOR =
        Mockito.mock(BatchingDescriptor.class);

    private static final String DEFAULT_GAPIC_NAME = "gapic";
    public static final String DEFAULT_SERVICE_ADDRESS = "pubsub-experimental.googleapis.com";
    public static final int DEFAULT_SERVICE_PORT = 443;
    public static final String DEFAULT_SERVICE_ENDPOINT =
        DEFAULT_SERVICE_ADDRESS + ':' + DEFAULT_SERVICE_PORT;
    public static final MtlsProvider DEFAULT_MTLS_PROVIDER = new MtlsProvider();
    public static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
        ImmutableList.<String>builder()
            .add("https://www.googleapis.com/auth/pubsub")
            .add("https://www.googleapis.com/auth/cloud-platform")
            .build();

    private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
        RETRYABLE_CODE_DEFINITIONS;

    static {
      ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
          ImmutableMap.builder();
      definitions.put(
          "idempotent",
          ImmutableSet.copyOf(
              Lists.newArrayList(StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
      definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
      RETRYABLE_CODE_DEFINITIONS = definitions.build();
    }

    private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;

    static {
      ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
      RetrySettings settings = null;
      settings =
          RetrySettings.newBuilder()
              .setInitialRetryDelay(Duration.ofMillis(100L))
              .setRetryDelayMultiplier(1.2)
              .setMaxRetryDelay(Duration.ofMillis(1000L))
              .setInitialRpcTimeout(Duration.ofMillis(2000L))
              .setRpcTimeoutMultiplier(1.5)
              .setMaxRpcTimeout(Duration.ofMillis(30000L))
              .setTotalTimeout(Duration.ofMillis(45000L))
              .build();
      definitions.put("default", settings);
      RETRY_PARAM_DEFINITIONS = definitions.build();
    }

    private final UnaryCallSettings<Integer, Integer> fakeMethodSimple;
    private final PagedCallSettings<Integer, Integer, FakePagedListResponse> fakePagedMethod;
    private final BatchingCallSettings<Integer, Integer> fakeMethodBatching;

    public UnaryCallSettings<Integer, Integer> fakeMethodSimple() {
      return fakeMethodSimple;
    }

    public PagedCallSettings<Integer, Integer, FakePagedListResponse> fakePagedMethod() {
      return fakePagedMethod;
    }

    public BatchingCallSettings<Integer, Integer> fakeMethodBatching() {
      return fakeMethodBatching;
    }

    public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
      return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
    }

    public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
      return InstantiatingExecutorProvider.newBuilder();
    }

    /** Returns a builder for the default TransportChannelProvider for this service. */
    public static InstantiatingGrpcChannelProvider.Builder defaultGrpcChannelProviderBuilder() {
      return InstantiatingGrpcChannelProvider.newBuilder()
          .setEndpoint(DEFAULT_SERVICE_ENDPOINT)
          .setMtlsProvider(DEFAULT_MTLS_PROVIDER);
    }

    public static ApiClientHeaderProvider.Builder defaultGoogleServiceHeaderProviderBuilder() {
      return ApiClientHeaderProvider.newBuilder()
          .setGeneratedLibToken(DEFAULT_GAPIC_NAME, "0.10.0")
          .setTransportToken(
              GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
    }

    public static TransportChannelProvider defaultTransportChannelProvider() {
      return defaultGrpcChannelProviderBuilder().build();
    }

    public static Builder newBuilder() {
      return Builder.createDefault();
    }

    @Override
    public Builder toBuilder() {
      return new Builder(this);
    }

    private FakeStubSettings(Builder settingsBuilder) {
      super(settingsBuilder);

      fakeMethodSimple = settingsBuilder.fakeMethodSimple().build();
      fakePagedMethod = settingsBuilder.fakePagedMethod().build();
      fakeMethodBatching = settingsBuilder.fakeMethodBatching().build();
    }

    private static class Builder extends StubSettings.Builder<FakeStubSettings, Builder> {

      private UnaryCallSettings.Builder<Integer, Integer> fakeMethodSimple;
      private PagedCallSettings.Builder<Integer, Integer, FakePagedListResponse> fakePagedMethod;
      private BatchingCallSettings.Builder<Integer, Integer> fakeMethodBatching;

      private Builder() {
        super((ClientContext) null);

        fakeMethodSimple = UnaryCallSettings.newUnaryCallSettingsBuilder();
        fakePagedMethod = PagedCallSettings.newBuilder(fakePagedListResponseFactory);
        fakeMethodBatching =
            BatchingCallSettings.newBuilder(FAKE_BATCHING_DESCRIPTOR)
                .setBatchingSettings(BatchingSettings.newBuilder().build());
      }

      private static Builder createDefault() {
        Builder builder = new Builder();
        builder.setTransportChannelProvider(defaultTransportChannelProvider());
        builder.setExecutorProvider(defaultExecutorProviderBuilder().build());
        builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
        builder.setHeaderProvider(new NoHeaderProvider());
        builder.setInternalHeaderProvider(defaultGoogleServiceHeaderProviderBuilder().build());
        builder.setStreamWatchdogProvider(FixedWatchdogProvider.create(null));

        builder
            .fakeMethodSimple()
            .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
            .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));

        builder
            .fakePagedMethod()
            .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
            .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));

        builder
            .fakeMethodBatching()
            .setBatchingSettings(
                BatchingSettings.newBuilder()
                    .setElementCountThreshold(800L)
                    .setRequestByteThreshold(8388608L)
                    .setDelayThreshold(Duration.ofMillis(100))
                    .build());
        builder
            .fakeMethodBatching()
            .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
            .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));

        return builder;
      }

      private Builder(FakeStubSettings settings) {
        super(settings);

        fakeMethodSimple = settings.fakeMethodSimple().toBuilder();
        fakePagedMethod = settings.fakePagedMethod().toBuilder();
        fakeMethodBatching = settings.fakeMethodBatching().toBuilder();
      }

      @Override
      public FakeStubSettings build() throws IOException {
        return new FakeStubSettings(this);
      }

      public UnaryCallSettings.Builder<Integer, Integer> fakeMethodSimple() {
        return fakeMethodSimple;
      }

      public PagedCallSettings.Builder<Integer, Integer, FakePagedListResponse> fakePagedMethod() {
        return fakePagedMethod;
      }

      public BatchingCallSettings.Builder<Integer, Integer> fakeMethodBatching() {
        return fakeMethodBatching;
      }
    }
  }

  // GrpcTransportProvider
  // ====

  @Test
  public void customCredentials() throws IOException {
    Credentials credentials = Mockito.mock(Credentials.class);

    FakeStubSettings settings =
        FakeStubSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();

    TransportChannelProvider actualChannelProvider = settings.getTransportChannelProvider();
    Truth.assertThat(actualChannelProvider).isInstanceOf(InstantiatingGrpcChannelProvider.class);
    InstantiatingGrpcChannelProvider actualInstChPr =
        (InstantiatingGrpcChannelProvider) actualChannelProvider;

    Truth.assertThat(actualInstChPr.getEndpoint())
        .isEqualTo(FakeStubSettings.DEFAULT_SERVICE_ENDPOINT);
    // TODO(michaelbausor): create JSON with credentials and define GOOGLE_APPLICATION_CREDENTIALS
    // environment variable to allow travis build to access application default credentials
    Truth.assertThat(settings.getCredentialsProvider().getCredentials())
        .isSameInstanceAs(credentials);
  }

  @Test
  public void channelCustomCredentialScopes() throws IOException {
    ImmutableList<String> inputScopes =
        ImmutableList.<String>builder().add("https://www.googleapis.com/auth/fakeservice").build();

    CredentialsProvider credentialsProvider =
        FakeStubSettings.defaultCredentialsProviderBuilder().setScopesToApply(inputScopes).build();
    FakeStubSettings settings =
        FakeStubSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();

    TransportChannelProvider actualChannelProvider = settings.getTransportChannelProvider();
    Truth.assertThat(actualChannelProvider).isInstanceOf(InstantiatingGrpcChannelProvider.class);
    InstantiatingGrpcChannelProvider actualInstChPr =
        (InstantiatingGrpcChannelProvider) actualChannelProvider;

    Truth.assertThat(actualInstChPr.getEndpoint())
        .isEqualTo(FakeStubSettings.DEFAULT_SERVICE_ENDPOINT);

    CredentialsProvider actualCredentialsProvider = settings.getCredentialsProvider();
    Truth.assertThat(actualCredentialsProvider).isInstanceOf(GoogleCredentialsProvider.class);
    GoogleCredentialsProvider googCredProv = (GoogleCredentialsProvider) actualCredentialsProvider;

    Truth.assertThat(googCredProv.getScopesToApply()).isEqualTo(inputScopes);

    // TODO(michaelbausor): create JSON with credentials and define GOOGLE_APPLICATION_CREDENTIALS
    // environment variable to allow travis build to access application default credentials
    // Truth.assertThat(connSettings.getCredentials()).isNotNull();
  }

  // CallSettings
  // ====

  @Test
  public void callSettingsToBuilder() {
    UnaryCallSettings.Builder<?, ?> builderA = UnaryCallSettings.newUnaryCallSettingsBuilder();
    UnaryCallSettings<?, ?> settingsA = builderA.build();
    UnaryCallSettings.Builder<?, ?> builderB = settingsA.toBuilder();
    UnaryCallSettings<?, ?> settingsB = builderB.build();

    assertEquals(settingsA, settingsB);
  }

  @Test
  public void unaryCallSettingsBuilderBuildDoesNotFailUnsetProperties() {
    UnaryCallSettings.Builder<Integer, Integer> builder =
        UnaryCallSettings.newUnaryCallSettingsBuilder();
    builder.build();
  }

  @Test
  public void callSettingsBuildFromTimeoutNoRetries() {
    Duration timeout = Duration.ofMillis(60000);

    UnaryCallSettings.Builder<Integer, Integer> builderA =
        UnaryCallSettings.newUnaryCallSettingsBuilder();
    builderA.setSimpleTimeoutNoRetries(timeout);
    UnaryCallSettings<Integer, Integer> settingsA = builderA.build();

    UnaryCallSettings.Builder<Integer, Integer> builderB =
        UnaryCallSettings.newUnaryCallSettingsBuilder();
    builderB
        .setRetryableCodes()
        .setRetrySettings(
            RetrySettings.newBuilder()
                .setTotalTimeout(timeout)
                .setInitialRetryDelay(Duration.ZERO)
                .setRetryDelayMultiplier(1)
                .setMaxRetryDelay(Duration.ZERO)
                .setInitialRpcTimeout(timeout)
                .setRpcTimeoutMultiplier(1)
                .setMaxRpcTimeout(timeout)
                .setMaxAttempts(1)
                .build());
    UnaryCallSettings<Integer, Integer> settingsB = builderB.build();

    assertEquals("UnaryCallSettings", settingsA, settingsB);
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dae.gui.level;

import com.google.common.eventbus.Subscribe;
import dae.GlobalObjects;
import dae.prefabs.ui.classpath.FileNode;
import dae.prefabs.ui.events.LevelEvent;
import dae.prefabs.ui.events.ProjectEvent;
import dae.prefabs.ui.events.ProjectEventType;
import dae.project.Level;
import dae.project.Project;
import java.awt.Frame;
import java.awt.Window;
import java.io.File;

/**
 *
 * @author Koen Samyn
 */
public class LevelRendererPanel extends javax.swing.JPanel {

    private Project currentProject;
    private Level currentLevel;

    /**
     * Creates new form LevelRendererPanel
     */
    public LevelRendererPanel() {
        initComponents();
        GlobalObjects.getInstance().registerListener(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        prefabComponentHeader1 = new dae.prefabs.ui.PrefabComponentHeader();
        lblSkyBox = new javax.swing.JLabel();
        txtSkyBox = new javax.swing.JTextField();
        btnChooseSkybox = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(0, 0, 0)));
        setLayout(new java.awt.GridBagLayout());

        prefabComponentHeader1.setTitle("Render Settings");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        add(prefabComponentHeader1, gridBagConstraints);

        lblSkyBox.setText("Skybox texture : ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        add(lblSkyBox, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        add(txtSkyBox, gridBagConstraints);

        btnChooseSkybox.setText("...");
        btnChooseSkybox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseSkyboxActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 0);
        add(btnChooseSkybox, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void btnChooseSkyboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseSkyboxActionPerformed
        FileNode skyboxTexture = GlobalObjects.getInstance().selectAsset((Window) this.getTopLevelAncestor(), this, currentProject, "Choose skybox texture", "dds");
        if (skyboxTexture != null) {
            txtSkyBox.setText(skyboxTexture.getFullName());
            currentLevel.setSkyBoxTexture(skyboxTexture.getFullName());
        }
    }//GEN-LAST:event_btnChooseSkyboxActionPerformed

    /*
     * Called when the project has changed.
     * @param pe the project event.
     */
    @Subscribe
    public void projectChanged(ProjectEvent pe) {
        if (pe.getEventType() == ProjectEventType.SELECTED) {
            currentProject = pe.getProject();
        }
    }

    @Subscribe
    public void levelSelected(LevelEvent le) {
        if (le.getEventType() == LevelEvent.EventType.LEVELSELECTED) {
            currentLevel = le.getLevel();
            txtSkyBox.setText(currentLevel.getSkyBoxTexture());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChooseSkybox;
    private javax.swing.JLabel lblSkyBox;
    private dae.prefabs.ui.PrefabComponentHeader prefabComponentHeader1;
    private javax.swing.JTextField txtSkyBox;
    // End of variables declaration//GEN-END:variables
}


text:
using System;

namespace BinarySearchTree
{
    public class Node<T> where T : IComparable
    {
        public T Data { get; set; }

        public Node<T> Left { get; set; }

        public Node<T> Right { get; set; }

        public Node()
        {
            Left = null;
            Right = null;
        }
    }
}


text:
import { Injectable } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { CanActivate } from '@angular/router';

@Injectable()
export class CanActivateOnLoginService {

  constructor(private authService: AuthService) { }

  ngOnInit() { }

  canActivate() {
    return this.authService.isLoggedIn();
  }
}


text:
/**
* @description
* Global Category. Model
* humpback-model created at Fri Sep 04 2015 11:20:23 GMT-0400 (EDT)
**/
angular.module('category.model', [
    'humpback.models'
])

/**
* @description
* Run and ignore for unit testing
*
**/
.run(function($sailsSocket, DS, CategoryService, utils){
    if(utils.development()){ console.log(window._name,': listening to category changes')};

    $sailsSocket.subscribe('category', function(envelope){
        //console.log(envelope);
        CategoryService.handler[envelope.verb](envelope)
    });

    return DS.defineResource({
        name: 'category',
        maxAge: 36000000,
        deleteOnExpire: 'none',
        onExpire: function (id, category) {
            console.log(id, 'Category Expired');
        },
        storageMode: 'localStorage',
        idAttribute: 'id',
        endpoint: '/category',
        baseUrl: window._prefix || '/api',
        meta: {
            contentCount: 0
        },

        /**
        * @description
        * Model's Life Cycle Callbacks
        * http://www.js-data.io/v1.5.8/docs/dsdefaults
        **/
        beforeInject: function(resource, data){

        },
        beforeCreate: function (resource, data, cb) {
            cb(null, data);
        },
        beforeUpdate: function(resource, data, cb){
            cb(null, data);
        },
        afterUpdate: function(resource, data, cb){
            cb(null, data);
        },
        afterInject: function(resource, attrs){
            console.log(attrs);
        },
        afterCreate: function (resource, data, cb) {
            cb(null, data);
        },
        beforeDestroy: function (resource, data, cb) {
            cb(null, data);
        },
        afterDestroy: function (resource, data, cb) {
            cb(null, data);
        },

        /**
        * @description
        * Define's Relations to the Model
        *
        **/
        relations:{

        }
    });
})

/**
* @description
* The CategoryService factory Exposes Handler and Service methods for the Category Server Side Model
*
**/
.factory('CategoryService',function(DS, $sailsSocket, utils){
	var _service = {};
	var _handler = {};

    /**
    * @description
    * When a Category is created that the app is listenting to inject it into the local DB
    *
    **/
	_handler.created = function(envelope){
        'use strict';
        utils.development(envelope);
        DS.inject('category', envelope.data);

    };

    /**
    * @description
    * When a Category is deleted that the app is listenting to eject it from the local DB
    *
    **/
    _handler.deleted = function(envelope){
        'use strict';
        utils.development(envelope);
        DS.eject('category', envelope.data);
    };

    /**
    * @description
    * When a Category is updated that the app is listenting to inject it from the local DB, or if only a ID fetch it from the server
    *
    **/
    _handler.updated = function(envelope){
        'use strict';
        utils.development(envelope);
        if(envelope.data){
            envelope.data.id = envelope.id;
            DS.inject('category', envelope.data);
        }else{
            DS.refresh('category',envelope.id);
        }

    };

    /**
    * @description
    * When a Category model's collection is added to, inject it into the Category Model
    *
    **/
    _handler.addedTo = function(envelope){
        'use strict';
        utils.development(envelope);
    };

    /**
    * @description
    * When a Category model's collection is detracted from eject it from the Category Model
    *
    **/
    _handler.removedFrom = function(envelope){
        'use strict';
        utils.development(envelope);
    };

    /**
    * @description
    * When a Category model is messaged
    *
    **/
    _handler.messaged = function(envelope){
        'use strict';
        utils.development(envelope);
    };

	return {
		service : _service,
		handler : _handler
	}
});


text:
package com.cloud.exception;

public class AgentControlChannelException extends CloudException {
    private static final long serialVersionUID = -310647782960500466L;

    public AgentControlChannelException(String msg) {
        super(msg);
    }
}


text:
package mr.wordcount.writables;

import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver;
import org.apache.hadoop.mrunit.types.Pair;
import org.junit.Test;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;

// MRUnit does not supports MultipleInputs (yet? MRUNIT-69)
public class StartsWithCountJob_GenericWritableTest {
    @Test
    public void withLongWritableMapper() throws IOException {
        doTest(new StartsWithCountJob_GenericWritable.LongObjWritableMapper());
    }

    @Test
    public void withIntWritableMapper() throws IOException {
        doTest(new StartsWithCountJob_GenericWritable.IntObjWritableMapper());
    }

    private void doTest(Mapper mapper) throws IOException {
        MapReduceDriver<LongWritable, Text, Text, StartsWithCountJob_GenericWritable.MyGenericObject, Text, StartsWithCountJob_GenericWritable.MyGenericObject> driver =
                new MapReduceDriver<LongWritable, Text, Text, StartsWithCountJob_GenericWritable.MyGenericObject,Text, StartsWithCountJob_GenericWritable.MyGenericObject>();

        driver.setMapper(mapper);
        driver.setReducer(new StartsWithCountJob_GenericWritable.GenericObjectReducer());

        LongWritable k = new LongWritable();
        driver.withInput(k, new Text("This is a line number one"));
        driver.withInput(k, new Text("This is another line"));

        List<Pair<Text,StartsWithCountJob_GenericWritable.MyGenericObject>> res = driver.run();
        assertEquals(6, res.size());

        Collections.sort(res, new ComparatorByPairKey<StartsWithCountJob_GenericWritable.MyGenericObject>());

        assertEquals("T", res.get(0).getFirst().toString());
        assertEquals(2, ((IntWritable)res.get(0).getSecond().get()).get());

        assertEquals("a", res.get(1).getFirst().toString());
        assertEquals(2, ((IntWritable)res.get(1).getSecond().get()).get());

        assertEquals("i", res.get(2).getFirst().toString());
        assertEquals(2, ((IntWritable)res.get(2).getSecond().get()).get());

        assertEquals("l", res.get(3).getFirst().toString());
        assertEquals(2, ((IntWritable)res.get(3).getSecond().get()).get());

        assertEquals("n", res.get(4).getFirst().toString());
        assertEquals(1, ((IntWritable)res.get(4).getSecond().get()).get());

        assertEquals("o", res.get(5).getFirst().toString());
        assertEquals(1, ((IntWritable)res.get(5).getSecond().get()).get());
    }
}


text:
using System.Collections.Generic;
using System.Json;
namespace SuperMap.Web.ISDotNET6
{
    ///
    /// 	<para>${IS6_ServerStyle_Title}</para>
    /// 	<para>${IS6_ServerStyle_Description}</para>
    ///
    /// <remarks>${IS6_ServerStyle_Remarks}</remarks>
    public class ServerStyle
    {
        /// ${IS6_ServerStyle_constructor_None_D}
        public ServerStyle()
        {
            BrushOpaqueRate = 100;
            BrushBackColor = new ServerColor(255, 255, 255);
            BrushColor = new ServerColor(255, 255, 0);

            PenColor = new ServerColor(197, 198, 201);
            PenWidth = 1;
        }

        /// ${IS6_ServerStyle_attribute_brushBackColor_D}
        public ServerColor BrushBackColor { get; set; }

        /// ${IS6_ServerStyle_attribute_brushBackTransparent_D}
        public bool BrushBackTransparent { get; set; }

        /// ${IS6_ServerStyle_attribute_brushColor_D}
        public ServerColor BrushColor { get; set; }

        //渐变填充的角度,以度为单位。圆形渐变该参数不起作用。
        ///
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_1}</para>
        /// 	<para></para>
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_2}</para>
        /// 	<para></para>
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_3}</para>
        /// 	<para></para>
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_4}</para>
        /// 	<para></para>
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_5}</para>
        /// 	<para></para>
        /// 	<para>${IS6_ServerStyle_attribute_brushGradientAngle_D_6}</para>
        ///
        public double BrushGradientAngle { get; set; }

        /// ${IS6_ServerStyle_attribute_brushGradientCenterOffsetX_D}
        public int BrushGradientCenterOffsetX { get; set; }

        /// ${IS6_ServerStyle_attribute_brushGradientCenterOffsetY_D}
        public int BrushGradientCenterOffsetY { get; set; }

        /// ${IS6_ServerStyle_attribute_brushGradientMode_D}
        public BrushGradientMode BrushGradientMode { get; set; }

        /// ${IS6_ServerStyle_attribute_brushOpaqueRate_D}
        public int BrushOpaqueRate { get; set; }

        //表示填充风格的ID。这里的ID是指工作空间的填充库中填充的编号。
        /// ${IS6_ServerStyle_attribute_brushStyle_D}
        public int BrushStyle { get; set; }

        /// ${IS6_ServerStyle_attribute_penColor_D}
        public ServerColor PenColor { get; set; }

        /// ${IS6_ServerStyle_attribute_penStyle_D}
        public int PenStyle { get; set; }

        //边线宽度,单位为0.1毫米。
        /// ${IS6_ServerStyle_attribute_penWidth_D}
        public int PenWidth { get; set; }

        /// ${IS6_ServerStyle_attribute_symbolRotation_D}
        public double SymbolRotation { get; set; }

        /// ${IS6_ServerStyle_attribute_symbolSize_D}
        public int SymbolSize { get; set; }

        /// ${IS6_ServerStyle_attribute_symbolStyle_D}
        public int SymbolStyle { get; set; }

        internal static string ToJson(ServerStyle param)
        {
            if (param == null)
            {
                return null;
            }

            string json = "{";
            List<string> list = new List<string>();

            list.Add(string.Format("\"brushBackColor\":{0}", ServerColor.ToJson(param.BrushBackColor)));

            list.Add(string.Format("\"brushBackTransparent\":{0}", param.BrushBackTransparent.ToString().ToLower()));

            list.Add(string.Format("\"brushColor\":{0}", ServerColor.ToJson(param.BrushColor)));

            list.Add(string.Format("\"brushGradientAngle\":{0}", param.BrushGradientAngle));

            list.Add(string.Format("\"brushGradientCenterOffsetX\":{0}", param.BrushGradientCenterOffsetX));

            list.Add(string.Format("\"brushGradientCenterOffsetY\":{0}", param.BrushGradientCenterOffsetY));

            list.Add(string.Format("\"brushGradientMode\":{0}", (int)param.BrushGradientMode));

            list.Add(string.Format("\"brushOpaqueRate\":{0}", param.BrushOpaqueRate));

            list.Add(string.Format("\"brushStyle\":{0}", param.BrushStyle));

            list.Add(string.Format("\"penColor\":{0}", ServerColor.ToJson(param.PenColor)));

            list.Add(string.Format("\"penStyle\":{0}", param.PenStyle));

            list.Add(string.Format("\"penWidth\":{0}", param.PenWidth));

            list.Add(string.Format("\"symbolRotation\":{0}", param.SymbolRotation));

            list.Add(string.Format("\"symbolSize\":{0}", param.SymbolSize));

            list.Add(string.Format("\"symbolStyle\":{0}", param.SymbolStyle));

            json += string.Join(",", list.ToArray());
            json += "}";

            return json;
        }

        /// ${IS6_ServerStyle_method_FromJson_D}
        /// <param name="jsonObject">${IS6_ServerStyle_method_FromJson_param_jsonObject}</param>
        /// <returns>${IS6_ServerStyle_method_FromJson_return}</returns>
        public static ServerStyle FromJson(JsonObject jsonObject)
        {
            if (jsonObject == null)
            {
                return null;
            }
            ServerStyle result = new ServerStyle
            {
                BrushBackColor = ServerColor.FromJson((int)jsonObject["brushBackColor"]),
                BrushBackTransparent = (bool)jsonObject["brushBackTransparent"],
                BrushColor = ServerColor.FromJson((int)jsonObject["brushColor"]),
                BrushGradientAngle = (int)jsonObject["brushGradientAngle"],
                BrushGradientCenterOffsetX = (int)jsonObject["brushGradientCenterOffsetX"],
                BrushGradientCenterOffsetY = (int)jsonObject["brushGradientCenterOffsetY"],
                BrushGradientMode = (BrushGradientMode)(int)jsonObject["brushGradientMode"],
                BrushOpaqueRate = (int)jsonObject["brushOpaqueRate"],
                BrushStyle = (int)jsonObject["brushStyle"],
                PenColor = ServerColor.FromJson((int)jsonObject["penColor"]),
                PenStyle = (int)jsonObject["penStyle"],
                PenWidth = (int)jsonObject["penWidth"],
                SymbolRotation = (double)jsonObject["symbolRotation"],
                SymbolSize = (int)jsonObject["symbolSize"],
                SymbolStyle = (int)jsonObject["symbolStyle"],
            };

            return result;
        }
    }
}


text:
package org.apache.hadoop.hive.ql.exec;

import java.io.Serializable;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.CompilationOpContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.HashTableDummyDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.plan.api.OperatorType;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.SerDeUtils;

public class HashTableDummyOperator extends Operator<HashTableDummyDesc> implements Serializable {
  private static final long serialVersionUID = 1L;

  /** Kryo ctor. */
  protected HashTableDummyOperator() {
    super();
  }

  public HashTableDummyOperator(CompilationOpContext ctx) {
    super(ctx);
  }

  @Override
  protected void initializeOp(Configuration hconf) throws HiveException {
    super.initializeOp(hconf);
    TableDesc tbl = this.getConf().getTbl();
    try {
      Deserializer serde = tbl.getDeserializerClass().newInstance();
      SerDeUtils.initializeSerDe(serde, hconf, tbl.getProperties(), null);
      this.outputObjInspector = serde.getObjectInspector();
    } catch (Exception e) {
      LOG.error("Generating output obj inspector from dummy object error", e);
      e.printStackTrace();
    }
  }

  @Override
  public void process(Object row, int tag) throws HiveException {
    throw new HiveException();
  }

  @Override
  public void closeOp(boolean abort) throws HiveException {
  }

  @Override
  public String getName() {
    return HashTableDummyOperator.getOperatorName();
  }

  static public String getOperatorName() {
    return "HASHTABLEDUMMY";
  }

  @Override
  public OperatorType getType() {
    return OperatorType.HASHTABLEDUMMY;
  }

  @Override
  public boolean equals(Object obj) {
    return super.equals(obj) || (obj instanceof HashTableDummyOperator) && ((HashTableDummyOperator)obj).operatorId.equals(operatorId);
  }

  @Override
  public int hashCode() {
    return operatorId.hashCode();
  }
}


text:
<?php

namespace myApp\Form;

use \ParagonIE\AntiCSRF\AntiCSRF;

class Base
{
  protected $fields;
  protected $namespace;
  protected $config;

  /**
   * @var \Slim\Views\Twig
   */
  protected $view;

  /**
   * @var \myApp\Utilities\View
   */
  protected $view_functions;

  /**
   * @var \Slim\Flash\Messages
   */
  protected $flash;

  protected $wasValidated = false;

  public function __construct($di)
  {
    $this->config = $di['config'];
    $this->view   = $di['view'];
    $this->view_functions = $di['utility.view'];
    $this->namespace = '';
    $this->fields = array();
    $this->errors = array();
    $this->flash = $di['flash'];
    $this->setup($di);
  }

  public function setInitial($initial)
  {
    if (!is_array($initial) && $initial instanceof \stdClass) {
      $initial = get_object_vars($initial);
    }
    foreach ($this->fields as $k => $field) {
      if (isset($initial[$k])) {
        $field = $field->setDefaultValue($initial[$k]);
      }
      $this->fields[$k] = $field;
    }
    return $this;
  }

  public function setNamespace($namespace)
  {
    $this->namespace = $namespace;
    return $this;
  }

  public function getNamespace()
  {
    return $this->namespace;
  }

  public function resolve($request)
  {
    foreach ($this->fields as $k => $field) {
      $resolved = $field->setName($this->getNamespace() . $k)->resolve($request);
      $field->setValue($resolved);
      $this->fields[$k] = $field;
    }
    return $this;
  }

  protected function setup($di)
  {
    // do nothing by default
  }

  public function addField(\myApp\Field\Base $field)
  {
    $key = $field->getName();
    $this->fields[$key] = $field;
    return $this;
  }

  public function __get($field_name)
  {
    return $this->fields[$field_name]->setName($this->getNamespace() . $field_name)->setView($this->view);
  }

  public function __isset($field_name)
  {
    return isset($this->fields[$field_name]);
  }

  public function validate()
  {
    $this->errors = array();

    $csrf = new AntiCSRF;
    if(!$csrf->validateRequest()) $this->addError('CSRF', 'CSRF token missing, invalid or expired. Refresh page and try again.');

    foreach ($this->fields as $field) {
      $fieldValidate = $field->validate();
      if (!$fieldValidate)
        $this->addError($field->getName(), $field->getErrors());
    }

    $this->wasValidated = (count($this->getErrors()) === 0);
    return $this->wasValidated;
  }

  public function getCleanedData()
  {
    if (!$this->wasValidated) {
      throw new \myApp\Exception\InvalidFormException();
    }
    return $this->getData();
  }

  protected function getData()
  {
    $output = array();

    foreach ($this->fields as $name => $field) {
      $output[$name] = $field->getValue();
    }

    return $output;
  }

  public function getErrors()
  {
    return $this->errors;
  }

  public function addError($fieldName, $error)
  {
    if (!isset($this->errors[$fieldName])){
      $this->errors[$fieldName] = array();
    }
    if (is_array($error)) {
      $this->errors[$fieldName] = array_merge($this->errors[$fieldName], $error);
      foreach ($error as $key => $value) {
        $this->flash->addMessage($fieldName . ' alert-danger ' . $key, $value);
      }
    }
    else {
      $this->errors[$fieldName][] = $error;
      $this->flash->addMessage($fieldName . ' alert-danger', $error);
    }
  }

  /**
   * Make sure the data values are allowed.
   *
   * This is used when form fields may be valid individually but become invalid
   * based on the values of other fields inside the form.
   *
   * The format of the allowed value map is the following:
   *   [Field name] => (array)
   *      [Field value] => (array)
   *        [Dependent field name] => (array) [Allowed values]
   *
   * The function is as follows: If [Field name] is set to [Field value],
   * then [Dependent field name] must have a value that is in [Allowed values array]
   * @param $data
   * @param $allowed
   * @return bool
   */
  public function validateAllowedValues($data, $allowed)
  {
    $this->errors = array();
    foreach ($data as $field_name => $field_value) {
      // dependent fields exist for that field
      if (isset($allowed[$field_name])) {
        $values_with_rules = $allowed[$field_name];
        // no dependent fields on that particular value, keep going
        if (!isset($values_with_rules[$field_value])) {
          continue;
        }

        $dependent_fields = $values_with_rules[$field_value];
        foreach ($dependent_fields as $dependent_field_name => $allowed_values)
        {
          // the field isn't even set! assume invalid
          if (!isset($data[$dependent_field_name])) {
            $this->addError(
              $dependent_field_name,
              "$dependent_field_name is required when $field_name set to $field_value"
            );
            continue;
          }

          // the value is not allowed!
          $actual_value = $data[$dependent_field_name];

          if (!in_array($actual_value, $allowed_values)) {
            $this->addError(
              $dependent_field_name,
              "$dependent_field_name can'be be $actual_value when $field_name set to $field_value"
            );
            continue;
          }
        }
      }
    }

    return (count($this->getErrors()) === 0);
  }

  /**
   * Return the allowed dropdown selection values, based on the provided form
   * data
   *
   * @param array $data the form data
   * @param array $allowed the allowed values used to validate the form
   * @return array
   */
  public function getAllowedDropdownValues($data, $allowed)
  {
    // first get the initial data and dropdown keys
    $allowedDropdownValues = array();
    foreach ($this->fields as $name => $f) {
      if (! $f instanceof \myApp\Field\Dropdown) continue;
      $key = $name;
      $allowedDropdownValues[$key] = array_keys($f->getOptions());
    }

    // now reduce the allowed values to whatever is in the $allowed list
    foreach ($data as $key => $value) {
      // no restrictions based on that field
      if (!isset($allowed[$key])) {
        continue;
      }

      $restrictions = $allowed[$key];

      // no restrictions based on that field value
      if (!isset($restrictions[$value])) {
        continue;
      }

      $restrictedFields = $restrictions[$value];
      foreach ($restrictedFields as $restrictedField => $allowedValues) {
        // not a dropdown field
        if (!isset($allowedDropdownValues[$restrictedField])) {
          continue;
        }

        // reduce to values in $allowedValues
        $allowedDropdownValues[$restrictedField] = array_intersect($allowedDropdownValues[$restrictedField], $allowedValues);
      }
    }

    return $allowedDropdownValues;
  }

  /**
   * Disable the form's dropdown options that aren't allowed
   *
   * @param array $data    the form data
   * @param array $allowed the allowed values used to validate the form
   */
  public function setDropdownDisabledOptionsBasedOnAllowed($data, $allowed)
  {
    $allowedDropdownValues = $this->getAllowedDropdownValues($data, $allowed);
    foreach ($allowedDropdownValues as $key => $values) {
      $this->$key->setDisabledOptionsFromAllowed($values);
    }
  }
}


text:
var DubAPI = require("dubapi"),
    log = require("jethro"),
    MongoClient = require('mongodb').MongoClient,
    pkg = require(process.cwd() + "/package.json"),
    repo = require(process.cwd() + '/repo.js'),
    settings = require(process.cwd() + '/settings.js').settings;

//make logger timestamp more readable
log.setTimeformat("YYYY-MM-DD HH:mm:ss:SSS");

new DubAPI({ username: settings.USERNAME, password: settings.PASSWORD }, function(err, bot) {

    if (err) {
        return log("error", "BOT", err);
    }

    //to find out how to use jethro visit: https://github.com/JethroLogger/Jethro
    bot.log = require("jethro");
    bot.log.setTimeformat("YYYY-MM-DD HH:mm:ss:SSS");

    bot.log("info", "BOT", 'Running SteveBot with DubAPI v' + bot.version);

    //connect to db
    MongoClient.connect(settings.MONGODBURL, function(errDb, db) {

        function connect() {
            bot.connect(settings.ROOMNAME);
        }

        function disconnect(err) {
            db.close();
            bot.disconnect();

            if(err) bot.log("error", "BOT", err.stack);

            process.exit();
        }

        //Properly disconnect from room and close db connection when program stops
        process.on('exit', disconnect); //automatic close
        process.on('SIGINT', disconnect); //ctrl+c close
        process.on('uncaughtException', disconnect);

        bot.on("error", function(err) {
            bot.log("error", "BOT", err);
        });

        connect();

        //pass the bot and db to the events handler
        require("./events")(bot, db);
    });
});


text:
package xworker.org.apache.kafka.streams.kstream.keyvaluemappers;

import org.apache.kafka.streams.kstream.KeyValueMapper;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

public class ActionKeyValueMapper implements KeyValueMapper<Object, Object, Object>{
	Thing thing;
	ActionContext actionContext;

	public ActionKeyValueMapper(Thing thing, ActionContext actionContext) {
		this.thing = thing;
		this.actionContext = actionContext;
	}

	@Override
	public Object apply(Object key, Object value) {
		return thing.getAction().run(actionContext, "key", key, "value", value);
	}

	public static ActionKeyValueMapper create(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");

		return new ActionKeyValueMapper(self, actionContext);
	}

}