text:
from __future__ import print_function, unicode_literals, absolute_import
import os
import pyreadline.logger as logger
from   pyreadline.logger import log
import pyreadline.lineeditor.lineobj as lineobj
import pyreadline.lineeditor.history as history
from . import basemode

class NotEmacsMode(basemode.BaseMode):
    mode="notemacs"
    def __init__(self,rlobj):
        super(NotEmacsMode,self).__init__(rlobj)

    def __repr__(self):
        return "<NotEmacsMode>"

    def _readline_from_keyboard(self):
        c=self.console
        while 1:
            self._update_line()
            event = c.getkeypress()
            if self.next_meta:
                self.next_meta = False
                control, meta, shift, code = event.keyinfo
                event.keyinfo = (control, True, shift, code)

            #Process exit keys. Only exit on empty line
            if event.keyinfo in self.exit_dispatch:
                if lineobj.EndOfLine(self.l_buffer) == 0:
                    raise EOFError

            dispatch_func = self.key_dispatch.get(event.keyinfo,self.self_insert)
            log("readline from keyboard:%s"%(event.keyinfo,))
            r = None
            if dispatch_func:
                r = dispatch_func(event)
                self.l_buffer.push_undo()

            self.previous_func = dispatch_func
            if r:
                self._update_line()
                break

    def readline(self, prompt=''):
        '''Try to act like GNU readline.'''
        # handle startup_hook
        if self.first_prompt:
            self.first_prompt = False
            if self.startup_hook:
                try:
                    self.startup_hook()
                except:
                    print('startup hook failed')
                    traceback.print_exc()

        c = self.console
        self.l_buffer.reset_line()
        self.prompt = prompt
        self._print_prompt()

        if self.pre_input_hook:
            try:
                self.pre_input_hook()
            except:
                print('pre_input_hook failed')
                traceback.print_exc()
                self.pre_input_hook = None

        log("in readline: %s"%self.paste_line_buffer)
        if len(self.paste_line_buffer)>0:
            self.l_buffer=lineobj.ReadlineTextBuffer(self.paste_line_buffer[0])
            self._update_line()
            self.paste_line_buffer=self.paste_line_buffer[1:]
            c.write('\r\n')
        else:
            self._readline_from_keyboard()
            c.write('\r\n')

        self.add_history(self.l_buffer.copy())

        log('returning(%s)' % self.l_buffer.get_line_text())
        return self.l_buffer.get_line_text() + '\n'

    ### Methods below here are bindable emacs functions

    def beginning_of_line(self, e): # (C-a)
        '''Move to the start of the current line. '''
        self.l_buffer.beginning_of_line()

    def end_of_line(self, e): # (C-e)
        '''Move to the end of the line. '''
        self.l_buffer.end_of_line()

    def forward_char(self, e): # (C-f)
        '''Move forward a character. '''
        self.l_buffer.forward_char()

    def backward_char(self, e): # (C-b)
        '''Move back a character. '''
        self.l_buffer.backward_char()

    def forward_word(self, e): # (M-f)
        '''Move forward to the end of the next word. Words are composed of
        letters and digits.'''
        self.l_buffer.forward_word()

    def backward_word(self, e): # (M-b)
        '''Move back to the start of the current or previous word. Words are
        composed of letters and digits.'''
        self.l_buffer.backward_word()

    def clear_screen(self, e): # (C-l)
        '''Clear the screen and redraw the current line, leaving the current
        line at the top of the screen.'''
        self.console.page()

    def redraw_current_line(self, e): # ()
        '''Refresh the current line. By default, this is unbound.'''
        pass

    def accept_line(self, e): # (Newline or Return)
        '''Accept the line regardless of where the cursor is. If this line
        is non-empty, it may be added to the history list for future recall
        with add_history(). If this line is a modified history line, the
        history line is restored to its original state.'''
        return True

#########  History commands
    def previous_history(self, e): # (C-p)
        '''Move back through the history list, fetching the previous command. '''
        self._history.previous_history(self.l_buffer)

    def next_history(self, e): # (C-n)
        '''Move forward through the history list, fetching the next command. '''
        self._history.next_history(self.l_buffer)

    def beginning_of_history(self, e): # (M-<)
        '''Move to the first line in the history.'''
        self._history.beginning_of_history()

    def end_of_history(self, e): # (M->)
        '''Move to the end of the input history, i.e., the line currently
        being entered.'''
        self._history.end_of_history(self.l_buffer)

    def _i_search(self, searchfun, direction, init_event):
        c = self.console
        line = self.get_line_buffer()
        query = ''
        hc_start = self._history.history_cursor #+ direction
        while 1:
            x, y = self.prompt_end_pos
            c.pos(0, y)
            if direction < 0:
                prompt = 'reverse-i-search'
            else:
                prompt = 'forward-i-search'

            scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line))
            self._update_prompt_pos(scroll)
            self._clear_after()

            event = c.getkeypress()
            if event.keysym == 'BackSpace':
                if len(query) > 0:
                    query = query[:-1]
                    self._history.history_cursor = hc_start
                else:
                    self._bell()
            elif event.char in string.letters + string.digits + string.punctuation + ' ':
                self._history.history_cursor = hc_start
                query += event.char
            elif event.keyinfo == init_event.keyinfo:
                self._history.history_cursor += direction
                line=searchfun(query)
                pass
            else:
                if event.keysym != 'Return':
                    self._bell()
                break
            line=searchfun(query)

        px, py = self.prompt_begin_pos
        c.pos(0, py)
        self.l_buffer.set_line(line)
        self._print_prompt()
        self._history.history_cursor=len(self._history.history)

    def reverse_search_history(self, e): # (C-r)
        '''Search backward starting at the current line and moving up
        through the history as necessary. This is an incremental search.'''
#        print("HEJ")
#        self.console.bell()
        self._i_search(self._history.reverse_search_history, -1, e)

    def forward_search_history(self, e): # (C-s)
        '''Search forward starting at the current line and moving down
        through the the history as necessary. This is an incremental search.'''
#        print("HEJ")
#        self.console.bell()
        self._i_search(self._history.forward_search_history, 1, e)

    def non_incremental_reverse_search_history(self, e): # (M-p)
        '''Search backward starting at the current line and moving up
        through the history as necessary using a non-incremental search for
        a string supplied by the user.'''
        self._history.non_incremental_reverse_search_history(self.l_buffer)

    def non_incremental_forward_search_history(self, e): # (M-n)
        '''Search forward starting at the current line and moving down
        through the the history as necessary using a non-incremental search
        for a string supplied by the user.'''
        self._history.non_incremental_reverse_search_history(self.l_buffer)

    def history_search_forward(self, e): # ()
        '''Search forward through the history for the string of characters
        between the start of the current line and the point. This is a
        non-incremental search. By default, this command is unbound.'''
        self.l_buffer=self._history.history_search_forward(self.l_buffer)

    def history_search_backward(self, e): # ()
        '''Search backward through the history for the string of characters
        between the start of the current line and the point. This is a
        non-incremental search. By default, this command is unbound.'''
        self.l_buffer=self._history.history_search_backward(self.l_buffer)

    def yank_nth_arg(self, e): # (M-C-y)
        '''Insert the first argument to the previous command (usually the
        second word on the previous line) at point. With an argument n,
        insert the nth word from the previous command (the words in the
        previous command begin with word 0). A negative argument inserts the
        nth word from the end of the previous command.'''
        pass

    def yank_last_arg(self, e): # (M-. or M-_)
        '''Insert last argument to the previous command (the last word of
        the previous history entry). With an argument, behave exactly like
        yank-nth-arg. Successive calls to yank-last-arg move back through
        the history list, inserting the last argument of each line in turn.'''
        pass

    def delete_char(self, e): # (C-d)
        '''Delete the character at point. If point is at the beginning of
        the line, there are no characters in the line, and the last
        character typed was not bound to delete-char, then return EOF.'''
        self.l_buffer.delete_char()

    def backward_delete_char(self, e): # (Rubout)
        '''Delete the character behind the cursor. A numeric argument means
        to kill the characters instead of deleting them.'''
        self.l_buffer.backward_delete_char()

    def forward_backward_delete_char(self, e): # ()
        '''Delete the character under the cursor, unless the cursor is at
        the end of the line, in which case the character behind the cursor
        is deleted. By default, this is not bound to a key.'''
        pass

    def quoted_insert(self, e): # (C-q or C-v)
        '''Add the next character typed to the line verbatim. This is how to
        insert key sequences like C-q, for example.'''
        e = self.console.getkeypress()
        self.insert_text(e.char)

    def tab_insert(self, e): # (M-TAB)
        '''Insert a tab character. '''
        cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
        ws = ' ' * (self.tabstop - (cursor % self.tabstop))
        self.insert_text(ws)

    def self_insert(self, e): # (a, b, A, 1, !, ...)
        '''Insert yourself. '''
        if ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys.
            self.insert_text(e.char)

    def transpose_chars(self, e): # (C-t)
        '''Drag the character before the cursor forward over the character
        at the cursor, moving the cursor forward as well. If the insertion
        point is at the end of the line, then this transposes the last two
        characters of the line. Negative arguments have no effect.'''
        self.l_buffer.transpose_chars()

    def transpose_words(self, e): # (M-t)
        '''Drag the word before point past the word after point, moving
        point past that word as well. If the insertion point is at the end
        of the line, this transposes the last two words on the line.'''
        self.l_buffer.transpose_words()

    def upcase_word(self, e): # (M-u)
        '''Uppercase the current (or following) word. With a negative
        argument, uppercase the previous word, but do not move the cursor.'''
        self.l_buffer.upcase_word()

    def downcase_word(self, e): # (M-l)
        '''Lowercase the current (or following) word. With a negative
        argument, lowercase the previous word, but do not move the cursor.'''
        self.l_buffer.downcase_word()

    def capitalize_word(self, e): # (M-c)
        '''Capitalize the current (or following) word. With a negative
        argument, capitalize the previous word, but do not move the cursor.'''
        self.l_buffer.capitalize_word()

    def overwrite_mode(self, e): # ()
        '''Toggle overwrite mode. With an explicit positive numeric
        argument, switches to overwrite mode. With an explicit non-positive
        numeric argument, switches to insert mode. This command affects only
        emacs mode; vi mode does overwrite differently. Each call to
        readline() starts in insert mode. In overwrite mode, characters
        bound to self-insert replace the text at point rather than pushing
        the text to the right. Characters bound to backward-delete-char
        replace the character before point with a space.'''
        pass

    def kill_line(self, e): # (C-k)
        '''Kill the text from point to the end of the line. '''
        self.l_buffer.kill_line()

    def backward_kill_line(self, e): # (C-x Rubout)
        '''Kill backward to the beginning of the line. '''
        self.l_buffer.backward_kill_line()

    def unix_line_discard(self, e): # (C-u)
        '''Kill backward from the cursor to the beginning of the current line. '''
        # how is this different from backward_kill_line?
        self.l_buffer.unix_line_discard()

    def kill_whole_line(self, e): # ()
        '''Kill all characters on the current line, no matter where point
        is. By default, this is unbound.'''
        self.l_buffer.kill_whole_line()

    def kill_word(self, e): # (M-d)
        '''Kill from point to the end of the current word, or if between
        words, to the end of the next word. Word boundaries are the same as
        forward-word.'''
        self.l_buffer.kill_word()

    def backward_kill_word(self, e): # (M-DEL)
        '''Kill the word behind point. Word boundaries are the same as
        backward-word. '''
        self.l_buffer.backward_kill_word()

    def unix_word_rubout(self, e): # (C-w)
        '''Kill the word behind point, using white space as a word
        boundary. The killed text is saved on the kill-ring.'''
        self.l_buffer.unix_word_rubout()

    def delete_horizontal_space(self, e): # ()
        '''Delete all spaces and tabs around point. By default, this is unbound. '''
        pass

    def kill_region(self, e): # ()
        '''Kill the text in the current region. By default, this command is unbound. '''
        pass

    def copy_region_as_kill(self, e): # ()
        '''Copy the text in the region to the kill buffer, so it can be
        yanked right away. By default, this command is unbound.'''
        pass

    def copy_region_to_clipboard(self, e): # ()
        '''Copy the text in the region to the windows clipboard.'''
        if self.enable_win32_clipboard:
                mark=min(self.l_buffer.mark,len(self.l_buffer.line_buffer))
                cursor=min(self.l_buffer.point,len(self.l_buffer.line_buffer))
                if self.l_buffer.mark==-1:
                        return
                begin=min(cursor,mark)
                end=max(cursor,mark)
                toclipboard="".join(self.l_buffer.line_buffer[begin:end])
                clipboard.SetClipboardText(str(toclipboard))

    def copy_backward_word(self, e): # ()
        '''Copy the word before point to the kill buffer. The word
        boundaries are the same as backward-word. By default, this command
        is unbound.'''
        pass

    def copy_forward_word(self, e): # ()
        '''Copy the word following point to the kill buffer. The word
        boundaries are the same as forward-word. By default, this command is
        unbound.'''
        pass

    def paste(self,e):
        '''Paste windows clipboard'''
        if self.enable_win32_clipboard:
                txt=clipboard.get_clipboard_text_and_convert(False)
                self.insert_text(txt)

    def paste_mulitline_code(self,e):
        '''Paste windows clipboard'''
        reg=re.compile("\r?\n")
        if self.enable_win32_clipboard:
                txt=clipboard.get_clipboard_text_and_convert(False)
                t=reg.split(txt)
                t=[row for row in t if row.strip()!=""] #remove empty lines
                if t!=[""]:
                    self.insert_text(t[0])
                    self.add_history(self.l_buffer.copy())
                    self.paste_line_buffer=t[1:]
                    log("multi: %s"%self.paste_line_buffer)
                    return True
                else:
                    return False

    def ipython_paste(self,e):
        '''Paste windows clipboard. If enable_ipython_paste_list_of_lists is
        True then try to convert tabseparated data to repr of list of lists or
        repr of array'''
        if self.enable_win32_clipboard:
                txt=clipboard.get_clipboard_text_and_convert(
                                                self.enable_ipython_paste_list_of_lists)
                if self.enable_ipython_paste_for_paths:
                        if len(txt)<300 and ("\t" not in txt) and ("\n" not in txt):
                                txt=txt.replace("\\", "/").replace(" ", r"\ ")
                self.insert_text(txt)

    def yank(self, e): # (C-y)
        '''Yank the top of the kill ring into the buffer at point. '''
        pass

    def yank_pop(self, e): # (M-y)
        '''Rotate the kill-ring, and yank the new top. You can only do this
        if the prior command is yank or yank-pop.'''
        pass

    def digit_argument(self, e): # (M-0, M-1, ... M--)
        '''Add this digit to the argument already accumulating, or start a
        new argument. M-- starts a negative argument.'''
        pass

    def universal_argument(self, e): # ()
        '''This is another way to specify an argument. If this command is
        followed by one or more digits, optionally with a leading minus
        sign, those digits define the argument. If the command is followed
        by digits, executing universal-argument again ends the numeric
        argument, but is otherwise ignored. As a special case, if this
        command is immediately followed by a character that is neither a
        digit or minus sign, the argument count for the next command is
        multiplied by four. The argument count is initially one, so
        executing this function the first time makes the argument count
        four, a second time makes the argument count sixteen, and so on. By
        default, this is not bound to a key.'''
        pass

    def delete_char_or_list(self, e): # ()
        '''Deletes the character under the cursor if not at the beginning or
        end of the line (like delete-char). If at the end of the line,
        behaves identically to possible-completions. This command is unbound
        by default.'''
        pass

    def start_kbd_macro(self, e): # (C-x ()
        '''Begin saving the characters typed into the current keyboard macro. '''
        pass

    def end_kbd_macro(self, e): # (C-x ))
        '''Stop saving the characters typed into the current keyboard macro
        and save the definition.'''
        pass

    def call_last_kbd_macro(self, e): # (C-x e)
        '''Re-execute the last keyboard macro defined, by making the
        characters in the macro appear as if typed at the keyboard.'''
        pass

    def re_read_init_file(self, e): # (C-x C-r)
        '''Read in the contents of the inputrc file, and incorporate any
        bindings or variable assignments found there.'''
        pass

    def abort(self, e): # (C-g)
        '''Abort the current editing command and ring the terminals bell
             (subject to the setting of bell-style).'''
        self._bell()

    def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
        '''If the metafied character x is lowercase, run the command that is
        bound to the corresponding uppercase character.'''
        pass

    def prefix_meta(self, e): # (ESC)
        '''Metafy the next character typed. This is for keyboards without a
        meta key. Typing ESC f is equivalent to typing M-f. '''
        self.next_meta = True

    def undo(self, e): # (C-_ or C-x C-u)
        '''Incremental undo, separately remembered for each line.'''
        self.l_buffer.pop_undo()

    def revert_line(self, e): # (M-r)
        '''Undo all changes made to this line. This is like executing the
        undo command enough times to get back to the beginning.'''
        pass

    def tilde_expand(self, e): # (M-~)
        '''Perform tilde expansion on the current word.'''
        pass

    def set_mark(self, e): # (C-@)
        '''Set the mark to the point. If a numeric argument is supplied, the
        mark is set to that position.'''
        self.l_buffer.set_mark()

    def exchange_point_and_mark(self, e): # (C-x C-x)
        '''Swap the point with the mark. The current cursor position is set
        to the saved position, and the old cursor position is saved as the
        mark.'''
        pass

    def character_search(self, e): # (C-])
        '''A character is read and point is moved to the next occurrence of
        that character. A negative count searches for previous occurrences.'''
        pass

    def character_search_backward(self, e): # (M-C-])
        '''A character is read and point is moved to the previous occurrence
        of that character. A negative count searches for subsequent
        occurrences.'''
        pass

    def insert_comment(self, e): # (M-#)
        '''Without a numeric argument, the value of the comment-begin
        variable is inserted at the beginning of the current line. If a
        numeric argument is supplied, this command acts as a toggle: if the
        characters at the beginning of the line do not match the value of
        comment-begin, the value is inserted, otherwise the characters in
        comment-begin are deleted from the beginning of the line. In either
        case, the line is accepted as if a newline had been typed.'''
        pass

    def dump_functions(self, e): # ()
        '''Print all of the functions and their key bindings to the Readline
        output stream. If a numeric argument is supplied, the output is
        formatted in such a way that it can be made part of an inputrc
        file. This command is unbound by default.'''
        pass

    def dump_variables(self, e): # ()
        '''Print all of the settable variables and their values to the
        Readline output stream. If a numeric argument is supplied, the
        output is formatted in such a way that it can be made part of an
        inputrc file. This command is unbound by default.'''
        pass

    def dump_macros(self, e): # ()
        '''Print all of the Readline key sequences bound to macros and the
        strings they output. If a numeric argument is supplied, the output
        is formatted in such a way that it can be made part of an inputrc
        file. This command is unbound by default.'''
        pass

    #Create key bindings:

    def init_editing_mode(self, e): # (C-e)
        '''When in vi command mode, this causes a switch to emacs editing
        mode.'''

        self._bind_exit_key('Control-d')
        self._bind_exit_key('Control-z')

        # I often accidentally hold the shift or control while typing space
        self._bind_key('Shift-space',       self.self_insert)
        self._bind_key('Control-space',     self.self_insert)
        self._bind_key('Return',            self.accept_line)
        self._bind_key('Left',              self.backward_char)
        self._bind_key('Control-b',         self.backward_char)
        self._bind_key('Right',             self.forward_char)
        self._bind_key('Control-f',         self.forward_char)
        self._bind_key('BackSpace',         self.backward_delete_char)
        self._bind_key('Home',              self.beginning_of_line)
        self._bind_key('End',               self.end_of_line)
        self._bind_key('Delete',            self.delete_char)
        self._bind_key('Control-d',         self.delete_char)
        self._bind_key('Clear',             self.clear_screen)

# make it case insensitive
def commonprefix(m):
    "Given a list of pathnames, returns the longest common leading component"
    if not m: return ''
    prefix = m[0]
    for item in m:
        for i in range(len(prefix)):
            if prefix[:i+1].lower() != item[:i+1].lower():
                prefix = prefix[:i]
                if i == 0: return ''
                break
    return prefix


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CommandEnum</title>
<meta name="date" content="2016-01-31">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

fr.eseo.game.command

Enum CommandEnum

java.lang.Object

java.lang.Enum<CommandEnum>

fr.eseo.game.command.CommandEnum

All Implemented Interfaces:

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

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

CommandEnum enum.

Enum Constant Summary

Enum Constants

Enum Constant and Description

CORRECT_MOVE

Refus de déplacement [/A X-Y-energy] {1}.

CRAZY_MONKEYS

Indication position singes erratiques [/e X1-Y1-...]{*} {1}.

HUNTER_MONKEYS

Indication position singes chasseurs [/c X2-Y2-...]{*} {1}.

INCORRECT_MOVE

Refus de déplacement [/R] {1}.

ISLAND

Indication carte [/C l h c1l-...

MOVE_PIRATE_CLIENT

Deplacement Pirate [/D X Y] (entre -1 et 1 avec au moins un 0) {1}.

MOVE_PIRATE_SERVER

Deplacement pirate identifié [/p id-X-Y] {*}.

NEW_GAME

Indication nouvelle partie [/N] {*} {1}.

NEW_PIRATE_CLIENT

Inscription Client-Pirate [/I] {1}.

NEW_PIRATE_SERVER

Indication nouveau pirate [/n id-X-Y] {*}.

PIRATE

Identifiant pirate [/i id-X-Y-energy] (id == socket) {1}.

PIRATES

Indication autres pirates [/P id1-X1-Y1-...] {1}.

REMOVE_PIRATE

Suppression pirate [/s id] {*} {1}.

RHUM

Indication visibilité rhum [/b id-visible] {*} {1}.

RHUMS

Indication position rhum et visibilité [/B X1-Y1-vis1-...]

TREASURE

Indication position tresor [/T X-Y] (si decouvert) {*}{1}.

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

static CommandEnum
fromString(java.lang.String command)

Parse the command string to the enum command.

java.lang.String
toString()

ToString.

static CommandEnum
valueOf(java.lang.String name)

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

static CommandEnum[]
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, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

NEW_PIRATE_CLIENT

public static final CommandEnum NEW_PIRATE_CLIENT

Inscription Client-Pirate [/I] {1}.

MOVE_PIRATE_CLIENT

public static final CommandEnum MOVE_PIRATE_CLIENT

Deplacement Pirate [/D X Y] (entre -1 et 1 avec au moins un 0) {1}.

PIRATE

public static final CommandEnum PIRATE

Identifiant pirate [/i id-X-Y-energy] (id == socket) {1}.

CORRECT_MOVE

public static final CommandEnum CORRECT_MOVE

Refus de déplacement [/A X-Y-energy] {1}.

INCORRECT_MOVE

public static final CommandEnum INCORRECT_MOVE

Refus de déplacement [/R] {1}.

PIRATES

public static final CommandEnum PIRATES

Indication autres pirates [/P id1-X1-Y1-...] {1}.

NEW_PIRATE_SERVER

public static final CommandEnum NEW_PIRATE_SERVER

Indication nouveau pirate [/n id-X-Y] {*}.

REMOVE_PIRATE

public static final CommandEnum REMOVE_PIRATE

Suppression pirate [/s id] {*} {1}.

MOVE_PIRATE_SERVER

public static final CommandEnum MOVE_PIRATE_SERVER

Deplacement pirate identifié [/p id-X-Y] {*}.

ISLAND

public static final CommandEnum ISLAND

Indication carte [/C l h c1l-...-ch1-...-chl] {1}.

CRAZY_MONKEYS

public static final CommandEnum CRAZY_MONKEYS

Indication position singes erratiques [/e X1-Y1-...]{*} {1}.

HUNTER_MONKEYS

public static final CommandEnum HUNTER_MONKEYS

Indication position singes chasseurs [/c X2-Y2-...]{*} {1}.

RHUMS

public static final CommandEnum RHUMS

Indication position rhum et visibilité [/B X1-Y1-vis1-...](vis1 == 0 ou
 1) {*} {1}.

RHUM

public static final CommandEnum RHUM

Indication visibilité rhum [/b id-visible] {*} {1}.

TREASURE

public static final CommandEnum TREASURE

Indication position tresor [/T X-Y] (si decouvert) {*}{1}.

NEW_GAME

public static final CommandEnum NEW_GAME

Indication nouvelle partie [/N] {*} {1}.

Method Detail

values

public static CommandEnum[] 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 (CommandEnum c : CommandEnum.values())
    System.out.println(c);

Returns:

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

valueOf

public static CommandEnum 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

fromString

public static CommandEnum fromString(java.lang.String command)
                              throws java.lang.NullPointerException

Parse the command string to the enum command.

Parameters:

command - String command.

Returns:

commandEnum The enum command.

Throws:

java.lang.NullPointerException - NullPointerException.

toString

public java.lang.String toString()

ToString.

Overrides:

toString in class java.lang.Enum<CommandEnum>

Returns:

string String of the command class.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE
    RecordWildCards
    #-}

{-|
Module      : HSat.Problen.Instances.Common.Clauses
Description : The 'Clause' data type
Copyright   : (c) Andrew Burnett 2014-2015
Maintainer  : andyburnett88@gmail.com
Stability   : experimental
Portability : Unknown

This module exports the common functions and definitions of 'Clauses' which is
a collection of 'Clause'.

These can be used, for example, to represent a collection of 'Clause' in Conjunctive
Normal Form and Disjunctive Normal Form. Details however are kept abstract
-}
module HSat.Problem.Instances.Common.Clauses (
  -- * Clause
  Clauses,
  getVectClause,           -- :: Clauses -> Vector Clause
  getSizeClauses,          -- :: Clauses -> Word
  -- * Construction
  mkClauses,               -- :: Vector Clause -> Clauses
  mkClausesFromClause,     -- :: [Clause] -> Clauses
  emptyClauses,            -- :: Clauses
  clausesAddClause,        -- :: Clauses -> Clause -> Clauses
  mkClausesFromIntegers,   -- :: [[Integer]] -> Clauses
  -- * Other Functions
  clausesToIntegers,       -- :: Clauses -> [[Integer]]
  clausesIsEmpty,          -- :: Clauses -> Bool
  findMaxVar,              -- :: Clauses -> Word
  getSetOfVars,            -- :: Clauses -> Set Variable
  getSetPos,               -- :: Clauses -> Set Variable
  getSetNeg                -- :: Clauses -> Set Variable
  ) where

import qualified Data.Set                                       as S
import           Data.Vector                                    (Vector)
import qualified Data.Vector                                    as V
import           HSat.Problem.Instances.Common.Clause
import           HSat.Problem.Instances.Common.Clause.Internal
import           HSat.Problem.Instances.Common.Clauses.Internal
import           HSat.Problem.Instances.Common.Literal
import           HSat.Problem.Instances.Common.Sign
import           HSat.Problem.Instances.Common.Variable

{-|
Constructs 'Clauses' from a 'Vector' of 'Clause'
-}
mkClauses      :: Vector Clause -> Clauses
mkClauses vect =
  Clauses vect (toEnum $ V.length vect)

{-|
Constructs an empty 'Clauses'
-}
emptyClauses :: Clauses
emptyClauses = Clauses V.empty 0

{-|
Construct a 'Clauses' from a list of 'Clause'
-}
mkClausesFromClause :: [Clause] -> Clauses
mkClausesFromClause =
  foldl clausesAddClause emptyClauses

{-|
Append the 'Clause' argument to the end of the 'Clauses' and returns the new
'Clauses'
-}
clausesAddClause                  :: Clauses -> Clause -> Clauses
clausesAddClause (Clauses cl n) c =
  Clauses (V.snoc cl c) (n+1)

{-|
Returns 'True' if there are no 'Clause' within the argument
-}
clausesIsEmpty               :: Clauses -> Bool
clausesIsEmpty (Clauses _ 0) = True
clausesIsEmpty _             = False

{-|
Takes a list of list of 'Integer' and constructs a 'Clauses'
-}
mkClausesFromIntegers :: [[Integer]] -> Clauses
mkClausesFromIntegers =
  foldl (\clauses ints ->
          clausesAddClause clauses (mkClauseFromIntegers ints)) emptyClauses

{-|
Constructs a list of lists of 'Integer's from a 'Clauses'
-}
clausesToIntegers :: Clauses -> [[Integer]]
clausesToIntegers =
  V.toList . V.map clauseToIntegers . getVectClause

{-|
A generic method for accumulating information from
each 'Literal' in a 'Clauses'
-}
clFold                              :: (a -> Literal -> a) -> a -> Clauses -> a
clFold function initial Clauses{..} =
  V.foldl (\o Clause{..} ->
            V.foldl function o getVectLiteral
          ) initial $ getVectClause

{-|
Returns the maximum 'Word' represented in a 'Variable within the 'Clauses'
-}
findMaxVar :: Clauses -> Word
findMaxVar =
  clFold (\w Literal{..} ->
           let w' = getWord getVariable
           in if w' > w then
                w' else
                w
                ) 0

{-|
Returns the 'Set' of 'Variable's contained within the argument
-}
getSetOfVars :: Clauses -> S.Set Variable
getSetOfVars =
  clFold (\set Literal{..} ->
           S.insert getVariable set
           ) S.empty

{-|
Returns the 'Set' of all 'Variable's that appear with a positive 'Sign' in the
argument
-}
getSetPos :: Clauses -> S.Set Variable
getSetPos =
  clFold (
    \set Literal{..} ->
     if isPos getSign then
       S.insert getVariable set else
       set
    ) S.empty

{-|
Returns the 'Set' of all 'Variable's that appear with a negative 'Sign' in the
argument
-}
getSetNeg :: Clauses -> S.Set Variable
getSetNeg =
  clFold (
    \set Literal{..} ->
     if isNeg getSign then
       S.insert getVariable set else
       set
    ) S.empty


text:
[![npm](https://img.shields.io/npm/v/js-mq.svg?maxAge=2592000?style=flat-square)](https://www.npmjs.com/package/js-mq)

Register media queries by name and fire callbacks when crossing breakpoints

#### Register Media Queries:
```js
mq.register([
  {name: 'xs', query: '(max-width: 767px)'},
  {name: 'sm', query: '(min-width: 768px) and (max-width: 991px)'}
]);
```
```js
mq.register({name: 'md', query: '(min-width: 992px) and (max-width: 1199px)'});
mq.register({name: 'lg', query: '(min-width: 1200px)'});
```

#### Then register callbacks:
```js
mq.on('xs', function(e) {
  console.log('xs!');
});
```
```js
mq.on('xs', 'sm', function(e) {
  console.log('from sm to xs!');
});
```
```js
mq.on('*', 'lg', function(e) {
  console.log('from lg to any other registered query!');
});
```

## Demo
### [Check it out!](https://dontgoplastic.github.io/js-mq/demo)

## API

### mq.register(queryRule)
#### queryRule
Type: `Object` or `Array`

Register a query rule object (or an array of). Query rules must have unique names.

##### queryRule.name
Type: `String`

Name used to reference the media query.

##### queryRule.query
Type: `String`

The [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Syntax) to test.

```js
mq.register({name: 'xs', query: '(max-width: 767px)'});
```
```js
mq.register([
  {name: 'landscape', query: '(orientation: landscape)' },
  {name: 'portrait', query: '(orientation: portrait)' }
]);
```

### mq.on(queryNameOn[, queryNameFrom], activateCallback[, deactivateCallback][, alwaysFire])

Register callbacks to be fired when you've entered (and optionally exited) specified media queries.

#### queryNameOn
Type: `String`

Space separated list of registered query names. When any of the named queries apply, the `activateCallback` will fire.

Special value `*` is considered a match on any media query update.

Values beginning with the `mq.config.inversePrefix` are considered a match when the prefixed name does not match. _These prefixed names are automatically created for you_. To use `not-xs` simply register `xs`.

value | matches
--- | ---
`xs` | on `xs` only
`xs sm lg` | on either `xs`, `sm`, or `lg`
`not-xs` | on any matching query except for `xs`
`*` | on any matching query

#### queryNameFrom
Type: `String` Default `*`

You may specify an additional query name set to further restrict when the rule is considered active and `activateCallback` fires. If this is specified (i.e. not `*`), in addition to the `queryNameOn` needing to match, the user must have also come from a state where `queryNameFrom` matched.

value | matches
--- | ---
`mq.on('xs', 'sm'` | on `xs` directly from `sm`
`mq.on('not-xs', 'sm'` | on anything other than `xs` directly from `sm`
`mq.on('*', 'sm'` | on any registered query directly from `sm`
`mq.on('*', 'xs sm'` | on any registered query directly from either `xs` or `sm`

#### activateCallback
Type: `Function` _TODO: Finalize and document callback params - recommendations welcome!_

Function that gets called when the registered rule activates.

#### deactivateCallback
Type: `Function` default `null`

Optional callback that gets fired when you go from an active to inactive state.

#### alwaysFire
Type: `Boolean` default `false`

By default, an `activateCallback` will not fire when moving from one applied media query to another. For example, `xs sm` will initially fire when either `xs` or `sm` applies, but from there if you move from one to the other, it will not fire again. Setting this to `true` changes this behavior.

```js
mq.on('*', function() {
  // fires once but never again
});

mq.on('*', function() {
  // fires every time a registered media query applies
}, true);
```


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.iOS.Runtime
{
	/// <summary>
	/// Parses JavaScript source code for errors.
	/// </summary>
	[CommandResponse(ProtocolName.Runtime.Parse)]
	[SupportedBy("iOS")]
	public class ParseCommandResponse
	{
		/// <summary>
		/// Gets or sets Parse result.
		/// </summary>
		public string Result { get; set; }
		/// <summary>
		/// Gets or sets Parse error message.
		/// </summary>
		[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
		public string Message { get; set; }
		/// <summary>
		/// Gets or sets Range in the source where the error occurred.
		/// </summary>
		[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
		public ErrorRange Range { get; set; }
	}
}


text:
package com.google.gerrit.server.restapi.change;

import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ChildCollection;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.change.ReviewerResource;
import com.google.gerrit.server.change.VoteResource;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.Map;
import java.util.TreeMap;

@Singleton
public class Votes implements ChildCollection<ReviewerResource, VoteResource> {
  private final DynamicMap<RestView<VoteResource>> views;
  private final List list;

  @Inject
  Votes(DynamicMap<RestView<VoteResource>> views, List list) {
    this.views = views;
    this.list = list;
  }

  @Override
  public DynamicMap<RestView<VoteResource>> views() {
    return views;
  }

  @Override
  public RestView<ReviewerResource> list() throws AuthException {
    return list;
  }

  @Override
  public VoteResource parse(ReviewerResource reviewer, IdString id)
      throws ResourceNotFoundException, AuthException, MethodNotAllowedException {
    if (reviewer.getRevisionResource() != null && !reviewer.getRevisionResource().isCurrent()) {
      throw new MethodNotAllowedException("Cannot access on non-current patch set");
    }
    return new VoteResource(reviewer, id.get());
  }

  @Singleton
  public static class List implements RestReadView<ReviewerResource> {
    private final ApprovalsUtil approvalsUtil;

    @Inject
    List(ApprovalsUtil approvalsUtil) {
      this.approvalsUtil = approvalsUtil;
    }

    @Override
    public Map<String, Short> apply(ReviewerResource rsrc) throws MethodNotAllowedException {
      if (rsrc.getRevisionResource() != null && !rsrc.getRevisionResource().isCurrent()) {
        throw new MethodNotAllowedException("Cannot list votes on non-current patch set");
      }

      Map<String, Short> votes = new TreeMap<>();
      Iterable<PatchSetApproval> byPatchSetUser =
          approvalsUtil.byPatchSetUser(
              rsrc.getChangeResource().getNotes(),
              rsrc.getChange().currentPatchSetId(),
              rsrc.getReviewerUser().getAccountId(),
              null,
              null);
      for (PatchSetApproval psa : byPatchSetUser) {
        votes.put(psa.getLabel(), psa.getValue());
      }
      return votes;
    }
  }
}


text:
////////////////////////////////////////////////////////////////////////////////
// File:    LprJobProgressEventArgs.cs
// Purpose: Class containing print job progress event data.
// Notice:  Copyright 2010 SunCat Services
// Author:  Edward F Eaglehouse
//
// THIS WORK IS PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES
// OR CONDITIONS OR GUARANTEES.
//
// This product is licensed under the terms of The Code Project Open
// License (CPOL) 1.02. You are free to use this code in any application,
// private, public, or commercial, subject to this license agreement. A
// copy of this license may be found on the web at
// http://www.codeproject.com/info/cpol10.aspx.
////////////////////////////////////////////////////////////////////////////////
// Revision    Contributor
// 12/08/2010  Edward F Eaglehouse
//      Initial revision.
////////////////////////////////////////////////////////////////////////////////

using System;

using System.Collections.Generic;
using System.Text;

namespace MobileLPR
{
    /// <summary>
    /// Class containing print job progress event data.
    /// </summary>
    public class LprJobProgressEventArgs : EventArgs
    {

        #region Private Members

        /// <summary>
        /// Local pathname of file being transferred.
        /// </summary>
        private String pathname_ = String.Empty;

        /// <summary>
        /// Server name of file being transferred.
        /// </summary>
        private String serverFilename_ = String.Empty;

        /// <summary>
        /// Total number of local bytes to be sent for the job.
        /// </summary>
        private Int64 total_ = 0;

        /// <summary>
        /// Current number of bytes sent for the job.
        /// </summary>
        private Int64 used_ = 0;

        /// <summary>
        /// Type of command for which progress is being reported.
        /// </summary>
        private LprJob.ServerCommands command_ = LprJob.ServerCommands.None;

        #endregion

        #region Properties

        /// <summary>
        /// Get or set local pathname of file being transferred.
        /// </summary>
        public String Pathname
        {
            get { return pathname_; }
            set { pathname_ = value; }
        }

        /// <summary>
        /// Get or set server name of file being transferred.
        /// </summary>
        public String ServerFilename
        {
            get { return serverFilename_; }
            set { serverFilename_ = value; }
        }

        /// <summary>
        /// Get or set total number of local bytes to be sent for the job.
        /// </summary>
        public Int64 Total
        {
            get { return total_; }
            set { total_ = value; }
        }

        /// <summary>
        /// Get or set current number of bytes sent for the job.
        /// </summary>
        public Int64 Used
        {
            get { return used_; }
            set { used_ = value; }
        }

        /// <summary>
        /// Get or set type of command for which progress is being reported.
        /// </summary>
        public LprJob.ServerCommands Command
        {
            get { return command_; }
            set { command_ = value; }
        }

        #endregion

    }

}


text:
FROM ubuntu:16.04

WORKDIR /opt/ownCA
ADD . .
RUN apt-get update
RUN apt-get install -y python-pip
RUN apt-get install -y libssl-dev
RUN pip install -r requirements.txt
RUN chmod a+x start.sh

EXPOSE 80

VOLUME database
VOLUME certs/migrations

CMD /opt/ownCA/start.sh


text:
<?php
class diMigration_20181027141056 extends \diCore\Database\Tool\Migration
{
	public static $idx = '20181027141056';
	public static $name = 'Page cache index';

	public function up()
	{
		/** @var \diCore\Database\Legacy\Mongo $mongo */
		$mongo = \diCore\Database\Connection::get('mongo_main')->getDb();

		$mongo->getCollectionResource(\diCore\Entity\PageCache\Model::table)
			->createIndex([
				'uri' => 1,
				'active' => 1,
			], [
				'name' => 'uri_idx',
			]);
	}

	public function down()
	{
		/** @var \diCore\Database\Legacy\Mongo $mongo */
		$mongo = \diCore\Database\Connection::get('mongo_main')->getDb();

		$mongo->getCollectionResource(\diCore\Entity\PageCache\Model::table)
			->dropIndex('uri_idx');
	}
}


text:
import {join} from 'path';
import mkdirp from 'mkdirp';

exports.initialize = dir => {
  const dirs = [
    join(dir, '.coren', 'commonjs'),
    join(dir, '.coren', 'html')
  ];
  dirs.forEach(d => mkdirp.sync(d));
};
// .coren
exports.getRootPath = dir => {
  return join(dir, '.coren');
};

exports.getAssetsJsonPath = dir => {
  return join(dir, '.coren', 'assets.json');
};

exports.getSsrDir = dir => {
  return join(dir, '.coren', 'html');
};

exports.getCommonJSDir = dir => {
  return join(dir, '.coren', 'commonjs');
};


text:
package com.azurehorsecreations.shopper.presentation;

import android.os.Handler;
import android.os.Looper;

import com.azurehorsecreations.shopper.domain.executor.IMainThread;

/**
 * This class makes sure that the runnable we provide will be run on the main UI thread.
 */
public class MainThreadImpl implements IMainThread {

    private static IMainThread sMainThread;

    private Handler mHandler;

    private MainThreadImpl() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void post(Runnable runnable) {
        mHandler.post(runnable);
    }

    public static IMainThread getInstance() {
        if (sMainThread == null) {
            sMainThread = new MainThreadImpl();
        }
        return sMainThread;
    }
}


text:
'use strict';

idl_test(
  ['webrtc-identity'],
  ['webrtc', 'mediacapture-streams', 'html', 'dom', 'webidl'],
  async idlArray => {
    idlArray.add_objects({
      RTCPeerConnection: [`new RTCPeerConnection()`],
      RTCIdentityAssertion: [`new RTCIdentityAssertion('idp', 'name')`],
      MediaStreamTrack: ['track'],
      // TODO: RTCIdentityProviderGlobalScope
      // TODO: RTCIdentityProviderRegistrar
    });

    try {
      self.track = await navigator.mediaDevices
          .getUserMedia({audio: true})
          .then(m => m.getTracks()[0]);
    } catch (e) {}
  }
);


text:
use super::Exop;

pub const STARTTLS_OID: &str = "1.3.6.1.4.1.1466.20037";

/// StartTLS extended operation ([RFC 4511](https://tools.ietf.org/html/rfc4511#section-4.14)).
///
/// This operation isn't meant to be directly used by user code; it is used by
/// connection-establishment routines when the StartTLS mechanism of securing the
/// connection is requested by the user.
pub struct StartTLS;

impl From<StartTLS> for Exop {
    fn from(_s: StartTLS) -> Exop {
        Exop {
            name: Some(STARTTLS_OID.to_owned()),
            val: None,
        }
    }
}


text:
'use strict';
var util = require('util'),
    yeoman = require('yeoman-generator'),
    fs = require('fs'),
    _ = require('lodash'),
    _s = require('underscore.string'),
    pluralize = require('pluralize');

var EntityGenerator = module.exports = function EntityGenerator(args, options, config) {
  // By calling `NamedBase` here, we get the argument to the subgenerator call
  // as `this.name`.
  yeoman.generators.NamedBase.apply(this, arguments);

  console.log('You called the entity subgenerator with the argument ' + this.name + '.');

  fs.readFile('generator.json', 'utf8', function (err, data) {
    if (err) {
      console.log('Error: ' + err);
      return;
    }
    this.generatorConfig = JSON.parse(data);
  }.bind(this));
};

util.inherits(EntityGenerator, yeoman.generators.NamedBase);

EntityGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  console.log('\nPlease specify an attribute:');

  var prompts = [{
    type: 'input',
    name: 'attrName',
    message: 'What is the name of the attribute?',
    default: 'myattr'
  },
  {
    type: 'list',
    name: 'attrType',
    message: 'What is the type of the attribute?',
    choices: ['String', 'Integer', 'Long', 'Float', 'Double', 'Boolean', 'Date', 'Enum'],
    default: 'String'
  },
  {
    when: function (props) { return (/String/).test(props.attrType); },
    type: 'input',
    name: 'minLength',
    message: 'Enter the minimum length for the String attribute, or hit enter:',
    validate: function (input) {
      if (input && isNaN(input)) {
        return "Please enter a number.";
      }
      return true;
    }
  },
  {
    when: function (props) { return (/String/).test(props.attrType); },
    type: 'input',
    name: 'maxLength',
    message: 'Enter the maximum length for the String attribute, or hit enter:',
    validate: function (input) {
      if (input && isNaN(input)) {
        return "Please enter a number.";
      }
      return true;
    }
  },
  {
    when: function (props) { return (/Integer|Long|Float|Double/).test(props.attrType); },
    type: 'input',
    name: 'min',
    message: 'Enter the minimum value for the numeric attribute, or hit enter:',
    validate: function (input) {
      if (input && isNaN(input)) {
        return "Please enter a number.";
      }
      return true;
    }
  },
  {
    when: function (props) { return (/Integer|Long|Float|Double/).test(props.attrType); },
    type: 'input',
    name: 'max',
    message: 'Enter the maximum value for the numeric attribute, or hit enter:',
    validate: function (input) {
      if (input && isNaN(input)) {
        return "Please enter a number.";
      }
      return true;
    }
  },
  {
    when: function (props) { return (/Date/).test(props.attrType); },
    type: 'list',
    name: 'dateConstraint',
    message: 'Constrain the date as follows:',
    choices: ['None', 'Past dates only', 'Future dates only'],
    filter: function (input) {
      if (/Past/.test(input)) return 'Past';
      if (/Future/.test(input)) return 'Future';
      return '';
    },
    default: 'None'
  },
  {
    when: function (props) { return (/Enum/).test(props.attrType); },
    type: 'input',
    name: 'enumValues',
    message: 'Enter an enumeration of values, separated by commas'
  },
  {
    type: 'confirm',
    name: 'required',
    message: 'Is the attribute required to have a value?',
    default: true
  },
  {
    type: 'confirm',
    name: 'again',
    message: 'Would you like to enter another attribute or reenter a previous attribute?',
    default: true
  }];

  this.prompt(prompts, function (props) {
    this.attrs = this.attrs || [];
    var attrType = props.attrType;
    var attrImplType = props.attrType;
    if (attrType === 'String') {
      attrImplType = 'string';
    } else if (attrType === 'Integer') {
      attrImplType = 'int';
    } else if (attrType === 'Long') {
      attrImplType = 'long';
    } else if (attrType === 'Float') {
      attrImplType = 'float';
    } else if (attrType === 'Double') {
      attrImplType = 'double';
    } else if (attrType === 'Boolean') {
      attrImplType = 'bool';
    } else if (attrType === 'Date') {
      attrImplType = 'DateTime';
    } else if (attrType === 'Enum') {
      attrImplType = 'Enum';
    }
    this.attrs = _.reject(this.attrs, function (attr) { return attr.attrName === props.attrName; });
    this.attrs.push({
      attrName: props.attrName,
      attrType: attrType,
      attrImplType: attrImplType,
      minLength: props.minLength,
      maxLength: props.maxLength,
      min: props.min,
      max: props.max,
      dateConstraint: props.dateConstraint,
      enumValues: props.enumValues ? props.enumValues.split(',') : [],
      required: props.required
    });

    if (props.again) {
      this.askFor();
    } else {
      cb();
    }
  }.bind(this));
};

EntityGenerator.prototype.files = function files() {

  this.baseName = this.generatorConfig.baseName;
  this.platform = this.generatorConfig.platform;
  this.orm = this.generatorConfig.orm;
  this.entities = this.generatorConfig.entities;
  this.entities = _.reject(this.entities, function (entity) { return entity.name === this.name; }.bind(this));
  this.entities.push({ name: this.name, attrs: this.attrs});
  this.pluralize = pluralize;
  this.generatorConfig.entities = this.entities;
  this.generatorConfigStr = JSON.stringify(this.generatorConfig, null, '\t');

  var appDir = _s.capitalize(this.baseName) + '/'
  var modelsDir = appDir + 'Models/'
  var mappingsDir = modelsDir + 'Mappings/'
  var modulesDir = appDir + 'Modules/'
  var publicDir = appDir + 'Content/'
  this.template('_generator.json', 'generator.json');
  this.template('../../app/templates/_App/_Bootstrapper.cs', appDir + 'Bootstrapper.cs');
  this.template('_App/Models/_Entity.cs', modelsDir + _s.capitalize(this.name) + '.cs');
  this.template('_App/Modules/_EntityModule.cs', modulesDir + _s.capitalize(this.name) + 'Module.cs');
  _.each(this.attrs, function (attr) {
    if (attr.attrType === 'Enum') {
      this.attr = attr;
      this.template('_App/Models/_AttrEnum.cs', modelsDir + _s.capitalize(attr.attrName) + 'Enum.cs');
    }
  }.bind(this));
  if (this.orm == 'NHibernate') {
    this.template('_App/Models/Mappings/_EntityMapping.cs', mappingsDir + _s.capitalize(this.name) + 'Mapping.cs');
  }

  var publicCssDir = publicDir + 'css/';
  var publicJsDir = publicDir + 'js/';
  var publicViewDir = publicDir + 'views/';
  var publicEntityJsDir = publicJsDir + this.name + '/';
  var publicEntityViewDir = publicViewDir + this.name + '/';
  this.mkdir(publicEntityJsDir);
  this.mkdir(publicEntityViewDir);
  this.template('../../app/templates/public/_index.html', publicDir + 'index.html');
  this.template('public/js/entity/_entity-controller.js', publicEntityJsDir + this.name + '-controller.js');
  this.template('public/js/entity/_entity-router.js', publicEntityJsDir + this.name + '-router.js');
  this.template('public/js/entity/_entity-service.js', publicEntityJsDir + this.name + '-service.js');
  this.template('public/views/entity/_entities.html', publicEntityViewDir + pluralize(this.name) + '.html');
};


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Dasyscypha gigantosporus Rehm

### Remarks
null


text:
//
//  LocalConnection.h
//  RealReachability
//
//  Created by Dustturtle on 16/1/9.
//  Copyright (c) 2016 Dustturtle. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

#define GLocalConnection [LocalConnection sharedInstance]

/// We post self to this notification,
/// then you should invoke currentLocalConnectionStatus method to fetch current status.
extern NSString *const kLocalConnectionChangedNotification;

/// After start observering, we post this notification once,
/// you may invoke currentLocalConnectionStatus method to fetch initial status.
extern NSString *const kLocalConnectionInitializedNotification;

typedef NS_ENUM(NSInteger, LocalConnectionStatus)
{
    LC_UnReachable = 0,
    LC_WWAN        = 1,
    LC_WiFi        = 2
};

@interface LocalConnection : NSObject

/// Newly added property for KVO usage:
/// maybe you only want to observe the local network is available or not.
@property (nonatomic, assign) BOOL isReachable;

+ (instancetype)sharedInstance;

/**
 * Start observering local connection status.
 */
- (void)startNotifier;

/**
 *  Stop observering local connection status.
 */
- (void)stopNotifier;

/**
 *  Return current local connection status immediately.
 *
 *  @return see enum LocalConnectionStatus
 */
- (LocalConnectionStatus)currentLocalConnectionStatus;

@end


text:
package ts.internal.client.protocol;

import java.util.List;

import com.google.gson.JsonObject;

import ts.client.CommandNames;
import ts.client.refactors.ApplicableRefactorInfo;

/**
 * @see https://github.com/Microsoft/TypeScript/blob/master/src/server/protocol.ts
 */
public class GetApplicableRefactorsRequest extends Request {

	public GetApplicableRefactorsRequest(String file, int line, int offset) {
		super(CommandNames.GetApplicableRefactors.getName(), new GetApplicableRefactorsRequestArgs(file, line, offset));
	}

	public GetApplicableRefactorsRequest(String file, int startLine, int startOffset, int endLine, int endOffset) {
		super(CommandNames.GetApplicableRefactors.getName(),
				new GetApplicableRefactorsRangeRequestArgs(file, startLine, startOffset, endLine, endOffset));
	}

	@Override
	public Response<List<ApplicableRefactorInfo>> parseResponse(JsonObject json) {
		return GsonHelper.DEFAULT_GSON.fromJson(json, GetApplicableRefactorsResponse.class);
	}

}


text:
<?php

namespace MaxBeckers\AmazonAlexa\Test\Response;

use ArrayObject;
use MaxBeckers\AmazonAlexa\Response\Card;
use MaxBeckers\AmazonAlexa\Response\Directives\Display\RenderTemplateDirective;
use MaxBeckers\AmazonAlexa\Response\OutputSpeech;
use MaxBeckers\AmazonAlexa\Response\Reprompt;
use MaxBeckers\AmazonAlexa\Response\ResponseBody;
use PHPUnit\Framework\TestCase;

/**
 * @author Fabian Graßl <fabian.grassl@db-n.com>
 */
class ResponseBodyTest extends TestCase
{
    public function testJsonSerialize()
    {
        $rb = new ResponseBody();
        $this->assertEquals(new ArrayObject(), $rb->jsonSerialize());
        $rb->shouldEndSession = true;
        $this->assertEquals(new ArrayObject(['shouldEndSession' => true]), $rb->jsonSerialize());
        $card             = new Card();
        $rb->card         = $card;
        $os               = new OutputSpeech();
        $rb->outputSpeech = $os;
        $directive        = new RenderTemplateDirective();
        $rb->addDirective($directive);
        $reprompt     = new Reprompt($rb->outputSpeech);
        $rb->reprompt = $reprompt;
        $this->assertEquals(new ArrayObject([
            'outputSpeech'     => $os,
            'card'             => $card,
            'reprompt'         => $reprompt,
            'shouldEndSession' => true,
            'directives'       => [$directive],
        ]), $rb->jsonSerialize());
    }
}


text:
from twisted.internet.protocol import ClientFactory, ServerFactory, DatagramProtocol
from twisted.web.client import getPage
import urllib
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys
import hashlib
import math
import time, datetime
from config import *

class Tool:
    VLC, QTBROADCASTER = range(2)
tool = Tool.VLC

class RTSP_RTP_Client(LineReceiver):                 # for connecting to VideoServer via RTSP over TCP, then sending RTP packets
    class State:
        ANNOUNCE, TRACK_1, TRACK_2, RECORD, STREAM, PAUSE, TEARDOWN = range(7)

    def __init__(self):
        self.state = self.State.ANNOUNCE
        self.session = None
        self.nonce = None
        self.seq = 0
        LineReceiver.setRawMode(self)
        global video_server_connection
        video_server_connection = self

    def processState(self):
        self.seq+=1
        #if self.seq >= 6:
        #    print "DONE"
        #    return

        if self.state == self.State.ANNOUNCE:
            self.sendAnnounce(uri)
        elif self.state == self.State.TRACK_1:
            self.sendSetup('%s/trackid=1' % uri, 'RTP/AVP/TCP;unicast;mode=record;interleaved=0-1')
            if len(rtp_ports) == 1:
                self.state = self.State.TRACK_2
        elif self.state == self.State.TRACK_2:
            self.sendSetup('%s/trackid=2' % uri, 'RTP/AVP/TCP;unicast;mode=record;interleaved=2-3')
        elif self.state == self.State.RECORD:
            self.sendRecord(uri)
            if tool == Tool.VLC:
                startListeningForRDP_UDP()
        elif self.state == self.State.PAUSE:
            self.sendPause(uri)
        elif self.state == self.State.TEARDOWN:
            self.sendTeardown(uri)

    def connectionMade(self):
        self.processState()

    def datagramReceived(self, datagram, address):
        self.dataReceived(self, datagram)

    def dataReceived(self, data):
        for line in data.split('\r\n'):
            self.lineReceived(line)
        self.processState()

    def lineReceived(self, line):
        writeSecretDebug("receive VideoServer:" + line)
        self.session = self.readSession(line, self.session)
        self.nonce = self.readVariable(line, self.nonce, 'www-authenticate', 'nonce')
        if line == 'RTSP/1.0 200 OK':
            self.state += 1
        elif line == 'RTSP/1.0 401 Unauthorized' and self.seq > 1:
            self.state = self.State.TEARDOWN
            reactor.stop()
            error("ERROR 100: your Justin.tv stream key or your username is not correct.  Please see the 'readme.txt' file for help.")
        elif line == 'RTSP/1.0 403 Forbidden':
            self.state = self.State.TEARDOWN
            reactor.stop()
            error("ERROR 101: received a 403 Forbidden error from the server.  Please try again.")

    def readSession(self, line, currentvalue):
        if line.strip().lower().startswith('session: '):
            return line.partition(';')[0].partition(': ')[2]

    def writeLine(self, line):
        writeSecretDebug("send VideoServer:" + line)
        self.sendLine(line)

    def writeData(self, data):
        writeDebug('Sending data to VideoServer...')
        writeSecretDebug("send VideoServer:" + data)
        self.transport.write(data)

    def readVariable(self, line, currentvalue, key, subkey = None):
        if line.strip().lower().startswith(key):
            value = line.partition('=')[2]
            if not subkey: return value
            for item in value.split(','):
                if item.lower().strip().startswith(subkey.lower() + '='):
                    return item.partition('=')[2].strip('\"')
            return currentvalue
        return currentvalue

    def sendAnnounce(self, location):
        self.writeLine('ANNOUNCE %s RTSP/1.0' % location)
        self.writeLine('CSeq: %d' % self.seq)
        self.writeLine('Content-Type: application/sdp')
        self.writeLine('User-Agent: %s' % user_agent)
        self.writeAuthorization('ANNOUNCE')
        body = sdp_contents
        self.writeLine('Content-Length: ' + str(len(body) + 2))
        self.writeLine('')
        self.writeLine(body)

    def sendSetup(self, track, transport):
        self.sendMethod('SETUP', track, 'Transport: %s' % transport)

    def sendRecord(self, location):
        self.sendMethod('RECORD', location)
        print "Connected to VideoServer successfully."

    def sendPause(self, location):
        self.sendMethod('PAUSE', location)

    def sendTeardown(self, location):
        self.sendMethod('TEARDOWN', location)

    def sendMethod(self, method, location, specialHeader = None):
        self.writeLine('%s %s RTSP/1.0' % (method, location))
        self.writeLine('CSeq: %d' % self.seq)
        if specialHeader: self.writeLine(specialHeader)
        self.writeLine('User-Agent: %s' % user_agent)
        self.writeLine('Accept-Language: en-US')
        self.writeAuthorization(method)
        self.writeLine('')

    def writeAuthorization(self, method):
        if self.nonce:
            m = hashlib.md5()
            m.update(streamkey + ':' + realm + ':' + password)
            a1 = m.hexdigest()
            m = hashlib.md5()
            m.update(method + ':' + file)
            a2 = m.hexdigest()
            m = hashlib.md5()
            m.update(a1 + ':' + self.nonce + ':' + a2)
            response = m.hexdigest()
            self.writeLine('Authorization: Digest username="' + streamkey + '", realm="' + realm + '", nonce="' + self.nonce + '", uri="' + file + '", response="' + response + '"')

class RTP_Server(LineReceiver):                 # for receiving RTP packets from VLC on localhost via TCP
    def __init__(self):
        self.seq = 0
        LineReceiver.setRawMode(self)

    def connectionMade(self):
        print "Receiving video data..."

    def dataReceived(self, data):
        writeSecretDebug("receive VLC:" + data)
        if tool == Tool.QTBROADCASTER:
            self.seq+=1
            #self.writeData(data)
            if data.find('RTSP/1.0') > -1:
                self.writeLine('RTSP/1.0 200 OK')
                self.writeLine('Session: 1603617977;timeout=60')
                self.writeLine('Cseq: %d' % self.seq)
                if data.find('SETUP') > -1:
                    #if self.seq == 3:
                    client_ports = data.partition('client_port=')[2].partition(';')[0].split('-')
                    #self.writeLine('Transport: RTP/AVP/TCP;unicast;mode=record;interleaved=0-1')
                    global rtp_ports, rtcp_ports
                    if len(rtp_ports) == 0:
                        server_ports = ['6970', '6971']
                    else:
                        s1 = rtp_ports[len(rtp_ports) - 1] + 2
                        s2 = rtcp_ports[len(rtp_ports) - 1] + 2
                        server_ports = [str(s1), str(s2)]
                    writeSecretDebug("Parsed ports: " + client_ports[0]  + client_ports[1])
                    rtp_ports.append(int(client_ports[0]))
                    rtcp_ports.append(int(client_ports[1]))
                    self.writeLine('Transport: RTP/AVP;unicast;client_port=' + client_ports[0] + '-' + client_ports[1] + ';mode=record;source=127.0.0.1;server_port=' + server_ports[0] + '-' + server_ports[1])
                    #else:
                    #self.writeLine('Transport: RTP/AVP/TCP;unicast;mode=record;interleaved=2-3')
                if data.find('OPTIONS') > -1:
                    self.writeLine('Public: DESCRIBE, SETUP, TEARDOWN, PAUSE, OPTIONS, ANNOUNCE, RECORD, GET_PARAMETER, SET_PARAMETER')
                if data.find('RECORD') > -1:
                    connectToVideoServer()
                self.writeLine('Server: VideoServer Media Server Pro 1.7.0 build11947')
                if data.find('ANNOUNCE') > -1:
                    if data.find('Content-Length: ') > -1:
                        global sdp_contents
                        sdp_contents = data.partition('Content-Length: ')[2].partition("\r\n\r\n")[2]
                        sdp_contents = sdp_contents.rpartition("\r\n")[0]
                        #print "SDP CONTENTS: **" + sdp_contents + "**"

                self.writeLine('')
                self.writeLine('')
            else:       #forward non-RTSP packets (e.g. RTP)
                video_server_connection.writeData(data)
        #elif tool == Tool.VLC:
        #    video_server_connection.writeData(data)
        #elif tool == Tool.VLC:

    def writeData(self, data):
        writeSecretDebug("send VLC:" + data)
        self.transport.write(data)

    def writeLine(self, line):
        writeSecretDebug("send VLC:" + line)
        self.sendLine(line)

class VideoServerClientFactory(ClientFactory):
    protocol = RTSP_RTP_Client

    def clientConnectionFailed(self, connector, reason):
        print reason.getErrorMessage()
        #print "Connection FAILED!"
        self.reconnectIn(60)

    def clientConnectionLost(self, connector, reason):
        print reason.getErrorMessage()
        #print "Connection LOST!"
        print "Disconnected."
        self.reconnectIn(60)

    def reconnectIn(self, seconds):
        global should_reconnect
        t = datetime.datetime.now()
        should_reconnect = time.mktime(t.timetuple()) + seconds

class VLC_ServerFactory(ServerFactory):
    protocol = RTP_Server

class RTP_UDP_Server0(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        #print "0 => " + str(address[1])
        dataReceived(0, datagram)

class RTP_UDP_Server1(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        #print "1 => " + str(address[1])
        dataReceived(1, datagram)

class RTP_UDP_Server2(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        #print "2 => " + str(address[1])
        dataReceived(2, datagram)

class RTP_UDP_Server3(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        #print "3 => " + str(address[1])
        dataReceived(3, datagram)

def dataReceived(channel, data):
    writeDebug('Receiving data from VLC...')
    writeSecretDebug('received UDP data on channel ' + str(channel))
    if packet_log:
        if channel == 0:
            global o1
            o1 += str(ord(data[3])) + ', '
        if channel == 2:
            global o2
            o2 += str(ord(data[3])) + ', '
        print "channel 0 seq: " + o1
        print "channel 2 seq: " + o2

    video_server_connection.writeData('$' + chr(channel) + twoByteLength(len(data)) + data)

    global live_sent, should_reconnect
    t = datetime.datetime.now()
    tt = time.mktime(t.timetuple())
    if tt > live_sent:
        live_sent = tt + 60
        feedback("live", "")
        #print "SENT LIVE"
    if should_reconnect != 0 and tt > should_reconnect:
        should_reconnect = 0
        #print "Attempting to reconnect..."

def twoByteLength(dataLength):
    v = int(math.floor(dataLength / 256))
    return chr(v) + chr(dataLength - 256 * v)

def printHelp():
    print "-----------------------------------------------------------------------"
    print "  " + user_agent + " Help - Vladislav Yazhbin <vlad@justin.tv>"
    print "-----------------------------------------------------------------------"
    print "  Please use the following command line format:\n"
    print "      jtvlc login stream_key sdp_file [-d]\n"
    print "  For example:\n"
    print "      jtvlc lin_user live_gk423_c3r4 file:///home/justin/Desktop/vlc.sdp"
    print "      jtvlc mac_user live_l01d_dlj1 /Users/Justin/Desktop/vlc.sdp"
    print "      jtvlc.exe win_user live_pj42_8fkh2 c:/users/justin/vlc.sdp\n"
    print "  -d is an optional parameter that enables debug logging to the console\n"
    print "  Please see 'readme.txt' for more information.\n"
    checkVersion()

def main(argv):
    #feedback("start", "Started the app")
    if len(argv) < 4 or (len(argv) > 1 and argv[1]=='--help'):
        printHelp()
        return

    print user_agent + " By Vladislav Yazhbin <vlad@justin.tv>"
    checkVersion()

    global username, streamkey, sdp_location, sdp_contents, debug_log, file, uri
    username = argv[1]
    streamkey = argv[2]
    sdp_location = argv[3].replace('file://', '')
    file = '/app/live_user_' + username + '.sdp'
    uri = domain + file

    if len(argv) > 4 and argv[4]=="-d":
        debug_log = True

    if tool==Tool.VLC:
        try:
            f = open(sdp_location, 'r')
            try:
                sdp_contents = f.read().replace('\n', '\r\n').strip()
            finally:
                f.close()
        except IOError:
            error("ERROR 102:  Could not find or access file '%s'.\nSuggestions:  Have you started VLC yet?  Is it broadcasting?  Does VLC successfully create the file?  See 'readme.txt' for more information.\nAborting..." % sdp_location)
            return
        if sdp_contents == '' or sdp_contents == '(null)':
            error("ERROR 103: The sdp file is empty.  Please check your VLC streaming settings.")
            return
        global rtp_ports, rtcp_ports
        if sdp_contents.find('m=audio') > -1:
            sdp_contents = sdp_contents.replace('m=video', 'a=control:trackid=1\r\nm=video') + '\r\na=control:trackid=2'
            rtp_ports = [int(sdp_contents.partition('m=audio ')[2].partition(' RTP')[0]), int(sdp_contents.partition('m=video ')[2].partition(' RTP')[0])]
            rtcp_ports = [rtp_ports[0] + 1, rtp_ports[1] + 1]
        else:
            sdp_contents += '\r\na=control:trackid=1'
            rtp_ports = [int(sdp_contents.partition('m=video ')[2].partition(' RTP')[0])]
            rtcp_ports = [rtp_ports[0] + 1]
        connectToVideoServer()
    else:
        sf = VLC_ServerFactory()
        reactor.listenTCP(1234, sf)
        #startListeningForRDP_UDP()

    reactor.run()

def startListeningForRDP_UDP():
    global rtp_ports, rtcp_ports
    reactor.listenUDP(rtp_ports[0], RTP_UDP_Server0())
    reactor.listenUDP(rtcp_ports[0], RTP_UDP_Server1())
    if len(rtp_ports) > 1: reactor.listenUDP(rtp_ports[1], RTP_UDP_Server2())
    if len(rtcp_ports) > 1: reactor.listenUDP(rtcp_ports[1], RTP_UDP_Server3())

def writeSecretDebug(msg, alternate=None):
    writeDebug(msg, True, alternate)

def writeDebug(msg, secret=False, alternate=None):
    if not debug_log or (not packet_log and secret):
        if alternate:
            print alternate
        return
    print msg

def connectToVideoServer():
    cf = VideoServerClientFactory()
    reactor.connectTCP(ip, port, cf)

def checkVersion():
    f = urllib.urlopen("http://vladdata.heroku.com/api/info/jtvlc.xml")
    contents = f.read()
    print "-----------------------------------------------------------------------"
    if contents.find("<version>") != -1:
        v = contents.partition("<version>")[2].partition("</version>")[0]
        if v == version:
            print "  You are using the latest version."
        else:
            print "***********************************************************************"
            print
            print "  New version of Jtvlc is available: " + v + "!"
            print "  Please visit the community wiki to download it:"
            print "  " + website
            print "-----------------------------------------------------------------------"
            return
    print "  Jtvlc homepage:  " + website
    print "-----------------------------------------------------------------------"

def error(message):
    print "  " + message
    print "-----------------------------------------------------------------------"
    feedback('error', message)

def feedback(type, message):
    u = "http://vladdata.heroku.com/api/event/jtvlc.xml?" + urllib.urlencode({'type': type, 'message': message, 'channel': username, 'key': api_key})
    if type=='error':
        urllib.urlopen(u).read()
    else:
        getPage(u).addCallback(parseResults)

def parseResults(contents):
    pass #print contents

if __name__ == '__main__':
    main(sys.argv)


text:
using System.Dynamic;
using Newtonsoft.Json;

namespace Swashbuckle.SwaggerGen.TestFixtures
{
    [JsonObject]
    public class DynamicObjectSubType : DynamicObject
    {
        public string Property1 { get; set; }
    }
}