text:
'use strict';

import URI from 'vs/base/common/uri';
import {Event} from 'vs/base/common/events';
import {IEditorSelection} from 'vs/editor/common/editorCommon';
import CommonEvents = require('vs/workbench/common/events');
import {BaseEditor} from 'vs/workbench/browser/parts/editor/baseEditor';
import {IEditor} from 'vs/platform/editor/common/editor';
import {EditorInput, EditorOptions} from 'vs/workbench/common/editor';
import {Position} from 'vs/platform/editor/common/editor';

/**
 * All workbench events are listed here. For DOM events, see Monaco.Base.DomUtils.EventType.
 */
export class EventType {

	/**
	 * Event type for when an editor is opened. This event is only sent once for a specific editor type until another
	 * editor type gets opened. For example, when the user opens a file, the editorOpened event will be sent. If another
	 * file is opened, this event will not be fired again. If the user opens, e.g. the diff editor, editorOpened will be
	 * fired, since another editor type opened.
	 */
	static EDITOR_OPENED = 'editorOpened';

	/**
	 * Event type for when an editor is closed because another editor type is opened.
	 */
	static EDITOR_CLOSED = 'editorClosed';

	/**
	 * Event to indciate that an editor input is about to open. This event can be prevented to do something else instead.
	 */
	static EDITOR_INPUT_OPENING = 'editorInputOpening';

	/**
	 * Event type for when the editor input is about to change. This event is being sent before (!) the input is being set
	 * to the active editor. Use EDITOR_INPUT_CHANGED to react after the input has been set and displayed by the editor.
	 *
	 * Note: This event will also be emitted when multiple editors are open and the user sets focus from the active editor
	 * to another one. This allows to detect a focus change of the active editor.
	 */
	static EDITOR_INPUT_CHANGING = 'editorInputChanging';

	/**
	 * Event type to indicate that the editor options of the current active editor are changing.
	 */
	static EDITOR_OPTIONS_CHANGING = 'editorOptionsChanging';

	/**
	 * Event type for when the editor input has been changed in the currently active editor. This event is being sent after
	 * the input has been set and displayed by the editor.
	 *
	 * Note: This event will also be emitted when multiple editors are open and the user sets focus from the active editor
	 * to another one. This allows to detect a focus change of the active editor.
	 */
	static EDITOR_INPUT_CHANGED = 'editorInputChanged';

	/**
	 * Event type for when the editor input state changed.
	 */
	static EDITOR_INPUT_STATE_CHANGED = 'editorInputStateChanged';

	/**
	 * Event type for when the editor input failed to be set to the editor.
	 */
	static EDITOR_SET_INPUT_ERROR = 'editorSetInputError';

	/**
	 * An event type that fires when a text editor changes its selection.
	 */
	static TEXT_EDITOR_SELECTION_CHANGED = 'textEditorSelectionChanged';

	/**
	 * An event type that fires when a text editor mode changes.
	 */
	static TEXT_EDITOR_MODE_CHANGED = 'textEditorModeChanged';

	/**
	 * An event type that fires when a text editor content changes.
	 */
	static TEXT_EDITOR_CONTENT_CHANGED = 'textEditorContentChanged';

	/**
	 * An event type that fires when a text editor's configuration changes.
	 */
	static TEXT_EDITOR_CONFIGURATION_CHANGED = 'textEditorOptionsChanged';

	/**
	 * Event type for when a viewlet is about to open.
	 */
	static VIEWLET_OPENING = 'viewletOpening';

	/**
	 * Event type for when a viewlet is opened.
	 */
	static VIEWLET_OPENED = 'viewletOpened';

	/**
	 * Event type for when a viewlet is closed.
	 */
	static VIEWLET_CLOSED = 'viewletClosed';

	/**
	 * Event type for when the workbench has been fully created.
	 */
	static WORKBENCH_CREATED = 'workbenchCreated';

	/**
	 * Event type for when the workbench is about to being disposed.
	 */
	static WORKBENCH_DISPOSING = 'workbenchDisposing';

	/**
	 * Event type for when the workbench is fully disposed.
	 */
	static WORKBENCH_DISPOSED = 'workbenchDisposed';

	/**
	 * Event type for when an untitled file is becoming dirty.
	 */
	static UNTITLED_FILE_DIRTY = 'untitledFileDirty';

	/**
	 * Event type for when an untitled file is deleted.
	 */
	static UNTITLED_FILE_DELETED = 'untitledFileDeleted';

	/**
	 * Event type for when a resources encoding changes.
	 */
	static RESOURCE_ENCODING_CHANGED = 'resourceEncodingChanged';

	/**
	 * Event type for when the workbench options change. Listeners should refresh their
	 * assumption on workbench options after this event is emitted.
	 */
	static WORKBENCH_OPTIONS_CHANGED = 'workbenchOptionsChanged';
}

/**
 * Editor events are being emitted when the editor input changes, shows, is being saved or when the editor content changes.
 */
export class EditorEvent extends Event {
	public editor: IEditor;
	public editorId: string;
	public editorInput: EditorInput;
	public editorOptions: EditorOptions;
	public position: Position;

	private prevented: boolean;

	constructor(editor: IEditor, editorId: string, editorInput: EditorInput, editorOptions: EditorOptions, position: Position, originalEvent?: any) {
		super(originalEvent);

		this.editor = editor;
		this.editorId = editorId;
		this.editorInput = editorInput;
		this.editorOptions = editorOptions;
		this.position = position;
	}

	public prevent(): void {
		this.prevented = true;
	}

	public isPrevented(): boolean {
		return this.prevented;
	}
}

/**
 * Editor input events are being emitted when the editor input state changes.
 */
export class EditorInputEvent extends Event {
	public editorInput: EditorInput;

	constructor(editorInput: EditorInput, originalEvent?: any) {
		super(originalEvent);

		this.editorInput = editorInput;
	}
}

/**
 * A subclass of EditorEvent for text editor selection changes.
 */
export class TextEditorSelectionEvent extends EditorEvent {
	public selection: IEditorSelection;

	constructor(selection: IEditorSelection, editor: IEditor, editorId: string, editorInput: EditorInput, editorOptions: EditorOptions, position: Position, originalEvent?: any) {
		super(editor, editorId, editorInput, editorOptions, position, originalEvent);

		this.selection = selection;
	}
}

/**
 * Option change events are send when the options in the running instance change.
 */
export class OptionsChangeEvent extends Event {
	public key: string;
	public before: any;
	public after: any;

	constructor(key: string, before: any, after: any, originalEvent?: any) {
		super(originalEvent);

		this.key = key;
		this.before = before;
		this.after = after;
	}
}

/**
 * Command events are emitted when an action is being executed through a command handler (Keybinding).
 */
export class CommandEvent extends Event {
	public actionId: string;

	constructor(actionId: string, originalEvent?: any) {
		super(originalEvent);

		this.actionId = actionId;
	}
}

/**
 * Viewlet events are emitted when a viewlet opens or closes in the sidebar.
 */
export class ViewletEvent extends Event {
	public viewletId: string;

	constructor(viewletId: string, originalEvent?: any) {
		super(originalEvent);

		this.viewletId = viewletId;
	}
}

export class ResourceEvent extends Event {
	public resource: URI;

	constructor(resource: URI, originalEvent?: any) {
		super(originalEvent);

		this.resource = resource;
	}
}

export class UntitledEditorEvent extends ResourceEvent {
	// No new methods
}

redpajama_set_name: RedPajamaGithub


text:
package dbinterfacetest;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;

import java.sql.ResultSet;
import java.util.HashMap;

import dbinterface.DBInterface;
import dbinterface.Query;

public class RecordTest extends TestCase {
  private DBInterface dbi;

  @Before
  public void setUp() throws Exception {
    dbi = new DBInterface().open();
    dbi.runSql(TestRecord.CREATE);
    for(int i = 0; i < 10; i++) {
      TestRecord tr = new TestRecord();
      tr.stringVar = "String value";
      tr.boolVar = (i % 2) == 0;
      tr.intVar = i;
      tr.save(dbi);
    }
  }

  @After
  public void tearDown() throws Exception {
    dbi.close();
  }

  public void testGetValues() throws Exception {
    TestRecord tr = new TestRecord();
    HashMap<String, Object> vals = tr.getValues();
    assertEquals(0, vals.get("intvar"));
    assertEquals(false, vals.get("boolvar"));
    assertEquals(null, vals.get("stringvar"));
    tr.boolVar = true;
    tr.intVar = 658;
    tr.stringVar = "A string value";

    vals = tr.getValues();
    assertEquals(658, vals.get("intvar"));
    assertEquals(true, vals.get("boolvar"));
    assertEquals("A string value", vals.get("stringvar"));
  }

  public void testSetValues() throws Exception {
    TestRecord tr = new TestRecord();
    tr.setValues(new Query(dbi).from("testrecord").firstCursor());
    assertEquals(0, tr.intVar);
    assertEquals(true, tr.boolVar);
    assertEquals("String value", tr.stringVar);
  }

  public void testInsertValues() throws Exception {
    TestRecord tr = new TestRecord();
    HashMap<String, Object> vals = new HashMap<String, Object>();
    tr.boolVar = true;
    tr.intVar = 658;
    tr.stringVar = "Strings strings strings";
    tr.insertValues(vals);
    assertEquals(658, vals.get("intvar"));
    assertEquals("Strings strings strings", vals.get("stringvar"));
    assertEquals(true, vals.get("boolvar"));
  }

  public void testGetID() throws Exception {
    TestRecord tr = new TestRecord();
    tr.boolVar = true;
    tr.intVar = 658;
    tr.stringVar = "Strings strings strings";
    assertEquals(DBInterface.DEFAULT_ID, tr.getID());
    tr.save(dbi);
    assertEquals(11, tr.getID());
  }

  public void testSave() throws Exception {
    TestRecord tr = new TestRecord();
    tr.boolVar = true;
    tr.intVar = 658;
    tr.stringVar = "Strings";
    assertEquals(DBInterface.DEFAULT_ID, tr.getID());
    tr.save(dbi);
    assertEquals(11, tr.getID());
    assertEquals("Strings", tr.stringVar);
    assertEquals(658, tr.intVar);
    assertEquals(true, tr.boolVar);
    tr.save(dbi);
    assertEquals(11, tr.getID());
    assertEquals("Strings", tr.stringVar);
    assertEquals(658, tr.intVar);
    assertEquals(true, tr.boolVar);
  }

  public void testDrop() throws Exception {
    TestRecord tr = new TestRecord();
    tr.save(dbi);
    assertEquals(11, tr.getID());
    tr.drop(dbi);
    ResultSet rs = dbi.rawQuery("select count(*) as count from testrecord", new Object[]{});
    assertEquals(10, rs.getInt("count"));
  }

  public void testIsSaved() throws Exception {
    TestRecord tr = new TestRecord();
    assertEquals(false, tr.isSaved());
    tr.save(dbi);
    assertEquals(true, tr.isSaved());
  }

  public void testEquals() throws Exception {
    TestRecord tr = new TestRecord();
    tr.save(dbi);
    TestRecord tr1 = new TestRecord(new Query(dbi).from(TestRecord.class).orderBy("id DESC").firstCursor());
    assertEquals(true, tr.equals(tr1));
    TestRecord tr2 = new TestRecord(new Query(dbi).from(TestRecord.class).firstCursor());
    assertEquals(false, tr.equals(tr2));
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>mimetypes — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="../index.html"/>
        <link rel="up" title="Module code" href="index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

Module code »

mimetypes

Source code for mimetypes

"""Guess the MIME type of a file.

This module defines two useful functions:

guess_type(url, strict=True) -- guess the MIME type and encoding of a URL.

guess_extension(type, strict=True) -- guess the extension for a given MIME type.

It also contains the following, for tuning the behavior:

Data:

knownfiles -- list of files to parse
inited -- flag set when init() has been called
suffix_map -- dictionary mapping suffixes to suffixes
encodings_map -- dictionary mapping suffixes to encodings
types_map -- dictionary mapping suffixes to types

Functions:

init([files]) -- parse a list of files, default knownfiles (on Windows, the
  default values are taken from the registry)
read_mime_types(file) -- parse one file, return a dictionary or None
"""

import os
import sys
import posixpath
import urllib.parse
try:
    import winreg as _winreg
except ImportError:
    _winreg = None

__all__ = [
    "guess_type","guess_extension","guess_all_extensions",
    "add_type","read_mime_types","init"
]

knownfiles = [
    "/etc/mime.types",
    "/etc/httpd/mime.types",                    # Mac OS X
    "/etc/httpd/conf/mime.types",               # Apache
    "/etc/apache/mime.types",                   # Apache 1
    "/etc/apache2/mime.types",                  # Apache 2
    "/usr/local/etc/httpd/conf/mime.types",
    "/usr/local/lib/netscape/mime.types",
    "/usr/local/etc/httpd/conf/mime.types",     # Apache 1.2
    "/usr/local/etc/mime.types",                # Apache 1.3
    ]

inited = False
_db = None

class MimeTypes:
    """MIME-types datastore.

    This datastore can handle information from mime.types-style files
    and supports basic determination of MIME type from a filename or
    URL, and can guess a reasonable extension given a MIME type.
    """

    def __init__(self, filenames=(), strict=True):
        if not inited:
            init()
        self.encodings_map = encodings_map.copy()
        self.suffix_map = suffix_map.copy()
        self.types_map = ({}, {}) # dict for (non-strict, strict)
        self.types_map_inv = ({}, {})
        for (ext, type) in types_map.items():
            self.add_type(type, ext, True)
        for (ext, type) in common_types.items():
            self.add_type(type, ext, False)
        for name in filenames:
            self.read(name, strict)

    def add_type(self, type, ext, strict=True):
        """Add a mapping between a type and an extension.

        When the extension is already known, the new
        type will replace the old one. When the type
        is already known the extension will be added
        to the list of known extensions.

        If strict is true, information will be added to
        list of standard types, else to the list of non-standard
        types.
        """
        self.types_map[strict][ext] = type
        exts = self.types_map_inv[strict].setdefault(type, [])
        if ext not in exts:
            exts.append(ext)

    def guess_type(self, url, strict=True):
        """Guess the type of a file based on its URL.

        Return value is a tuple (type, encoding) where type is None if
        the type can't be guessed (no or unknown suffix) or a string
        of the form type/subtype, usable for a MIME Content-type
        header; and encoding is None for no encoding or the name of
        the program used to encode (e.g. compress or gzip).  The
        mappings are table driven.  Encoding suffixes are case
        sensitive; type suffixes are first tried case sensitive, then
        case insensitive.

        The suffixes .tgz, .taz and .tz (case sensitive!) are all
        mapped to '.tar.gz'.  (This is table-driven too, using the
        dictionary suffix_map.)

        Optional `strict' argument when False adds a bunch of commonly found,
        but non-standard types.
        """
        scheme, url = urllib.parse.splittype(url)
        if scheme == 'data':
            # syntax of data URLs:
            # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
            # mediatype := [ type "/" subtype ] *( ";" parameter )
            # data      := *urlchar
            # parameter := attribute "=" value
            # type/subtype defaults to "text/plain"
            comma = url.find(',')
            if comma < 0:
                # bad data URL
                return None, None
            semi = url.find(';', 0, comma)
            if semi >= 0:
                type = url[:semi]
            else:
                type = url[:comma]
            if '=' in type or '/' not in type:
                type = 'text/plain'
            return type, None           # never compressed, so encoding is None
        base, ext = posixpath.splitext(url)
        while ext in self.suffix_map:
            base, ext = posixpath.splitext(base + self.suffix_map[ext])
        if ext in self.encodings_map:
            encoding = self.encodings_map[ext]
            base, ext = posixpath.splitext(base)
        else:
            encoding = None
        types_map = self.types_map[True]
        if ext in types_map:
            return types_map[ext], encoding
        elif ext.lower() in types_map:
            return types_map[ext.lower()], encoding
        elif strict:
            return None, encoding
        types_map = self.types_map[False]
        if ext in types_map:
            return types_map[ext], encoding
        elif ext.lower() in types_map:
            return types_map[ext.lower()], encoding
        else:
            return None, encoding

    def guess_all_extensions(self, type, strict=True):
        """Guess the extensions for a file based on its MIME type.

        Return value is a list of strings giving the possible filename
        extensions, including the leading dot ('.').  The extension is not
        guaranteed to have been associated with any particular data stream,
        but would be mapped to the MIME type `type' by guess_type().

        Optional `strict' argument when false adds a bunch of commonly found,
        but non-standard types.
        """
        type = type.lower()
        extensions = self.types_map_inv[True].get(type, [])
        if not strict:
            for ext in self.types_map_inv[False].get(type, []):
                if ext not in extensions:
                    extensions.append(ext)
        return extensions

    def guess_extension(self, type, strict=True):
        """Guess the extension for a file based on its MIME type.

        Return value is a string giving a filename extension,
        including the leading dot ('.').  The extension is not
        guaranteed to have been associated with any particular data
        stream, but would be mapped to the MIME type `type' by
        guess_type().  If no extension can be guessed for `type', None
        is returned.

        Optional `strict' argument when false adds a bunch of commonly found,
        but non-standard types.
        """
        extensions = self.guess_all_extensions(type, strict)
        if not extensions:
            return None
        return extensions[0]

    def read(self, filename, strict=True):
        """
        Read a single mime.types-format file, specified by pathname.

        If strict is true, information will be added to
        list of standard types, else to the list of non-standard
        types.
        """
        with open(filename, encoding='utf-8') as fp:
            self.readfp(fp, strict)

    def readfp(self, fp, strict=True):
        """
        Read a single mime.types-format file.

        If strict is true, information will be added to
        list of standard types, else to the list of non-standard
        types.
        """
        while 1:
            line = fp.readline()
            if not line:
                break
            words = line.split()
            for i in range(len(words)):
                if words[i][0] == '#':
                    del words[i:]
                    break
            if not words:
                continue
            type, suffixes = words[0], words[1:]
            for suff in suffixes:
                self.add_type(type, '.' + suff, strict)

    def read_windows_registry(self, strict=True):
        """
        Load the MIME types database from Windows registry.

        If strict is true, information will be added to
        list of standard types, else to the list of non-standard
        types.
        """

        # Windows only
        if not _winreg:
            return

        def enum_types(mimedb):
            i = 0
            while True:
                try:
                    ctype = _winreg.EnumKey(mimedb, i)
                except EnvironmentError:
                    break
                else:
                    yield ctype
                i += 1

        with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
            for subkeyname in enum_types(hkcr):
                try:
                    with _winreg.OpenKey(hkcr, subkeyname) as subkey:
                        # Only check file extensions
                        if not subkeyname.startswith("."):
                            continue
                        # raises EnvironmentError if no 'Content Type' value
                        mimetype, datatype = _winreg.QueryValueEx(
                            subkey, 'Content Type')
                        if datatype != _winreg.REG_SZ:
                            continue
                        self.add_type(mimetype, subkeyname, strict)
                except EnvironmentError:
                    continue

[docs]def guess_type(url, strict=True):
    """Guess the type of a file based on its URL.

    Return value is a tuple (type, encoding) where type is None if the
    type can't be guessed (no or unknown suffix) or a string of the
    form type/subtype, usable for a MIME Content-type header; and
    encoding is None for no encoding or the name of the program used
    to encode (e.g. compress or gzip).  The mappings are table
    driven.  Encoding suffixes are case sensitive; type suffixes are
    first tried case sensitive, then case insensitive.

    The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
    to ".tar.gz".  (This is table-driven too, using the dictionary
    suffix_map).

    Optional `strict' argument when false adds a bunch of commonly found, but
    non-standard types.
    """
    if _db is None:
        init()
    return _db.guess_type(url, strict)

[docs]def guess_all_extensions(type, strict=True):
    """Guess the extensions for a file based on its MIME type.

    Return value is a list of strings giving the possible filename
    extensions, including the leading dot ('.').  The extension is not
    guaranteed to have been associated with any particular data
    stream, but would be mapped to the MIME type `type' by
    guess_type().  If no extension can be guessed for `type', None
    is returned.

    Optional `strict' argument when false adds a bunch of commonly found,
    but non-standard types.
    """
    if _db is None:
        init()
    return _db.guess_all_extensions(type, strict)

[docs]def guess_extension(type, strict=True):
    """Guess the extension for a file based on its MIME type.

    Return value is a string giving a filename extension, including the
    leading dot ('.').  The extension is not guaranteed to have been
    associated with any particular data stream, but would be mapped to the
    MIME type `type' by guess_type().  If no extension can be guessed for
    `type', None is returned.

    Optional `strict' argument when false adds a bunch of commonly found,
    but non-standard types.
    """
    if _db is None:
        init()
    return _db.guess_extension(type, strict)

[docs]def add_type(type, ext, strict=True):
    """Add a mapping between a type and an extension.

    When the extension is already known, the new
    type will replace the old one. When the type
    is already known the extension will be added
    to the list of known extensions.

    If strict is true, information will be added to
    list of standard types, else to the list of non-standard
    types.
    """
    if _db is None:
        init()
    return _db.add_type(type, ext, strict)

[docs]def init(files=None):
    global suffix_map, types_map, encodings_map, common_types
    global inited, _db
    inited = True    # so that MimeTypes.__init__() doesn't call us again
    db = MimeTypes()
    if files is None:
        if _winreg:
            db.read_windows_registry()
        files = knownfiles
    for file in files:
        if os.path.isfile(file):
            db.read(file)
    encodings_map = db.encodings_map
    suffix_map = db.suffix_map
    types_map = db.types_map[True]
    common_types = db.types_map[False]
    # Make the DB a global variable now that it is fully initialized
    _db = db

[docs]def read_mime_types(file):
    try:
        f = open(file)
    except OSError:
        return None
    with f:
        db = MimeTypes()
        db.readfp(f, True)
        return db.types_map[True]

def _default_mime_types():
    global suffix_map
    global encodings_map
    global types_map
    global common_types

    suffix_map = {
        '.svgz': '.svg.gz',
        '.tgz': '.tar.gz',
        '.taz': '.tar.gz',
        '.tz': '.tar.gz',
        '.tbz2': '.tar.bz2',
        '.txz': '.tar.xz',
        }

    encodings_map = {
        '.gz': 'gzip',
        '.Z': 'compress',
        '.bz2': 'bzip2',
        '.xz': 'xz',
        }

    # Before adding new types, make sure they are either registered with IANA,
    # at http://www.iana.org/assignments/media-types
    # or extensions, i.e. using the x- prefix

    # If you add to these, please keep them sorted!
    types_map = {
        '.a'      : 'application/octet-stream',
        '.ai'     : 'application/postscript',
        '.aif'    : 'audio/x-aiff',
        '.aifc'   : 'audio/x-aiff',
        '.aiff'   : 'audio/x-aiff',
        '.au'     : 'audio/basic',
        '.avi'    : 'video/x-msvideo',
        '.bat'    : 'text/plain',
        '.bcpio'  : 'application/x-bcpio',
        '.bin'    : 'application/octet-stream',
        '.bmp'    : 'image/x-ms-bmp',
        '.c'      : 'text/plain',
        # Duplicates :(
        '.cdf'    : 'application/x-cdf',
        '.cdf'    : 'application/x-netcdf',
        '.cpio'   : 'application/x-cpio',
        '.csh'    : 'application/x-csh',
        '.css'    : 'text/css',
        '.dll'    : 'application/octet-stream',
        '.doc'    : 'application/msword',
        '.dot'    : 'application/msword',
        '.dvi'    : 'application/x-dvi',
        '.eml'    : 'message/rfc822',
        '.eps'    : 'application/postscript',
        '.etx'    : 'text/x-setext',
        '.exe'    : 'application/octet-stream',
        '.gif'    : 'image/gif',
        '.gtar'   : 'application/x-gtar',
        '.h'      : 'text/plain',
        '.hdf'    : 'application/x-hdf',
        '.htm'    : 'text/html',
        '.html'   : 'text/html',
        '.ico'    : 'image/vnd.microsoft.icon',
        '.ief'    : 'image/ief',
        '.jpe'    : 'image/jpeg',
        '.jpeg'   : 'image/jpeg',
        '.jpg'    : 'image/jpeg',
        '.js'     : 'application/javascript',
        '.ksh'    : 'text/plain',
        '.latex'  : 'application/x-latex',
        '.m1v'    : 'video/mpeg',
        '.m3u'    : 'application/vnd.apple.mpegurl',
        '.m3u8'   : 'application/vnd.apple.mpegurl',
        '.man'    : 'application/x-troff-man',
        '.me'     : 'application/x-troff-me',
        '.mht'    : 'message/rfc822',
        '.mhtml'  : 'message/rfc822',
        '.mif'    : 'application/x-mif',
        '.mov'    : 'video/quicktime',
        '.movie'  : 'video/x-sgi-movie',
        '.mp2'    : 'audio/mpeg',
        '.mp3'    : 'audio/mpeg',
        '.mp4'    : 'video/mp4',
        '.mpa'    : 'video/mpeg',
        '.mpe'    : 'video/mpeg',
        '.mpeg'   : 'video/mpeg',
        '.mpg'    : 'video/mpeg',
        '.ms'     : 'application/x-troff-ms',
        '.nc'     : 'application/x-netcdf',
        '.nws'    : 'message/rfc822',
        '.o'      : 'application/octet-stream',
        '.obj'    : 'application/octet-stream',
        '.oda'    : 'application/oda',
        '.p12'    : 'application/x-pkcs12',
        '.p7c'    : 'application/pkcs7-mime',
        '.pbm'    : 'image/x-portable-bitmap',
        '.pdf'    : 'application/pdf',
        '.pfx'    : 'application/x-pkcs12',
        '.pgm'    : 'image/x-portable-graymap',
        '.pl'     : 'text/plain',
        '.png'    : 'image/png',
        '.pnm'    : 'image/x-portable-anymap',
        '.pot'    : 'application/vnd.ms-powerpoint',
        '.ppa'    : 'application/vnd.ms-powerpoint',
        '.ppm'    : 'image/x-portable-pixmap',
        '.pps'    : 'application/vnd.ms-powerpoint',
        '.ppt'    : 'application/vnd.ms-powerpoint',
        '.ps'     : 'application/postscript',
        '.pwz'    : 'application/vnd.ms-powerpoint',
        '.py'     : 'text/x-python',
        '.pyc'    : 'application/x-python-code',
        '.pyo'    : 'application/x-python-code',
        '.qt'     : 'video/quicktime',
        '.ra'     : 'audio/x-pn-realaudio',
        '.ram'    : 'application/x-pn-realaudio',
        '.ras'    : 'image/x-cmu-raster',
        '.rdf'    : 'application/xml',
        '.rgb'    : 'image/x-rgb',
        '.roff'   : 'application/x-troff',
        '.rtx'    : 'text/richtext',
        '.sgm'    : 'text/x-sgml',
        '.sgml'   : 'text/x-sgml',
        '.sh'     : 'application/x-sh',
        '.shar'   : 'application/x-shar',
        '.snd'    : 'audio/basic',
        '.so'     : 'application/octet-stream',
        '.src'    : 'application/x-wais-source',
        '.sv4cpio': 'application/x-sv4cpio',
        '.sv4crc' : 'application/x-sv4crc',
        '.svg'    : 'image/svg+xml',
        '.swf'    : 'application/x-shockwave-flash',
        '.t'      : 'application/x-troff',
        '.tar'    : 'application/x-tar',
        '.tcl'    : 'application/x-tcl',
        '.tex'    : 'application/x-tex',
        '.texi'   : 'application/x-texinfo',
        '.texinfo': 'application/x-texinfo',
        '.tif'    : 'image/tiff',
        '.tiff'   : 'image/tiff',
        '.tr'     : 'application/x-troff',
        '.tsv'    : 'text/tab-separated-values',
        '.txt'    : 'text/plain',
        '.ustar'  : 'application/x-ustar',
        '.vcf'    : 'text/x-vcard',
        '.wav'    : 'audio/x-wav',
        '.wiz'    : 'application/msword',
        '.wsdl'   : 'application/xml',
        '.xbm'    : 'image/x-xbitmap',
        '.xlb'    : 'application/vnd.ms-excel',
        # Duplicates :(
        '.xls'    : 'application/excel',
        '.xls'    : 'application/vnd.ms-excel',
        '.xml'    : 'text/xml',
        '.xpdl'   : 'application/xml',
        '.xpm'    : 'image/x-xpixmap',
        '.xsl'    : 'application/xml',
        '.xwd'    : 'image/x-xwindowdump',
        '.zip'    : 'application/zip',
        }

    # These are non-standard types, commonly found in the wild.  They will
    # only match if strict=0 flag is given to the API methods.

    # Please sort these too
    common_types = {
        '.jpg' : 'image/jpg',
        '.mid' : 'audio/midi',
        '.midi': 'audio/midi',
        '.pct' : 'image/pict',
        '.pic' : 'image/pict',
        '.pict': 'image/pict',
        '.rtf' : 'application/rtf',
        '.xul' : 'text/xul'
        }

_default_mime_types()

if __name__ == '__main__':
    import getopt

    USAGE = """\
Usage: mimetypes.py [options] type

Options:
    --help / -h       -- print this message and exit
    --lenient / -l    -- additionally search of some common, but non-standard
                         types.
    --extension / -e  -- guess extension instead of type

More than one type argument may be given.
"""

    def usage(code, msg=''):
        print(USAGE)
        if msg: print(msg)
        sys.exit(code)

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hle',
                                   ['help', 'lenient', 'extension'])
    except getopt.error as msg:
        usage(1, msg)

    strict = 1
    extension = 0
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-l', '--lenient'):
            strict = 0
        elif opt in ('-e', '--extension'):
            extension = 1
    for gtype in args:
        if extension:
            guess = guess_extension(gtype, strict)
            if not guess: print("I don't know anything about type", gtype)
            else: print(guess)
        else:
            guess, encoding = guess_type(gtype, strict)
            if not guess: print("I don't know anything about type", gtype)
            else: print('type:', guess, 'encoding:', encoding)

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
from __future__ import absolute_import

from kafka.producer.kafka import KafkaProducer

__all__ = [
    'KafkaProducer'
]


text:
var assert = require('assert');
var {Admin, Role} = require('../lib/index')

describe('Admin', function() {
  describe('constructor', function() {
    it('should work', function() {
      var a = new Admin(
        "id",
        "fn",
        "ln",
        "ph",
        true,
        "ak_token",
        "ak_uid",
        1,
        12,
        123,
        1234,
        12345,
        "profilePhotoUrl",
        [Role.ADMIN.name]
      )
      assert.equal(a.id, "id");
      assert.equal(a.first_name, "fn");
      assert.equal(a.last_name, "ln");
      assert.equal(a.phone, "ph");
      assert.equal(a.kind, "Admin");
      assert.ok(a.active);
      assert.equal(a.ak_access_token, "ak_token");
      assert.equal(a.ak_user_id, "ak_uid");
      assert.equal(a.ak_token_refresh_interval_sec, 1);
      assert.equal(a.ak_token_last_renewed_timestamp, 12);
      assert.equal(a.last_login_timestamp, 123);
      assert.equal(a.created_on_timestamp, 1234);
      assert.equal(a.member_since_timestamp, 12345);
      assert.deepEqual(a.roles, [Role.ADMIN.name])
      assert.equal(a.profilePhotoUrl, "profilePhotoUrl");
    });
  });
});


text:
// Copyright (c). All rights reserved.
//
// Licensed under the MIT license.

using Shouldly;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using Xunit;

namespace Microsoft.Dism.Tests
{
    public abstract class DismCollectionTest<TCollection, TItem> : TestBase
        where TCollection : ReadOnlyCollection<TItem>
        where TItem : class
    {
        protected DismCollectionTest(TestWimTemplate template)
            : base(template)
        {
        }

        protected abstract IntPtr Pointer { get; }

        [Fact]
        public void CollectionTest()
        {
            IntPtr pointer = Pointer;

            try
            {
                TCollection actual = GetActual(pointer);
                ReadOnlyCollection<TItem> expected = GetExpected();
                actual.ShouldBe(expected);
            }
            finally
            {
                Marshal.FreeHGlobal(pointer);
            }
        }

        [Fact]
        public void CollectionTest_Empty()
        {
            TCollection actual = GetActual(IntPtr.Zero);
            ReadOnlyCollection<TItem> expected = new ReadOnlyCollection<TItem>(new List<TItem>(0));
            actual.ShouldBe(expected);
        }

        protected abstract TCollection GetActual(IntPtr pointer);

        protected abstract ReadOnlyCollection<TItem> GetExpected();
    }
}


text:
namespace base {
class FilePath;
};

namespace xwalk {
namespace extensions {

class XWalkExternalAdapter;
class XWalkExternalInstance;

// XWalkExternalExtension implements an XWalkExtension backed by a shared
// library implemented using our C ABI (see XW_Extension.h).
//
// It works together with XWalkExternalAdapter to handle calls from shared
// library, and store the callbacks to call it back later. The associated
// XW_Extension is used to identify this extension when calling the shared
// library.
class XWalkExternalExtension : public XWalkExtension {
 public:
  explicit XWalkExternalExtension(const base::FilePath& path);

  ~XWalkExternalExtension() override;

  bool Initialize();

  void set_runtime_variables(const base::ValueMap& runtime_variables) {
    runtime_variables_ = runtime_variables;
  }

 protected:
  // XWalkExtension implementation.
  XWalkExtensionInstance* CreateInstance() override;

 private:
  friend class XWalkExternalAdapter;
  friend class XWalkExternalInstance;

  // Variables from the browser process. Usually things like currently-running
  // application ID.
  base::ValueMap runtime_variables_;

  // XW_CoreInterface_1 (from XW_Extension.h) implementation.
  void CoreSetExtensionName(const char* name);
  void CoreSetJavaScriptAPI(const char* js_api);
  void CoreRegisterInstanceCallbacks(
      XW_CreatedInstanceCallback created_callback,
      XW_DestroyedInstanceCallback destroyed_callback);
  void CoreRegisterShutdownCallback(XW_ShutdownCallback callback);
  void EntryPointsSetExtraJSEntryPoints(const char** entry_points);

  // XW_MessagingInterface_1 (from XW_Extension.h) implementation.
  void MessagingRegister(XW_HandleMessageCallback callback);

  // XW_MessagingInterface_2 (from XW_Extension.h) implementation.
  void MessagingRegisterBinaryMessageCallback(
      XW_HandleBinaryMessageCallback callback);

  // XW_Internal_SyncMessagingInterface_1 (from XW_Extension.h) implementation.
  void SyncMessagingRegister(XW_HandleSyncMessageCallback callback);

  // XW_Internal_BrowserInterface_1 (from XW_Browser.h) implementation.
  void RuntimeGetStringVariable(const char* key, char* value, size_t value_len);

  base::FilePath library_path_;
  base::ScopedNativeLibrary library_;
  XW_Extension xw_extension_;

  XW_CreatedInstanceCallback created_instance_callback_;
  XW_DestroyedInstanceCallback destroyed_instance_callback_;
  XW_ShutdownCallback shutdown_callback_;
  XW_HandleMessageCallback handle_msg_callback_;
  XW_HandleSyncMessageCallback handle_sync_msg_callback_;
  XW_HandleBinaryMessageCallback handle_binary_msg_callback_;

  bool initialized_;

  DISALLOW_COPY_AND_ASSIGN(XWalkExternalExtension);
};

}  // namespace extensions
}  // namespace xwalk

#endif  // XWALK_EXTENSIONS_COMMON_XWALK_EXTERNAL_EXTENSION_H_


text:
<?php

declare(strict_types=1);

namespace Bitrix24\SDK\Services\Telephony\Result;

use Bitrix24\SDK\Core\Result\AbstractItem;

/**
 * @property-read  string $CALL_ID
 * @property-read  int $CRM_CREATED_LEAD
 * @property-read  int $CRM_ENTITY_ID
 * @property-read  string $CRM_ENTITY_TYPE
 * @property-read  array $CRM_CREATED_ENTITIES
 * @property-read  string $LEAD_CREATION_ERROR
 */
class ExternalCallRegisterItemResult extends AbstractItem
{

}


text:
{% extends "base.html" %}
{%block extracss %}<link rel="stylesheet" href="css/pygments.css" type="text/css"> {% endblock %}
{%block extrajs %}

{% endblock %}

{% block title %} {{title}} {% endblock %}

{%block content %}

{{title}}

{{doc}}

{{code}}

Data used to generate the chart — {{name}}.json

{% endblock %}

{% block sidebar %} {{sidebar}} {% endblock %}


text:
#ifndef __CASS_MULTIPLE_REQUEST_HANDLER_HPP_INCLUDED__
#define __CASS_MULTIPLE_REQUEST_HANDLER_HPP_INCLUDED__

#include "handler.hpp"
#include "ref_counted.hpp"
#include "request.hpp"

#include <string>
#include <vector>

namespace cass {

class Connection;
class Response;

class MultipleRequestHandler : public RefCounted<MultipleRequestHandler> {
public:
  typedef std::vector<SharedRefPtr<Response> > ResponseVec;

  MultipleRequestHandler(Connection* connection)
    : connection_(connection)
    , has_errors_or_timeouts_(false)
    , remaining_(0) { }

  virtual ~MultipleRequestHandler() { }

  void execute_query(const std::string& query);

  virtual void on_set(const ResponseVec& responses) = 0;
  virtual void on_error(CassError code, const std::string& message) = 0;
  virtual void on_timeout() = 0;

  Connection* connection() {
    return connection_;
  }

private:
  class InternalHandler : public Handler {
  public:
    InternalHandler(MultipleRequestHandler* parent, const Request* request, int index)
      : Handler(request)
      , parent_(parent)
      , index_(index) { }

    virtual void on_set(ResponseMessage* response);
    virtual void on_error(CassError code, const std::string& message);
    virtual void on_timeout();

  private:
    ScopedRefPtr<MultipleRequestHandler> parent_;
    int index_;
  };

  Connection* connection_;
  bool has_errors_or_timeouts_;
  int remaining_;
  ResponseVec responses_;
};

} // namespace cass

#endif


text:
<?php

  class LocationController extends BaseController
  {
    public function showList()
    {
      $locations = Location::all();
      return View::make('locations.list', compact('locations'));
    }

    public function create()
    {
      return View::make('locations.create');
    }

    public function showMap(Location $location)
    {
      return View::make('locations.map', compact('location'));
    }

    public function handleCreate()
    {
      $location = new Location();
      $location->name = Input::get('name');
      $location->longitude = Input::get('longitude');
      $location->latitude = Input::get('latitude');
      $location->description = Input::get('description');
      $location->save();

      return Redirect::action('LocationController@showList');
    }

    public function edit(Location $location)
    {
      return View::make('locations.edit', compact('location'));
    }

    public function handleEdit()
    {
      $location = Location::findOrFail(Input::get('id'));
      $location->name = Input::get('name');
      $location->longitude = Input::get('longitude');
      $location->latitude = Input::get('latitude');
      $location->description = Input::get('description');
      $location->save();
      return Redirect::action('LocationController@showList');
    }

    public function delete(Location $location)
    {
      return View::make('locations.delete', compact('location'));
    }

    public function handleDelete()
    {
      $id = Input::get('location');
      $location = Location::findOrFail($id);
      $location->delete();

      return Redirect::action('LocationController@showList');
    }
  }


text:
package org.kuali.coeus.common.committee.impl.bo;

import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.common.framework.person.KcPerson;
import org.kuali.coeus.common.framework.person.KcPersonService;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.coeus.sys.framework.util.DateUtils;
import org.kuali.kra.protocol.personnel.ProtocolPersonRolodexBase;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * This class implements the committee membership business object.
 *
 */
public abstract class CommitteeMembershipBase extends CommitteeAssociateBase {

    private static final long serialVersionUID = 3036751811459612428L;

    private final String DATE_FORMAT = "MM/dd/yyyy";

    private Long committeeMembershipId;

    private String personId;

    private Integer rolodexId;

    private String personName;

    private String membershipId;

    private boolean paidMember;

    private Date termStartDate;

    private Date termEndDate;

    private String membershipTypeCode;

    private String comments;

    private String contactNotes;

    private String trainingNotes;

    private List<CommitteeMembershipRole> membershipRoles;

    private List<CommitteeMembershipExpertiseBase> membershipExpertise;

    private CommitteeMembershipType membershipType;

    private ProtocolPersonRolodexBase rolodex;

    private boolean delete;

    private boolean wasInactiveAtLastSave;

    private transient KcPersonService kcPersonService;

    private transient KcPerson kcPerson;

    public CommitteeMembershipBase() {
        setMembershipRoles(new ArrayList<CommitteeMembershipRole>());
        setMembershipExpertise(new ArrayList<CommitteeMembershipExpertiseBase>());
    }

    public Long getCommitteeMembershipId() {
        return committeeMembershipId;
    }

    public void setCommitteeMembershipId(Long committeeMembershipId) {
        this.committeeMembershipId = committeeMembershipId;
    }

    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }

    public Integer getRolodexId() {
        return rolodexId;
    }

    public void setRolodexId(Integer rolodexId) {
        this.rolodexId = rolodexId;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public String getMembershipId() {
        return membershipId;
    }

    public void setMembershipId(String membershipId) {
        this.membershipId = membershipId;
    }

    public boolean getPaidMember() {
        return paidMember;
    }

    public void setPaidMember(boolean paidMemberFlag) {
        this.paidMember = paidMemberFlag;
    }

    public Date getTermStartDate() {
        return termStartDate;
    }

    public String getFormattedTermStartDate() {
        if (termStartDate == null) {
            return null;
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
            return dateFormat.format(termStartDate);
        }
    }

    public void setTermStartDate(Date termStartDate) {
        this.termStartDate = termStartDate;
    }

    public Date getTermEndDate() {
        return termEndDate;
    }

    public String getFormattedTermEndDate() {
        if (termEndDate == null) {
            return null;
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
            return dateFormat.format(termEndDate);
        }
    }

    public void setTermEndDate(Date termEndDate) {
        this.termEndDate = termEndDate;
    }

    public String getMembershipTypeCode() {
        return membershipTypeCode;
    }

    public void setMembershipTypeCode(String membershipTypeCode) {
        this.membershipTypeCode = membershipTypeCode;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getContactNotes() {
        return contactNotes;
    }

    public void setContactNotes(String contactNotes) {
        this.contactNotes = contactNotes;
    }

    public String getTrainingNotes() {
        return trainingNotes;
    }

    public void setTrainingNotes(String trainingNotes) {
        this.trainingNotes = trainingNotes;
    }

    public void setMembershipRoles(List<CommitteeMembershipRole> membershipRoles) {
        this.membershipRoles = membershipRoles;
    }

    public List<CommitteeMembershipRole> getMembershipRoles() {
        return membershipRoles;
    }

    public void setMembershipExpertise(List<CommitteeMembershipExpertiseBase> committeeMembershipExpertise) {
        this.membershipExpertise = committeeMembershipExpertise;
    }

    public List<CommitteeMembershipExpertiseBase> getMembershipExpertise() {
        return membershipExpertise;
    }

    public CommitteeMembershipType getMembershipType() {
        return membershipType;
    }

    public void setMembershipType(CommitteeMembershipType membershipType) {
        this.membershipType = membershipType;
    }

    public KcPerson getPerson() {
        // Each kcpersonservice call will get kimidentityservice call
        // in tag, it may need several calls of this.  just try to improve performance.
        if (kcPerson == null && StringUtils.isNotBlank(personId)) {
            kcPerson = getKcPersonService().getKcPersonByPersonId(personId);
        }
        return kcPerson;
    }

    /**
     * Gets the KC Person Service.
     * @return KC Person Service.
     */
    protected KcPersonService getKcPersonService() {
        if (this.kcPersonService == null) {
            this.kcPersonService = KcServiceLocator.getService(KcPersonService.class);
        }
        return this.kcPersonService;
    }

    public ProtocolPersonRolodexBase getRolodex() {
        return rolodex;
    }

    public void setRolodex(ProtocolPersonRolodexBase rolodex) {
        this.rolodex = rolodex;
    }

    public boolean isDelete() {
        return delete;
    }

    public void setDelete(boolean delete) {
        this.delete = delete;
    }

    public boolean getWasInactiveAtLastSave() {
        return wasInactiveAtLastSave;
    }

    public void setWasInactiveAtLastSave(boolean wasInactiveAtLastSave) {
        this.wasInactiveAtLastSave = wasInactiveAtLastSave;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (obj.getClass() != this.getClass()) {
            return false;
        }
        CommitteeMembershipBase committeeMembership = (CommitteeMembershipBase) obj;
        if (this.getCommitteeIdFk() != null && this.getCommitteeIdFk().equals(committeeMembership.getCommitteeIdFk()) && ((this.getPersonId() != null && this.getPersonId().equals(committeeMembership.getPersonId())) || (this.getRolodexId() != null && this.getRolodexId().equals(committeeMembership.getRolodexId()))) && (this.getTermStartDate() != null && this.getTermStartDate().equals(committeeMembership.getTermStartDate()))) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + (this.getCommitteeIdFk() == null ? 0 : this.getCommitteeIdFk().hashCode());
        result = PRIME * result + (this.getPersonId() == null ? 0 : this.getPersonId().hashCode());
        result = PRIME * result + (this.getRolodexId() == null ? 0 : this.getRolodexId().hashCode());
        result = PRIME * result + (this.getTermStartDate() == null ? 0 : this.getTermStartDate().hashCode());
        return result;
    }

    /**
     * This method determines if the current committee member is active as of the current date.
     * @return true if member is active, false otherwise
     */
    public boolean isActive() {
        Date currentDate = DateUtils.clearTimeFields(new Date(System.currentTimeMillis()));
        return isActive(currentDate);
    }

    /**
     *
     * This method determines if the current committee member is active for the given date
     * @param date
     * @return true if member is active, false otherwise
     */
    public boolean isActive(Date date) {
        boolean isActive = false;
        for (CommitteeMembershipRole role : membershipRoles) {
            if (role.getStartDate() != null && role.getEndDate() != null && !date.before(role.getStartDate()) && !date.after(role.getEndDate())) {
                if (role.getMembershipRoleCode().equals(CommitteeMembershipRole.INACTIVE_ROLE)) {
                    isActive = false;
                    break;
                } else {
                    isActive = true;
                }
            }
        }
        return isActive;
    }

    /**
     * Indicates if the committee memberships are of the same person (i.e. the personId and rolodexId are the same).
     *
     * @param committeeMembership - the committee membership to compare against
     * @return true if both committee membership belong to the same person, false otherwise
     */
    public boolean isSamePerson(CommitteeMembershipBase committeeMembership) {
        boolean isEquals = false;
        if (this.getPersonId() != null && this.getPersonId().equals(committeeMembership.getPersonId()) || this.getRolodexId() != null && this.getRolodexId().equals(committeeMembership.getRolodexId())) {
            isEquals = true;
        }
        return isEquals;
    }

    public void resetPersistenceState() {
        setCommitteeMembershipId(null);
    }

    /**
     *
     * This method returns true if the member's term has ended before the current date, otherwise
     * false. Also returns true if member's term end date is null.
     * @return true if member is term has ended, false otherwise
     */
    public boolean hasTermEnded() {
        boolean retVal = true;
        Date currentDate = DateUtils.clearTimeFields(new Date(System.currentTimeMillis()));
        if ((this.termEndDate != null) && !(this.termEndDate.before(currentDate))) {
            retVal = false;
        }
        return retVal;
    }

    /**
     * This method will return true if personId parameter matches that of the membership's personID, and false otherwise.
     * Also returns false if the personId parameter is null, or if the membership's personId is null.
     * @param personId
     * @return
     */
    public boolean isRepresentingPerson(String personId) {
        boolean retVal = false;
        if (this.personId != null) {
            retVal = this.personId.equals(personId);
        }
        return retVal;
    }

}


text:
/*  Transforms SQL statements
    @(#) $Id: SQLTransformer.java 611 2010-12-12 19:14:56Z gfis $
    2010-06-09: collapse string and comment tags to one with mode attribute
    2010-05-31: many more keywords from SQL99
    2010-05-21: WITH, CALL
    2008-06-30: more keywords
    2008-01-23, Georg Fischer: copied from CSSTransformer

    Still to do:
    - What about the '<>' comparision operator?
*/
/*
 * Copyright 2006 Dr. Georg Fischer <punctum at punctum dot kom>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.teherba.xtrans.proglang;
import  org.teherba.xtrans.proglang.ProgLangTransformer;
import  java.util.regex.Matcher;
import  java.util.regex.Pattern;
import  org.apache.logging.log4j.Logger;
import  org.apache.logging.log4j.LogManager;

/** Transformer for the Structured Query Language (SQL) used in relational databases
 *	like DB2, Oracle, MySQL etc.
 *  See {@link ProgLangTransformer} for a general description of the
 *	the generated elements.
 *  @author Dr. Georg Fischer
 */
public class SQLTransformer extends ProgLangTransformer {
    public final static String CVSID = "@(#) $Id: SQLTransformer.java 611 2010-12-12 19:14:56Z gfis $";

    /** log4j logger (category) */
    private static Logger log = LogManager.getLogger(SQLTransformer.class.getName());

    /** No-args Constructor.
     *  This should be as lightweight as possible.
     */
    public SQLTransformer() {
        super();
        setFormatCodes("sql");
        setDescription("Structured Query Language");
        setFileExtensions("sql,ddl");
    } // Constructor

	/** Initializes the (quasi-constant) global structures and variables
	 *  common to generator and serializer.
	 *  This method is called by the {@link org.teherba.xtrans.XtransFactory} once for the
	 *  selected generator and serializer.
	 */
	public void initialize() {
		super.initialize();
        lineEndComment  = "--";
        doubleInnerApos = true;
        caseIndependant = true;
        bothStringTypes = true; // for mySQL (?)
		escapeCode      = LANG_PL1;
	} // initialize

    /** Prepares the class.
     *  Does all heavy-weight initialization.
     */
    protected void prepareGenerator() {
        super.prepareGenerator();
        identifierPattern  = Pattern.compile
                ("[\\w\\_]+");
        numberPattern      = Pattern.compile
                ("\\d+");
        // reserved in SQL99, from http://www.sql.org/sql-database/postgresql/manual/sql-keywords-appendix.html
        keywords = new String[] { "()"
		, "absolute"
		, "action"
		, "add"
		, "admin"
		, "after"
		, "aggregate"
		, "alias"
		, "all"
		, "allocate"
		, "alter"
		, "and"
		, "any"
		, "are"
		, "array"
		, "as"
		, "asc"
		, "assertion"
		, "at"
		, "authorization"
		, "before"
		, "begin"
		, "binary"
		, "bit"
		, "blob"
		, "boolean"
		, "both"
		, "breadth"
		, "by"
		, "call"
		, "cascade"
		, "cascaded"
		, "case"
		, "cast"
		, "catalog"
		, "char"
		, "character"
		, "check"
		, "class"
		, "clob"
		, "close"
		, "collate"
		, "collation"
		, "column"
		, "commit"
		, "completion"
		, "connect"
		, "connection"
		, "constraint"
		, "constraints"
		, "constructor"
		, "continue"
		, "corresponding"
		, "create"
		, "cross"
		, "cube"
		, "current"
		, "current_date"
		, "current_path"
		, "current_role"
		, "current_time"
		, "current_timestamp"
		, "current_user"
		, "cursor"
		, "cycle"
		, "data"
		, "date"
		, "day"
		, "deallocate"
		, "dec"
		, "decimal"
		, "declare"
		, "default"
		, "deferrable"
		, "deferred"
		, "delete"
		, "depth"
		, "deref"
		, "desc"
		, "describe"
		, "descriptor"
		, "destroy"
		, "destructor"
		, "deterministic"
		, "diagnostics"
		, "dictionary"
		, "disconnect"
		, "distinct"
		, "domain"
		, "double"
		, "drop"
		, "dynamic"
		, "each"
		, "else"
		, "end"
		, "end-exec"
		, "equals"
		, "escape"
		, "every"
		, "except"
		, "exception"
		, "exec"
		, "execute"
		, "exists"
		, "external"
		, "false"
		, "fetch"
		, "first"
		, "float"
		, "for"
		, "foreign"
		, "found"
		, "free"
		, "from"
		, "full"
		, "function"
		, "general"
		, "get"
		, "global"
		, "go"
		, "goto"
		, "grant"
		, "group"
		, "grouping"
		, "having"
		, "host"
		, "hour"
		, "identity"
		, "ignore"
		, "immediate"
		, "in"
		, "indicator"
		, "initialize"
		, "initially"
		, "inner"
		, "inout"
		, "input"
		, "insert"
		, "int"
		, "integer"
		, "intersect"
		, "interval"
		, "into"
		, "is"
		, "isolation"
		, "iterate"
		, "join"
		, "key"
		, "language"
		, "large"
		, "last"
		, "lateral"
		, "leading"
		, "left"
		, "less"
		, "level"
		, "like"
		, "limit"
		, "local"
		, "localtime"
		, "localtimestamp"
		, "locator"
		, "map"
		, "match"
		, "minute"
		, "modifies"
		, "modify"
		, "module"
		, "month"
		, "names"
		, "national"
		, "natural"
		, "nchar"
		, "nclob"
		, "new"
		, "next"
		, "no"
		, "none"
		, "not"
		, "null"
		, "numeric"
		, "object"
		, "of"
		, "off"
		, "old"
		, "on"
		, "only"
		, "open"
		, "operation"
		, "option"
		, "or"
		, "order"
		, "ordinality"
		, "out"
		, "outer"
		, "output"
		, "pad"
		, "parameter"
		, "parameters"
		, "partial"
		, "path"
		, "postfix"
		, "precision"
		, "prefix"
		, "preorder"
		, "prepare"
		, "preserve"
		, "primary"
		, "prior"
		, "privileges"
		, "procedure"
		, "public"
		, "read"
		, "reads"
		, "real"
		, "recursive"
		, "ref"
		, "references"
		, "referencing"
		, "relative"
		, "restrict"
		, "result"
		, "return"
		, "returns"
		, "revoke"
		, "right"
		, "role"
		, "rollback"
		, "rollup"
		, "routine"
		, "row"
		, "rows"
		, "savepoint"
		, "schema"
		, "scope"
		, "scroll"
		, "search"
		, "second"
		, "section"
		, "select"
		, "sequence"
		, "session"
		, "session_user"
		, "set"
		, "sets"
		, "size"
		, "smallint"
		, "some"
		, "space"
		, "specific"
		, "specifictype"
		, "sql"
		, "sqlexception"
		, "sqlstate"
		, "sqlwarning"
		, "start"
		, "state"
		, "statement"
		, "static"
		, "structure"
		, "system_user"
		, "table"
		, "temporary"
		, "terminate"
		, "than"
		, "then"
		, "time"
		, "timestamp"
		, "timezone_hour"
		, "timezone_minute"
		, "to"
		, "trailing"
		, "transaction"
		, "translation"
		, "treat"
		, "trigger"
		, "true"
		, "under"
		, "union"
		, "unique"
		, "unknown"
		, "unnest"
		, "update"
		, "usage"
		, "user"
		, "using"
		, "value"
		, "values"
		, "varchar"
		, "variable"
		, "varying"
		, "view"
		, "when"
		, "whenever"
		, "where"
		, "with"
		, "without"
		, "work"
		, "write"
		, "year"
		, "zone"

        , "longvarbinary"
        , "longvarchar"
        , "numeric"
        , "varbinary"
        , "varchar2"
        };
        storeWords();
    } // prepareGenerator

    //////////////////////
    // SAX event generator
    //////////////////////

    /** Matches all punctuation and operator elements apart from parentheses, ";", "," and ".".
     *  This special implementation cares for SQL's line end comment ("--").
     *  @param line input line containing the start of the operator at position linePos
     *  @param linePos position where the operator starts
     *  @return position behind the element, - 1
     */
    protected int matchOperator(String line, int linePos, int trap) {
        int pos2 = linePos + 1; // position behind the element just recognized
        Matcher matcher = operatorPattern.matcher(line.substring(linePos));
        if (matcher.lookingAt()) {
            pos2 = linePos + matcher.end();
            String oper = line.substring(linePos, pos2);
            if (! oper.startsWith(lineEndComment)) {
            	fireEmptyElement(OPERATOR_TAG, spaceAndValAttr(oper));
            } else { // line end comment starts here
	            int pos1 = linePos + lineEndComment.length();
		        fireStartElement(COMMENT_TAG, spaceAndModeAttr(LINE_END_MODE));
        	    fireCharacters(replaceNoSource(line.substring(pos1)));
            	fireEndElement(COMMENT_TAG);
            	pos2 = trap; // skip to end of line
            } // LEC
        } else {
            log.error("unknown operator in line " + (lineNo + 1)
                    + " at column " + (linePos + 1) + ": " + line.substring(linePos));
        }
        return pos2 - 1; // 1 before the end
    } // matchOperator

    /////////////////////////
    // SAX content handler //
    /////////////////////////

} // class SQLTransformer


text:
var NodeCache = require('node-cache');
var myCache = new NodeCache();

var cache = {
  /** Gets key from cache if exists, else sets the cache and returns data.
  * @param {string} cacheKey - Key to get or set.
  * @param {integer} timeout - Timeout (in seconds) for cache to release.
  * @param {Function} fn - Function to get data if key does not exist.
  * @param {Function} callback - Callback function to send back data or value.
  */
  getOrSet: function(cacheKey, timeout, fn, callback) {
    myCache.get(cacheKey, function(err, value) {
      if (!err) {
        if (value == undefined) {
          fn(function(data) {
            if (!(data.statusCode))
              myCache.set(cacheKey, data, timeout);
            callback(data);
          });
        } else {
          callback(value);
        }
      }
    });
  },

  get: function(cacheKey, callback) {
    myCache.get(cacheKey, function(err, value) {
      if (!err) {
        if (value == undefined) {
          callback(value);
        } else {
          callback(value);
        }
      }
    });
  },

  set: function(cacheKey, timeout, fn, callback) {
    fn(function(data) {
      myCache.set(cacheKey, data, timeout, function(err, success) {
        if (!err && success) {
          callback(data);
        }
        callback();
      });
    });
  }
}

module.exports = cache;


text:
layout: page
title: Solemn Gold Industries Party
date: 2016-05-24
author: Gabriel Santiago
tags: weekly links, java
status: published
summary: Praesent feugiat at tortor vel.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 08/11/2017
  endDate: 08/13/2017
  ctyhocn: BMIWEHX
  groupCode: SGIP
published: true
---
Nulla facilisi. Maecenas leo mauris, euismod nec tortor non, bibendum efficitur odio. Nullam porttitor pellentesque dignissim. Duis aliquam augue at mattis congue. Vestibulum lobortis dignissim nunc, sed tristique orci congue ac. Sed quis justo tortor. Maecenas id ultrices massa. In hac habitasse platea dictumst. Sed pellentesque feugiat convallis.

* Donec vitae nibh hendrerit, sagittis magna vitae, tempus diam.

Etiam facilisis congue nunc, id hendrerit nibh suscipit eget. Suspendisse tempus vulputate ultricies. Nunc aliquam tempus neque eu malesuada. Cras ut tellus in justo sodales pretium tincidunt fringilla dolor. Phasellus vel orci eu massa molestie egestas et in metus. Curabitur vestibulum luctus massa vel gravida. Nam gravida in urna sed consequat. Sed pulvinar fringilla enim ultricies tincidunt. Sed sed pretium felis, quis consequat massa. Nullam a placerat augue. Nulla cursus ex velit, vitae placerat neque mattis vitae. Aliquam erat volutpat. Sed dictum magna nulla, in tempor dui euismod a.


text:
import includes from "lodash/includes";
import isUndefined from "lodash/isUndefined";
import constant from "lodash/constant";
import filter from "lodash/filter";
import find from "lodash/find";
import overEvery from "lodash/overEvery";

export interface Node {
  id: string;
  order: number;
  name?: string | typeof undefined;
  description?: string | typeof undefined;
  tags?: string[] | typeof undefined;
  yPosition: number;
}

export interface Edge {
  id: string;
  source: string;
  target: string;
  value: number;
}

export class Graph {
  nodes: Node[];
  edges: Edge[];
  constructor(nodes: Node[], edges: Edge[]) {
    this.nodes = nodes;
    this.edges = edges;
  }

  getNode(nodeId: string): ?Node {
    return find(this.nodes, { id: nodeId });
  }

  getParents(nodeId: string): Node[] {
    return filter(
      this.nodes,
      n => filter(this.edges, { source: n.id, target: nodeId }).length > 0
    );
  }

  getChildren(nodeId: string): Node[] {
    return filter(
      this.nodes,
      n => filter(this.edges, { source: nodeId, target: n.id }).length > 0
    );
  }

  getEdges({ from, to }: $Shape<{ from: string[], to: string[] }>): Edge[] {
    const filterSource = isUndefined(from)
      ? constant(true)
      : edge => includes(from, edge.source);
    const filterTarget = isUndefined(to)
      ? constant(true)
      : edge => includes(to, edge.target);
    return filter(this.edges, overEvery([filterSource, filterTarget]));
  }

  changeNodesOrder(orderedIds: Node[]): void {
    orderedIds.forEach(el => {
      const node = find(this.nodes, { id: el.id });
      if (node) (node.order = el.order), (node.yPosition = el.yPosition);
    });
  }
}


text:
	{$formParams.label}:
	{if $formParams.listType == 'checkbox'}
		{foreach $formParams.listItems as $i}

<input type="checkbox" {if current($i) == $formParams.value} checked="checked"{/if} {$formParams.attr} value="{current($i)}" name="{$formParams.name}[]" id="checkbox_{$formParams.name}_{current($i)}" /> {next($i)}
		{/foreach}
	{elseif $formParams.listType == 'radiobox'}
		{if !$formParams.required}

<input type="radio" {$formParams.attr} value="0" name="{$formParams.name}" id="radio_{$formParams.name}_0" /> {$formParams.placeholder}
		{/if}
		{foreach $formParams.listItems as $i}

<input type="radio" {if current($i) == $formParams.value} checked="checked"{/if} {$formParams.attr} value="{current($i)}" name="{$formParams.name}" id="radio_{$formParams.name}_{current($i)}" /> {next($i)}
		{/foreach}
	{else}
		<select {if $formParams.multiple} multiple {/if}{$formParams.attr} name="{$formParams.name}{if $formParams.multiple}[]{/if}" id="sel_{$formParams.name}">
			{if !$formParams.required}
				<option value="0">{$formParams.placeholder}</option>
			{/if}
			{foreach $formParams.listItems as $i}
				<option value="{current($i)}" {if current($i) == $formParams.value} selected="selected"{/if} >{next($i)}</option>
			{/foreach}
		</select>
	{/if}


text:
package main

import (
	"golang.org/x/net/websocket"
	"log"
	"net/http"
)

var (
	clients   = make(map[*websocket.Conn]bool)
	broadcast = make(chan string)
)

func main() {

	// Setup new websocket connections
	http.Handle("/", websocket.Handler(newWebsocket))

	// Broadcast messages
	go broadcastMessage()

	// Start server
	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func newWebsocket(ws *websocket.Conn) {
	// Close connection when function returns
	defer ws.Close()

	// Add to pool of clients
	clients[ws] = true

	// Setup receiver
	for {
		var msg string
		if err := websocket.Message.Receive(ws, &msg); err != nil {
			log.Printf("Cant receive error: %v\n", err)
			delete(clients, ws)
			break
		}
		log.Println("Received:", msg)
		broadcast <- msg
	} // end while

}

func broadcastMessage() {
	for {
		// Get message from broadcast channel
		msg := <-broadcast
		// Send to connected clients
		for client := range clients {
			if err := websocket.Message.Send(client, msg); err != nil {
				log.Printf("Cant Send error: %v\n", err)
				client.Close()
				delete(clients, client)
			}
		}
	} // end while
}


text:
package com.github.ruediste.salta.standard.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import com.github.ruediste.salta.core.CompiledSupplier;
import com.github.ruediste.salta.core.CoreDependencyKey;
import com.github.ruediste.salta.core.CoreInjector;
import com.github.ruediste.salta.core.SaltaException;
import com.github.ruediste.salta.standard.InjectionPoint;
import com.github.ruediste.salta.standard.StandardInjector;
import com.github.ruediste.salta.standard.config.StandardInjectorConfiguration;
import com.google.common.reflect.TypeToken;

/**
 * Base class for static members injectors.
 */
public abstract class StaticMembersInjectorBase {

    protected enum InjectionInstruction {
        NO_INJECT, INJECT, INJECT_OPTIONAL
    }

    /**
     * Determine if a field should be injected. Called for static fields only;
     */
    protected abstract InjectionInstruction shouldInject(Field field);

    /**
     * Determine if a method should be injected. Called for static methods only;
     */
    protected abstract InjectionInstruction shouldInject(Method method);

    /**
     * Injects all
     * {@link StandardInjectorConfiguration#requestedStaticInjections}
     */
    public void injectStaticMembers(StandardInjectorConfiguration config, StandardInjector injector) {
        Set<Class<?>> injectedClasses = new HashSet<>();
        for (Class<?> cls : config.requestedStaticInjections) {
            performStaticInjections(cls, injector, injectedClasses);
        }
    }

    private void performStaticInjections(Class<?> cls, StandardInjector injector, Set<Class<?>> injectedClasses) {
        if (cls == null)
            return;
        if (injectedClasses.add(cls)) {
            performStaticInjections(cls.getSuperclass(), injector, injectedClasses);

            performStaticInjections(injector.getCoreInjector(), cls);
        }
    }

    private void performStaticInjections(CoreInjector injector, Class<?> cls) {
        // inject fields
        for (Field f : cls.getDeclaredFields()) {
            if (!Modifier.isStatic(f.getModifiers()))
                continue;
            InjectionInstruction injectionInstruction = shouldInject(f);
            if (injectionInstruction == InjectionInstruction.NO_INJECT)
                continue;
            InjectionPoint<?> d = new InjectionPoint<>(TypeToken.of(f.getGenericType()), f, f, null);
            f.setAccessible(true);
            Optional<CompiledSupplier> instance = injector.tryGetCompiledRecipe(d);
            if (instance.isPresent() || injectionInstruction != InjectionInstruction.INJECT_OPTIONAL)
                try {
                    f.set(null, instance.get().getNoThrow());
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new SaltaException("Error while setting static " + f, e);
                }
        }

        // inject methods
        methodLoop: for (Method m : cls.getDeclaredMethods()) {
            if (!Modifier.isStatic(m.getModifiers()))
                continue;
            InjectionInstruction injectionInstruction = shouldInject(m);
            if (injectionInstruction == InjectionInstruction.NO_INJECT)
                continue;
            ArrayList<Object> args = new ArrayList<>();
            Parameter[] parameters = m.getParameters();
            for (int i = 0; i < parameters.length; i++) {
                Parameter p = parameters[i];
                CoreDependencyKey<?> d = new InjectionPoint<>(TypeToken.of(p.getParameterizedType()), m, p, i);
                if (injectionInstruction == InjectionInstruction.INJECT_OPTIONAL) {
                    Optional<CompiledSupplier> tmp = injector.tryGetCompiledRecipe(d);
                    if (!tmp.isPresent())
                        continue methodLoop;
                    args.add(tmp.get().getNoThrow());
                } else
                    args.add(injector.getInstance(d));
            }

            m.setAccessible(true);
            try {
                m.invoke(null, args.toArray());
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new SaltaException("Error while setting static " + m, e);
            } catch (InvocationTargetException e) {
                throw new SaltaException("Error while setting static " + m, e.getCause());
            }

        }
    }

}


text:
package com.ibm.dcm;

/**
 * This simple class adds forXPath to DCM, allowing the body of the loop
 * to be executed multiple times based on the XML and XPath, and the optional
 * xpathtype="...".
 *
 * <forxpath (inprop="..." | infile="...") xpath="...">
 *   <sequential>
 *     ... tasks to execute ...
 *   </sequential>
 * </forxpath>
 *
 * Optional arguments:
 *   xpathtype = (text|node)
 *   debug = true
 *   propname = name of property within loop, defaults to "forxpath"
 *
 * Note3:
 *   1. inprop and infile are mutually exclusive and one or the other is required.
 *   2. The <sequential> task is required.
 *   3. xpathtype=text takes the string() of the current node while
 *      xpathtype=node serializes the current node.
 *   4. propname is the macrodef attribute to use within the <sequential>.
 *
 * Examples:
 *
 *   Given ${in} is hello world<c><d>live to work</d></c>
 *
 *   <forxpath inprop="in" xpath="/a/*">
 *     <sequential>
 *       <echo>@{forxpath}</echo>
 *     </sequential>
 *   </forxpath>
 *
 *   prints:
 *
 *     [echo] hello world          (from )
 *     [echo] live to work         (from <c>)
 *
 *   <forxpath inprop="in" xpath="/a/*" xpathtype="node" propname="testme">
 *     <sequential>
 *       <echo>@{testme}</echo>
 *     </sequential>
 *   </forxpath>
 *
 *   prints:
 *
 *     [echo] hello world
 *     [echo] <c><d>live to work</d></c>
 *
 */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.MacroDef;
import org.apache.tools.ant.taskdefs.MacroInstance;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class taskForXpath extends Task {

  private String inProp = "";
  private String inFile = "";
  private String xpath = "";
  private String xpathType = "text";
  private String propname = "forxpath";
  private boolean debug = false;
  private MacroDef baseMacroDef;

  public taskForXpath() {

    // Create the macrodef template that will form the basis for this task.
    baseMacroDef = new MacroDef();
    baseMacroDef.setProject(getProject());

  }

  /**
   * The Task base class requires that the user provide a <sequential> object.
   * This is where all the child tasks are recorded.
   *
   * @return Object
   */
  public Object createSequential() {
    return baseMacroDef.createSequential();
  }

  public void setInprop(String propname) {
    inProp = propname;
  }

  public void setInfile(String filename) {
    inFile = filename;
  }

  public void setXpath(String text) {
    xpath = text;
  }

  public void setXpathtype(String text) {
    xpathType = text;
  }

  public void setPropname(String text) {
    propname = text;
  }

  public void setDebug(String text) {
    String lc = text.toLowerCase();
    if (lc.equals("true") || lc.equals("on") ||
        lc.equals("enable") || lc.equals("enabled") ||
        lc.equals("1")) {
      debug = true;
    }
  }

  public void execute() throws BuildException {

    // Define the desired property name for the loop variable (e.g. forxpath)
    MacroDef.Attribute attrForxpath = new MacroDef.Attribute();
    attrForxpath.setName(propname);
    baseMacroDef.addConfiguredAttribute(attrForxpath);

    Project proj = getProject();
    try {

      // Do basic validation of the inputs.
      if ((inProp+inFile).length() == 0 || (inProp != "" && inFile != ""))
        throw new BuildException("The <forxpath> task requires XML either from an ANT property (inprop) or a file/url (infile), which are mutually exclusive.");
      if (xpath.length() == 0)
        throw new BuildException("The <forxpath> task requires an xpath=\"...\" attribute.");
      if (!(xpathType.equals("text") || xpathType.equals("node"))) {
        throw new BuildException("xpathtype=\"(text|node)\" where 'text' is the string() value of the node returned by the xpath and 'node' is the serialized form of the node.");
      }

      // Pull in the XML.
      String xml = "";
      if (inProp != "") {

        xml = proj.getProperty(inProp);

      } else {

        File file = new File (inFile);
        byte[] buffer = new byte[(int)file.length()];
        BufferedInputStream input = new BufferedInputStream (new FileInputStream (inFile));
        try {
            input.read (buffer);
        }
        finally {
            input.close();
        }
        xml = new String(buffer);

      }

      if (debug) {
        System.out.println("### xml=" + xml);
      }

      // Parse the XML and run the xpath against it.
      Node doc = SomaUtils.getDOM(xml);
      NodeList nl = SomaUtils.nodelistXpathFor(doc, xpath);

      // For each node returned by the xpath, create a <sequential> element,
      // populate it with the children of this <forXPath> element, then execute
      // it.
      for (int i = 0; i < nl.getLength(); i += 1) {
        String forxpath = nl.item(i).getTextContent();
        if (xpathType.equals("node")) {
          // We'll need to pass this XML to the tasks within the loop as text.
          forxpath = SomaUtils.xmlNoHeader(SomaUtils.serializeXML(nl.item(i)));
        }
        if (debug) {
          System.out.println("### " + i + " : " + xpathType + " : " + forxpath);
        }

        try {

          // Create an instance of the base <sequential> element (using the
          // macroDef mechanism) and run it, setting to loop property to the
          // content of the current node.
          MacroInstance runme = new MacroInstance();
          runme.setProject(getProject());
          runme.setOwningTarget(getOwningTarget());
          runme.setMacroDef(baseMacroDef);
          runme.setDynamicAttribute(propname, forxpath);
          runme.execute();

        } catch (BuildException e) {
          throw e;
        }
      }
    } catch (Exception e) {
      // Checked exceptions were some language designer's irritating idea that
      // didn't work out, but now we're stuck with them.
      throw new BuildException (e);
    }
  }
}


text:
package goryachev.swing;

public interface CSelectionListener
{
	public void selectionChanged();
}


text:
package uk.dangrew.nuts.persistence.fooditems;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

import java.net.URISyntaxException;

import org.junit.Test;

import uk.dangrew.jupa.file.protocol.JarJsonPersistingProtocol;
import uk.dangrew.jupa.file.protocol.WorkspaceJsonPersistingProtocol;
import uk.dangrew.nuts.persistence.goal.GoalParseModelTest;
import uk.dangrew.nuts.store.Database;

public class FoodSessionsTest {

   @Test public void shouldAcceptMissingOptionalData() throws URISyntaxException{
      Database database = new Database();
      FoodSessions sessions = new FoodSessions(
               database,
               mock( JarJsonPersistingProtocol.class ),
               new WorkspaceJsonPersistingProtocol( "food-items.txt", getClass() ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class )
      );
      sessions.databaseIo().read();

      assertThat( database.foodItems().objectList(), is( not( empty() ) ) );
   }//End Method

   @Test public void shouldReadSingleGoalData() throws URISyntaxException{
      Database database = new Database();
      FoodSessions sessions = new FoodSessions(
               database,
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               new WorkspaceJsonPersistingProtocol( "goal-no-id-name.txt", getClass() ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class ),
               mock( JarJsonPersistingProtocol.class )
      );
      sessions.databaseIo().read();
      assertThat( database.calorieGoals().objectList(), is( not( empty() ) ) );
      assertThat( database.templates().defaultGoal().properties().nameProperty().get(), is( GoalParseModelTest.SINGLETON_GOAL_DEFAULT_NAME ) );
   }//End Method

   @Test public void untested() {
      System.out.println( "WARNING: UNTESTED - " + getClass().getName() );
   }//End Method

}//End Class


text:
struct LexingIterator {
  const char* begin;
  const char* itr;
  const char* end;

  const char* last_line_begin;
  unsigned int line_count;

  const char* token_begin;
  unsigned int token_line;
  unsigned int token_column;
};

class Token {
public:
  Token();
  Token(LexingIterator lex_itr, int token_id);

  u64 index;
  unsigned int length;
  int id;
  unsigned int line_count;
  unsigned int column_count;
};

class Lexer {
public:
  Lexer();
  ~Lexer();

  void addRule(const Regexpr regexpr, int token_id);
  void build();

  void setStream(const char* input_data_begin, const char* input_data_end);
  const char* begin();

  Token nextToken();
  void rewind();
private:
  void rewindBackTo(LexingIterator& rewind_data, std::vector<unsigned int>& state_set);

  LexingIterator lexing_data;

  enum class LexingState : u8 {
    INITIALIZATION_PHASE,
    BUILD_PHASE,
    QUERY_PHASE
  } status;

  // Lexer internally constructs NFA during build phase
  // which gets replaced with a DFA for lexing phase.
  union {
//  DFA<unsigned int, int, 1 << 7>* dfa;
    NFA<unsigned int, int, 1 << 7>* nfa;
  };
};

#endif // LEXER_H_


text:
This app connects to an Aurora Server instance ([see this project](https://github.com/barrymcandrews/aurora-server)) to control the color or pattern of an RGB LED strip. You can choose from a pool of existing colors and patterns or use the editor to make your own.

## Getting Started

### Prerequisities

This project uses Carthage as a dependency manager. If you do not have Carthage already installed you can do so using macOS Homebrew:

```
$ brew update
$ brew install carthage
```

### Installation

To use and contribute to this project clone it directly from this repository:

```
#HTTP
$ git clone https://github.com/barrymcandrews/aurora-ios.git
#SSH
$ git clone git@github.com:barrymcandrews/aurora-ios.git
```
#### Dependencies

Before building the project you must download all dependencies with Carthage. In your terminal, navigate to the root of the project directory and run the following command:

```
$ carthage update --platform iOS
```

Unfortunately, in order to get the animations from the [Hero](https://github.com/lkzhao/Hero/) library to work correctly, I was forced to edit the source code and publicly expose one method. Hopefully, they'll fix this in the future, but in the meantime you'll have to make this change to get the code to work.

On line 295 of Hero.swift change `private extension Hero` to `public extension Hero`


text:
/**
 * El main que genera la instancia de la ventana
 */
package bankmanager;

public class BankManager {

    public static void main (String [] args)
	{

          Principal  frame1 = new Principal();
          frame1.setVisible(true);

	}

}


text:
package com.orange.util.modifier.ease;

/**
 * (c) OrangeGame 2012
 *
 *
 *
 * @author OrangeGame <OGEngine@orangegame.cn>
 */
public class EaseBounceInOut implements IEaseFunction {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private static EaseBounceInOut INSTANCE;

	// ===========================================================
	// Constructors
	// ===========================================================

	private EaseBounceInOut() {

	}

	public static EaseBounceInOut getInstance() {
		if(INSTANCE == null) {
			INSTANCE = new EaseBounceInOut();
		}
		return INSTANCE;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public float getPercentage(final float pSecondsElapsed, final float pDuration) {
		final float percentage = pSecondsElapsed / pDuration;

		if(percentage < 0.5f) {
			return 0.5f * EaseBounceIn.getValue(2 * percentage);
		} else {
			return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1);
		}
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
<?php defined('_LINDEX') or die('STOP in file ' . __FILE__);

function getContent()
{
    $DBhostname = (isset($_POST['DBhostname'])) ? trim($_POST['DBhostname']) : '';
    $DBuserName = (isset($_POST['DBuserName'])) ? trim($_POST['DBuserName']) : '';
    $DBpassword = (isset($_POST['DBpassword'])) ? trim($_POST['DBpassword']) : '';
    $DBname = (isset($_POST['DBname'])) ? trim($_POST['DBname']) : '';
    $DBPrefix = (isset($_POST['DBPrefix'])) ? trim($_POST['DBPrefix']) : 'jos_';

    $sitename = (isset($_POST['sitename'])) ? trim($_POST['sitename']) : '';
    $siteUrl = (isset($_POST['siteUrl'])) ? trim($_POST['siteUrl']) : preg_replace('#\:[\d]*[\s]*$#i', '',_LPATH_SITE);
    $siteport = (isset($_POST['siteport'])) ? trim($_POST['siteport']) : trim(_LPATH_SITE_PORT, ':');
    $absolutePath = (isset($_POST['absolutePath'])) ? trim($_POST['absolutePath']) : _LPATH_ROOT;
    $absolutePath = str_replace('\\', '/', $absolutePath);

    $adminLogin = (isset($_POST['adminLogin'])) ? trim($_POST['adminLogin']) : 'admin';
    $adminPassword = (isset($_POST['adminPassword'])) ? trim($_POST['adminPassword']) : makePassword();
    $adminEmail = (isset($_POST['adminEmail'])) ? trim($_POST['adminEmail']) : '';

    $DBSample = (isset($_POST['DBSample'])) ? trim($_POST['DBSample']) : 1;
    $DBSample = ($DBSample === 0 or $DBSample === '0') ? 0 : 1;

    $info['left'] = getLeft(1, 1, 1, 0, 0);
    $info['title'] = 'Настройка Сайта';

    $info['button'] = getButton(5, 'Далее', 'form');
    $info['content']
        = '
    <form action="index.php?page=5" method="post" name="form" id="form">
	    <input type="hidden" name="DBhostname" value="' . $DBhostname . '" />
	    <input type="hidden" name="DBuserName" value="' . $DBuserName . '"/>
	    <input type="hidden" name="DBpassword" value="' . $DBpassword . '"/>
	    <input type="hidden" name="DBname" value="' . $DBname . '"/>
	    <input type="hidden" name="DBPrefix" value="' . $DBPrefix . '"/>
        <input type="hidden" name="DBSample" value="' . $DBSample . '" />

			Название сайта
			<input class="inputbox" type="text" name="sitename" size="40" value="'.$sitename.'"/>
			Например: Мой новый сайт!

            URL сайта
			<input class="inputbox" type="text" name="siteUrl" value="' . $siteUrl . '" size="40"/>
			Это значение как правило не требует вмешательства пользователя

			Абсолютный путь
			<input class="inputbox" type="text" name="absolutePath" value="' . $absolutePath . '" size="40"/>
			Это значение как правило не требует вмешательства пользователя

			Порт HTTP
			<input class="inputbox" type="text" name="siteport" value="' . $siteport . '" size="4"/>
			Если при подключении Вам необходимо указывать нестандартный порт HTTP, то укажите только цифры. Если Вам это неизвестно, то оставьте поле пустым

			Ваш логин
			<input class="inputbox" type="text" name="adminLogin" value="' . $adminLogin . '" size="40"/>
			Используется как логин для авторизации главного Администратора сайта. Длина логина должна быть больше 2 и не больше 30 символов

			Пароль Администратора
			<input class="inputbox" type="text" name="adminPassword" value="' . $adminPassword . '" size="40"/>
			Пароль должен содержать минимум 8 символов и должен содержать минимум два символа отличных от цифр

		    Ваш E-mail
			<input class="inputbox" type="text" name="adminEmail" value="' . $adminEmail . '" size="40"/>
			Используется как адрес главного Администратора сайта

    </form>
    ';
    return $info;
}