text:
from __future__ import with_statement
from fnmatch import fnmatchcase

import os
import re
import stat
import time
import glob

from .config import (Configuration, IntegerEntry, NewlineEntry, StringEntry,
                     TimeEntry)

class SSHClientException(RuntimeError):
    pass

class _ClientConfiguration(Configuration):

    def __init__(self, host, alias, port, timeout, newline, prompt, term_type,
                 width, height, path_separator, encoding):
        super(_ClientConfiguration, self).__init__(
            index=IntegerEntry(None),
            host=StringEntry(host),
            alias=StringEntry(alias),
            port=IntegerEntry(port),
            timeout=TimeEntry(timeout),
            newline=NewlineEntry(newline),
            prompt=StringEntry(prompt),
            term_type=StringEntry(term_type),
            width=IntegerEntry(width),
            height=IntegerEntry(height),
            path_separator=StringEntry(path_separator),
            encoding=StringEntry(encoding)
        )

class AbstractSSHClient(object):
    """Base class for the SSH client implementation.

    This class defines the public API. Subclasses (:py:class:`pythonclient.
    PythonSSHClient` and :py:class:`javaclient.JavaSSHClient`) provide the
    language specific concrete implementations.
    """
    def __init__(self, host, alias=None, port=22, timeout=3, newline='LF',
                 prompt=None, term_type='vt100', width=80, height=24,
                 path_separator='/', encoding='utf8'):
        self.config = _ClientConfiguration(host, alias, port, timeout, newline,
                                           prompt, term_type, width, height,
                                           path_separator, encoding)
        self._sftp_client = None
        self._shell = None
        self._started_commands = []
        self.client = self._get_client()

    def _get_client(self):
      raise NotImplementedError('This should be implemented in the subclass.')

    @staticmethod
    def enable_logging(path):
        """Enables logging of SSH events to a file.

        :param str path: Path to the file the log is written to.

        :returns: `True`, if logging was successfully enabled. False otherwise.
        """
        raise NotImplementedError

    @property
    def sftp_client(self):
        """Gets the SSH client for the connection.

        :returns: An object of the class that inherits from
            :py:class:`AbstractSFTPClient`.
        """
        if not self._sftp_client:
            self._sftp_client = self._create_sftp_client()
        return self._sftp_client

    @property
    def shell(self):
        """Gets the shell for the connection.

        :returns: An object of the class that inherits from
            :py:class:`AbstractShell`.
        """
        if not self._shell:
            self._shell = self._create_shell()
        return self._shell

    def _create_sftp_client(self):
        raise NotImplementedError

    def _create_shell(self):
        raise NotImplementedError

    def close(self):
        """Closes the connection."""
        self.client.close()

    def login(self, username, password, delay=None):
        """Logs into the remote host using password authentication.

        This method reads the output from the remote host after logging in,
        thus clearing the output. If prompt is set, everything until the prompt
        is read (using :py:meth:`read_until_prompt` internally).
        Otherwise everything on the output is read with the specified `delay`
        (using :py:meth:`read` internally).

        :param str username: Username to log in with.

        :param str password: Password for the `username`.

        :param str delay: The `delay` passed to :py:meth:`read` for reading
            the output after logging in. The delay is only effective if
            the prompt is not set.

        :raises SSHClientException: If logging in failed.

        :returns: The read output from the server.
        """
        username = self._encode(username)
        password = self._encode(password)
        try:
            self._login(username, password)
        except SSHClientException:
            raise SSHClientException("Authentication failed for user '%s'."
                                     % username)
        return self._read_login_output(delay)

    def _encode(self, text):
        if isinstance(text, str):
            return text
        if not isinstance(text, basestring):
            text = unicode(text)
        return text.encode(self.config.encoding)

    def _login(self, username, password):
        raise NotImplementedError

    def _read_login_output(self, delay):
        if self.config.prompt:
            return self.read_until_prompt()
        return self.read(delay)

    def login_with_public_key(self, username, keyfile, password, delay=None):
        """Logs into the remote host using the public key authentication.

        This method reads the output from the remote host after logging in,
        thus clearing the output. If prompt is set, everything until the prompt
        is read (using :py:meth:`read_until_prompt` internally).
        Otherwise everything on the output is read with the specified `delay`
        (using :py:meth:`read` internally).

        :param str username: Username to log in with.

        :param str keyfile: Path to the valid OpenSSH private key file.

        :param str password: Password (if needed) for unlocking the `keyfile`.

        :param str delay: The `delay` passed to :py:meth:`read` for reading
            the output after logging in. The delay is only effective if
            the prompt is not set.

        :raises SSHClientException: If logging in failed.

        :returns: The read output from the server.
        """
        username = self._encode(username)
        self._verify_key_file(keyfile)
        try:
            self._login_with_public_key(username, keyfile, password)
        except SSHClientException:
            raise SSHClientException("Login with public key failed for user "
                                     "'%s'." % username)
        return self._read_login_output(delay)

    def _verify_key_file(self, keyfile):
        if not os.path.exists(keyfile):
            raise SSHClientException("Given key file '%s' does not exist." %
                                     keyfile)
        try:
            open(keyfile).close()
        except IOError:
            raise SSHClientException("Could not read key file '%s'." % keyfile)

    def _login_with_public_key(self, username, keyfile, password):
        raise NotImplementedError

    def execute_command(self, command):
        """Executes the `command` on the remote host.

        This method waits until the output triggered by the execution of the
        `command` is available and then returns it.

        The `command` is always executed in a new shell, meaning that changes to
        the environment are not visible to the subsequent calls of this method.

        :param str command: The command to be executed on the remote host.

        :returns: A 3-tuple (stdout, stderr, return_code) with values
            `stdout` and `stderr` as strings and `return_code` as an integer.
        """
        self.start_command(command)
        return self.read_command_output()

    def start_command(self, command):
        """Starts the execution of the `command` on the remote host.

        The started `command` is pushed into an internal stack. This stack
        always has the latest started `command` on top of it.

        The `command` is always started in a new shell, meaning that changes to
        the environment are not visible to the subsequent calls of this method.

        This method does not return anything. Use :py:meth:`read_command_output`
        to get the output of the previous started command.

        :param str command: The command to be started on the remote host.
        """
        command = self._encode(command)
        self._started_commands.append(self._start_command(command))

    def _start_command(self, command):
        raise NotImplementedError

    def read_command_output(self):
        """Reads the output of the previous started command.

        The previous started command, started with :py:meth:`start_command`,
        is popped out of the stack and its outputs (stdout, stderr and the
        return code) are read and returned.

        :raises SSHClientException: If there are no started commands to read
            output from.

        :returns: A 3-tuple (stdout, stderr, return_code) with values
            `stdout` and `stderr` as strings and `return_code` as an integer.
        """
        try:
            return self._started_commands.pop().read_outputs()
        except IndexError:
            raise SSHClientException('No started commands to read output from.')

    def write(self, text, add_newline=False):
        """Writes `text` in the current shell.

        :param str text: The text to be written.

        :param bool add_newline: If `True`, the configured newline will be
            appended to the `text` before writing it on the remote host.
            The newline is set when calling :py:meth:`open_connection`
        """
        text = self._encode(text)
        if add_newline:
            text += self.config.newline
        self.shell.write(text)

    def read(self, delay=None):
        """Reads all output available in the current shell.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :param str delay: If given, this method reads again after the delay
            to see if there is more output is available. This wait-read cycle is
            repeated as long as further reads return more output or the
            configured timeout expires. The timeout is set when calling
            :py:meth:`open_connection`. The delay can be given as an integer
            (the number of seconds) or in Robot Framework's time format, e.g.
            `4.5s`, `3 minutes`, `2 min 3 sec`.

        :returns: The read output from the remote host.
        """
        output = self.shell.read()
        if delay:
            output += self._delayed_read(delay)
        return self._decode(output)

    def _decode(self, output):
        return output.decode(self.config.encoding)

    def _delayed_read(self, delay):
        delay = TimeEntry(delay).value
        max_time = time.time() + self.config.get('timeout').value
        output = ''
        while time.time() < max_time:
            time.sleep(delay)
            read = self.shell.read()
            if not read:
                break
            output += read
        return output

    def read_char(self):
        """Reads a single char from the current shell.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :returns: A single char read from the output.
        """
        server_output = ''
        while True:
            try:
                server_output += self.shell.read_byte()
                return self._decode(server_output)
            except UnicodeDecodeError:
                pass

    def read_until(self, expected):
        """Reads output from the current shell until the `expected` text is
        encountered or the timeout expires.

        The timeout is set when calling :py:meth:`open_connection`.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :param str expected: The text to look for in the output.

        :raises SSHClientException: If `expected` is not found in the output
            when the timeout expires.

        :returns: The read output, including the encountered `expected` text.
        """
        expected = self._encode(expected)
        return self._read_until(lambda s: expected in s, expected)

    def _read_until(self, matcher, expected, timeout=None):
        output = ''
        timeout = TimeEntry(timeout) if timeout else self.config.get('timeout')
        max_time = time.time() + timeout.value
        while time.time() < max_time:
            output += self.read_char()
            if matcher(output):
                return output
        raise SSHClientException("No match found for '%s' in %s\nOutput:\n%s."
                                 % (expected, timeout, output))

    def read_until_newline(self):
        """Reads output from the current shell until a newline character is
        encountered or the timeout expires.

        The newline character and the timeout are set when calling
        :py:meth:`open_connection`.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :raises SSHClientException: If the newline character is not found in the
            output when the timeout expires.

        :returns: The read output, including the encountered newline character.
        """
        return self.read_until(self.config.newline)

    def read_until_prompt(self):
        """Reads output from the current shell until the prompt is encountered
        or the timeout expires.

        The prompt and timeout are set when calling :py:meth:`open_connection`.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :raises SSHClientException: If prompt is not set or is not found
            in the output when the timeout expires.

        :returns: The read output, including the encountered prompt.
        """
        if not self.config.prompt:
            raise SSHClientException('Prompt is not set.')
        return self.read_until(self.config.prompt)

    def read_until_regexp(self, regexp):
        """Reads output from the current shell until the `regexp` matches or
        the timeout expires.

        The timeout is set when calling :py:meth:`open_connection`.

        Reading always consumes the output, meaning that after being read,
        the read content is no longer present in the output.

        :param regexp: Either the regular expression as a string or a compiled
            Regex object.

        :raises SSHClientException: If no match against `regexp` is found when
            the timeout expires.

        :returns: The read output up and until the `regexp` matches.
        """
        regexp = self._encode(regexp)
        if isinstance(regexp, basestring):
            regexp = re.compile(regexp)
        return self._read_until(lambda s: regexp.search(s), regexp.pattern)

    def write_until_expected(self, text, expected, timeout, interval):
        """Writes `text` repeatedly in the current shell until the `expected`
        appears in the output or the `timeout` expires.

        :param str text: Text to be written. Uses :py:meth:`write_bare`
            internally so no newline character is appended to the written text.

        :param str expected: Text to look for in the output.

        :param int timeout: The timeout during which `expected` must appear
            in the output. Can be given as an integer (the number of seconds)
            or in Robot Framework's time format, e.g. `4.5s`, `3 minutes`,
            `2 min 3 sec`.

        :param int interval: Time to wait between the repeated writings of
            `text`.

        :raises SSHClientException: If `expected` is not found in the output
            before the `timeout` expires.

        :returns: The read output, including the encountered `expected` text.
        """
        expected = self._encode(expected)
        interval = TimeEntry(interval)
        timeout = TimeEntry(timeout)
        max_time = time.time() + timeout.value
        while time.time() < max_time:
            self.write(text)
            try:
                return self._read_until(lambda s: expected in s, expected,
                                        timeout=interval.value)
            except SSHClientException:
                pass
        raise SSHClientException("No match found for '%s' in %s."
                                 % (expected, timeout))

    def put_file(self, source, destination='.', mode='0744', newline='',
                 path_separator=''):
        """Calls :py:meth:`AbstractSFTPClient.put_file` with the given
        arguments.

        If `path_separator` is empty, the connection specific path separator,
        which is set when calling :py:meth:`open_connection`, is used instead.
        This is due to backward compatibility as `path_separator` was moved
        to a connection specific setting in SSHLibrary 2.0.

        See :py:meth:`AbstractSFTPClient.put_file` for more documentation.
        """
        # TODO: Remove deprecated path_separator in SSHLibrary 2.1.
        path_separator = path_separator or self.config.path_separator
        return self.sftp_client.put_file(source, destination, mode, newline,
                                         path_separator)

    def put_directory(self, source, destination='.', mode='0744', newline='',
                      recursive=False):
        """Calls :py:meth:`AbstractSFTPClient.put_directory` with the given
        arguments and the connection specific path separator.

        The connection specific path separator is set when calling
        :py:meth:`open_connection`.

        See :py:meth:`AbstractSFTPClient.put_directory` for more documentation.
        """
        return self.sftp_client.put_directory(source, destination, mode,
                                              newline,
                                              self.config.path_separator,
                                              recursive)

    def get_file(self, source, destination='.', path_separator=''):
        """Calls :py:meth:`AbstractSFTPClient.get_file` with the given
        arguments.

        If `path_separator` is empty, the connection specific path separator,
        which is set when calling :py:meth:`open_connection`, is used instead.
        This is due to backward compatibility as `path_separator` was moved
        to a connection specific setting in SSHLibrary 2.0.

        See :py:meth:`AbstractSFTPClient.get_file` for more documentation.
        """
        # TODO: Remove deprecated path_separator in SSHLibrary 2.1.
        path_separator = path_separator or self.config.path_separator
        return self.sftp_client.get_file(source, destination, path_separator)

    def get_directory(self, source, destination='.', recursive=False):
        """Calls :py:meth:`AbstractSFTPClient.get_directory` with the given
        arguments and the connection specific path separator.

        The connection specific path separator is set when calling
        :py:meth:`open_connection`.

        See :py:meth:`AbstractSFTPClient.get_directory` for more documentation.
        """
        return self.sftp_client.get_directory(source, destination,
                                              self.config.path_separator,
                                              recursive)

    def list_dir(self, path, pattern=None, absolute=False):
        """Calls :py:meth:`.AbstractSFTPClient.list_dir` with the given
        arguments.

        See :py:meth:`AbstractSFTPClient.list_dir` for more documentation.

        :returns: A sorted list of items returned by
            :py:meth:`AbstractSFTPClient.list_dir`.
        """
        items = self.sftp_client.list_dir(path, pattern, absolute)
        return sorted(items)

    def list_files_in_dir(self, path, pattern=None, absolute=False):
        """Calls :py:meth:`AbstractSFTPClient.list_files_in_dir` with the given
        arguments.

        See :py:meth:`AbstractSFTPClient.list_files_in_dir` for more documentation.

        :returns: A sorted list of items returned by
            :py:meth:`AbstractSFTPClient.list_files_in_dir`.
        """
        files = self.sftp_client.list_files_in_dir(path, pattern, absolute)
        return sorted(files)

    def list_dirs_in_dir(self, path, pattern=None, absolute=False):
        """Calls :py:meth:`AbstractSFTPClient.list_dirs_in_dir` with the given
        arguments.

        See :py:meth:`AbstractSFTPClient.list_dirs_in_dir` for more documentation.

        :returns: A sorted list of items returned by
            :py:meth:`AbstractSFTPClient.list_dirs_in_dir`.
        """
        dirs = self.sftp_client.list_dirs_in_dir(path, pattern, absolute)
        return sorted(dirs)

    def is_dir(self, path):
        """Calls :py:meth:`AbstractSFTPClient.is_dir` with the given `path`.

        See :py:meth:`AbstractSFTPClient.is_dir` for more documentation.
        """
        return self.sftp_client.is_dir(path)

    def is_file(self, path):
        """Calls :py:meth:`AbstractSFTPClient.is_file` with the given `path`.

        See :py:meth:`AbstractSFTPClient.is_file` for more documentation.
        """
        return self.sftp_client.is_file(path)

class AbstractShell(object):
    """Base class for the shell implementation.

    Classes derived from this class (i.e. :py:class:`pythonclient.Shell`
    and :py:class:`javaclient.Shell`) provide the concrete and the language
    specific implementations for reading and writing in a shell session.
    """

    def read(self):
        """Reads all the output from the shell.

        :returns: The read output.
        """
        raise NotImplementedError

    def read_byte(self):
        """Reads a single byte from the shell.

        :returns: The read byte.
        """
        raise NotImplementedError

    def write(self, text):
        """Writes the `text` in the current shell.

        :param str text: The text to be written. No newline characters are
            be appended automatically to the written text by this method.
        """
        raise NotImplementedError

class AbstractSFTPClient(object):
    """Base class for the SFTP implementation.

    Classes derived from this class (i.e. :py:class:`pythonclient.SFTPClient`
    and :py:class:`javaclient.SFTPClient`) provide the concrete and the language
    specific implementations for getting, putting and listing files and
    directories.
    """

    def __init__(self):
        self._homedir = self._absolute_path('.')

    def _absolute_path(self, path):
        raise NotImplementedError

    def is_file(self, path):
        """Checks if the `path` points to a regular file on the remote host.

        If the `path` is a symlink, its destination is checked instead.

        :param str path: The path to check.

        :returns: `True`, if the `path` is points to an existing regular file.
            False otherwise.
        """
        try:
            item = self._stat(path)
        except IOError:
            return False
        return item.is_regular()

    def _stat(self, path):
        raise NotImplementedError

    def is_dir(self, path):
        """Checks if the `path` points to a directory on the remote host.

        If the `path` is a symlink, its destination is checked instead.

        :param str path: The path to check.

        :returns: `True`, if the `path` is points to an existing directory.
            False otherwise.
        """
        try:
            item = self._stat(path)
        except IOError:
            return False
        return item.is_directory()

    def list_dir(self, path, pattern=None, absolute=False):
        """Gets the item names, or optionally the absolute paths, on the given
        `path` on the remote host.

        This includes regular files, directories as well as other file types,
        e.g. device files.

        :param str path: The path on the remote host to list.

        :param str pattern: If given, only the item names that match
            the given pattern are returned. Please do note, that the `pattern`
            is never matched against the full path, even if `absolute` is set
            `True`.

        :param bool absolute: If `True`, the absolute paths of the items are
            returned instead of the item names.

        :returns: A list containing either the item names or the absolute
            paths. In both cases, the List is first filtered by the `pattern`
            if it is given.
        """
        return self._list_filtered(path, self._get_item_names, pattern,
                                   absolute)

    def _list_filtered(self, path, filter_method, pattern=None, absolute=False):
        self._verify_remote_dir_exists(path)
        items = filter_method(path)
        if pattern:
            items = self._filter_by_pattern(items, pattern)
        if absolute:
            items = self._include_absolute_path(items, path)
        return items

    def _verify_remote_dir_exists(self, path):
        if not self.is_dir(path):
            raise SSHClientException("There was no directory matching '%s'." %
                                     path)

    def _get_item_names(self, path):
        return [item.name for item in self._list(path)]

    def _list(self, path):
        raise NotImplementedError

    def _filter_by_pattern(self, items, pattern):
        return [name for name in items if fnmatchcase(name, pattern)]

    def _include_absolute_path(self, items, path):
        absolute_path = self._absolute_path(path)
        if absolute_path[1:3] == ':\\':
            absolute_path += '\\'
        else:
            absolute_path += '/'
        return [absolute_path + name for name in items]

    def list_files_in_dir(self, path, pattern=None, absolute=False):
        """Gets the file names, or optionally the absolute paths, of the regular
        files on the given `path` on the remote host.
.
        :param str path: The path on the remote host to list.

        :param str pattern: If given, only the file names that match
            the given pattern are returned. Please do note, that the `pattern`
            is never matched against the full path, even if `absolute` is set
            `True`.

        :param bool absolute: If `True`, the absolute paths of the regular files
            are returned instead of the file names.

        :returns: A list containing either the regular file names or the absolute
            paths. In both cases, the List is first filtered by the `pattern`
            if it is given.
        """
        return self._list_filtered(path, self._get_file_names, pattern,
                                   absolute)

    def _get_file_names(self, path):
        return [item.name for item in self._list(path) if item.is_regular()]

    def list_dirs_in_dir(self, path, pattern=None, absolute=False):
        """Gets the directory names, or optionally the absolute paths, on the
        given `path` on the remote host.

        :param str path: The path on the remote host to list.

        :param str pattern: If given, only the directory names that match
            the given pattern are returned. Please do note, that the `pattern`
            is never matched against the full path, even if `absolute` is set
            `True`.

        :param bool absolute: If `True`, the absolute paths of the directories
            are returned instead of the directory names.

        :returns: A list containing either the directory names or the absolute
            paths. In both cases, the List is first filtered by the `pattern`
            if it is given.
        """
        return self._list_filtered(path, self._get_directory_names, pattern,
                                   absolute)

    def _get_directory_names(self, path):
        return [item.name for item in self._list(path) if item.is_directory()]

    def get_directory(self, source, destination, path_separator='/',
                      recursive=False):
        """Downloads directory(-ies) from the remote host to the local machine,
        optionally with subdirectories included.

        :param str source: The path to the directory on the remote machine.

        :param str destination: The target path on the local machine.
            The destination defaults to the current local working directory.

        :param str path_separator: The path separator used for joining the
            paths on the remote host. On Windows, this must be set as `\`.
            The default is `/`, which is also the default on Linux-like systems.

        :param bool recursive: If `True`, the subdirectories in the `source`
            path are downloaded as well.

        :returns: A list of 2-tuples for all the downloaded files. These tuples
            contain the remote path as the first value and the local target
            path as the second.
        """
        source = self._remove_ending_path_separator(path_separator, source)
        self._verify_remote_dir_exists(source)
        files = []
        items = self.list_dir(source)
        if items:
            for item in items:
                remote = source + path_separator + item
                local = os.path.join(destination, item)
                if self.is_file(remote):
                    files += self.get_file(remote, local)
                elif recursive:
                    files += self.get_directory(remote, local, path_separator,
                                                recursive)
        else:
            os.mkdir(destination)
            files.append((source, destination))
        return files

    def _remove_ending_path_separator(self, path_separator, source):
        if source.endswith(path_separator):
            source = source[:-len(path_separator)]
        return source

    def get_file(self, source, destination, path_separator='/'):
        """Downloads file(s) from the remote host to the local machine.

        :param str source: The path to the file on the remote machine.
            Glob patterns, like '*' and '?', can be used in the source, in
            which case all the matching files are downloaded.

        :param str destination: The target path on the local machine.
            If many files are downloaded, e.g. patterns are used in the
            `source`, then this must be a path to an existing directory.
            The destination defaults to the current local working directory.

        :param str path_separator: The path separator used for joining the
            paths on the remote host. On Windows, this must be set as `\`.
            The default is `/`, which is also the default on Linux-like systems.

        :returns: A list of 2-tuples for all the downloaded files. These tuples
            contain the remote path as the first value and the local target
            path as the second.
        """
        remote_files = self._get_get_file_sources(source, path_separator)
        if not remote_files:
            msg = "There were no source files matching '%s'." % source
            raise SSHClientException(msg)
        local_files = self._get_get_file_destinations(remote_files, destination)
        files = zip(remote_files, local_files)
        for src, dst in files:
            self._get_file(src, dst)
        return files

    def _get_get_file_sources(self, source, path_separator):
        if path_separator in source:
            path, pattern = source.rsplit(path_separator, 1)
        else:
            path, pattern = '', source
        if not path:
            path = '.'
        return [filename for filename in
                self.list_files_in_dir(path, pattern, absolute=True)]

    def _get_get_file_destinations(self, source_files, destination):
        target_is_dir = destination.endswith(os.sep) or destination == '.'
        if not target_is_dir and len(source_files) > 1:
            raise SSHClientException('Cannot copy multiple source files to one '
                                     'destination file.')
        destination = os.path.abspath(destination.replace('/', os.sep))
        self._create_missing_local_dirs(destination, target_is_dir)
        if target_is_dir:
            return [os.path.join(destination, os.path.basename(name))
                    for name in source_files]
        return [destination]

    def _create_missing_local_dirs(self, destination, target_is_dir):
        if not target_is_dir:
            destination = os.path.dirname(destination)
        if not os.path.exists(destination):
            os.makedirs(destination)

    def _get_file(self, source, destination):
        raise NotImplementedError

    def put_directory(self, source, destination, mode, newline,
                      path_separator='/', recursive=False):
        """Uploads directory(-ies) from the local machine to the remote host,
        optionally with subdirectories included.

        :param str source: The path to the directory on the local machine.

        :param str destination: The target path on the remote host.
            The destination defaults to the user's home at the remote host.

        :param str mode: The uploaded files on the remote host are created with
            these modes. The modes are given as traditional Unix octal
            permissions, such as '0600'.

        :param str newline: If given, the newline characters of the uploaded
            files on the remote host are converted to this.

        :param str path_separator: The path separator used for joining the
            paths on the remote host. On Windows, this must be set as `\`.
            The default is `/`, which is also the default on Linux-like systems.

        :param bool recursive: If `True`, the subdirectories in the `source`
            path are uploaded as well.

        :returns: A list of 2-tuples for all the uploaded files. These tuples
            contain the local path as the first value and the remote target
            path as the second.
        """
        self._verify_local_dir_exists(source)
        destination = self._remove_ending_path_separator(path_separator,
                                                         destination)
        if self.is_dir(destination):
            destination = destination + path_separator +\
                          source.rsplit(os.path.sep)[-1]
        return self._put_directory(source, destination, mode, newline,
                                   path_separator, recursive)

    def _put_directory(self, source, destination, mode, newline,
                      path_separator, recursive):
        files = []
        items = os.listdir(source)
        if items:
            for item in items:
                local_path = os.path.join(source, item)
                remote_path = destination + path_separator + item
                if os.path.isfile(local_path):
                    files += self.put_file(local_path, remote_path, mode,
                                           newline, path_separator)
                elif recursive and os.path.isdir(local_path):
                    files += self._put_directory(local_path, remote_path, mode,
                                                newline, path_separator,
                                                recursive)
        else:
            self._create_missing_remote_path(destination)
            files.append((source, destination))
        return files

    def _verify_local_dir_exists(self, path):
        if not os.path.isdir(path):
            raise SSHClientException("There was no source path matching '%s'."
                                     % path)

    def put_file(self, sources, destination, mode, newline, path_separator='/'):
        """Uploads the file(s) from the local machine to the remote host.

        :param str source: The path to the file on the local machine.
            Glob patterns, like '*' and '?', can be used in the source, in
            which case all the matching files are uploaded.

        :param str destination: The target path on the remote host.
            If multiple files are uploaded, e.g. patterns are used in the
            `source`, then this must be a path to an existing directory.
            The destination defaults to the user's home at the remote host.

        :param str mode: The uploaded files on the remote host are created with
            these modes. The modes are given as traditional Unix octal
            permissions, such as '0600'.

        :param str newline: If given, the newline characters of the uploaded
            files on the remote host are converted to this.

        :param str path_separator: The path separator used for joining the
            paths on the remote host. On Windows, this must be set as `\`.
            The default is `/`, which is also the default on Linux-like systems.

        :returns: A list of 2-tuples for all the uploaded files. These tuples
            contain the local path as the first value and the remote target
            path as the second.
        """
        mode = int(mode, 8)
        newline = {'CRLF': '\r\n', 'LF': '\n'}.get(newline.upper(), None)
        local_files = self._get_put_file_sources(sources)
        remote_files, remote_dir = self._get_put_file_destinations(local_files,
                                                                   destination,
                                                                   path_separator)
        self._create_missing_remote_path(remote_dir)
        files = zip(local_files, remote_files)
        for source, destination in files:
            self._put_file(source, destination, mode, newline)
        return files

    def _get_put_file_sources(self, source):
        sources = [f for f in glob.glob(source.replace('/', os.sep))
                   if os.path.isfile(f)]
        if not sources:
            msg = "There are no source files matching '%s'." % source
            raise SSHClientException(msg)
        return sources

    def _get_put_file_destinations(self, sources, destination, path_separator):
        destination = destination.split(':')[-1].replace('\\', '/')
        if destination == '.':
            destination = self._homedir + '/'
        if len(sources) > 1 and destination[-1] != '/':
            raise ValueError('It is not possible to copy multiple source '
                             'files to one destination file.')
        dir_path, filename = self._parse_path_elements(destination,
                                                       path_separator)
        if filename:
            files = [path_separator.join([dir_path, filename])]
        else:
            files = [path_separator.join([dir_path, os.path.basename(path)])
                     for path in sources]
        return files, dir_path

    def _parse_path_elements(self, destination, path_separator):
        def _isabs(path):
            if destination.startswith(path_separator):
                return True
            if path_separator == '\\' and path[1:3] == ':\\':
                return True
            return False
        if not _isabs(destination):
            destination = path_separator.join([self._homedir, destination])
        return destination.rsplit(path_separator, 1)

    def _create_missing_remote_path(self, path):
        if path.startswith('/'):
            current_dir = '/'
        else:
            current_dir = self._absolute_path('.')
        for dir_name in path.split('/'):
            if dir_name:
                current_dir = '%s/%s' % (current_dir, dir_name)
            try:
                self._client.stat(current_dir)
            except:
                self._client.mkdir(current_dir, 0744)

    def _put_file(self, source, destination, mode, newline):
        remote_file = self._create_remote_file(destination, mode)
        with open(source, 'rb') as local_file:
            position = 0
            while True:
                data = local_file.read(4096)
                if not data:
                    break
                if newline and '\n' in data:
                    data = data.replace('\n', newline)
                self._write_to_remote_file(remote_file, data, position)
                position += len(data)
            self._close_remote_file(remote_file)

    def _create_remote_file(self, destination, mode):
        raise NotImplementedError

    def _write_to_remote_file(self, remote_file, data, position):
        raise NotImplementedError

    def _close_remote_file(self, remote_file):
        raise NotImplementedError

class AbstractCommand(object):
    """Base class for the remote command.

    Classes derived from this class (i.e. :py:class:`pythonclient.RemoteCommand`
    and :py:class:`javaclient.RemoteCommand`) provide the concrete and the
    language specific implementations for running the command on the remote
    host.
    """

    def __init__(self, command, encoding):
        self._command = command
        self._encoding = encoding
        self._shell = None

    def run_in(self, shell):
        """Runs this command in the given `shell`.

        :param shell: A shell in the already open connection.
        """
        self._shell = shell
        self._execute()

    def _execute(self):
        raise NotImplementedError

    def read_outputs(self):
        """Returns the outputs of this command.

        :returns: A 3-tuple (stdout, stderr, return_code) with values
            `stdout` and `stderr` as strings and `return_code` as an integer.
        """
        raise NotImplementedError

class SFTPFileInfo(object):
    """Wrapper class for the language specific file information objects.

    Returned by the concrete SFTP client implementations.
    """

    def __init__(self, name, mode):
        self.name = name
        self.mode = mode

    def is_regular(self):
        """Checks if this file is a regular file.

        :returns: `True`, if the file is a regular file. False otherwise.
        """
        return stat.S_ISREG(self.mode)

    def is_directory(self):
        """Checks if this file is a directory.

        :returns: `True`, if the file is a regular file. False otherwise.
        """
        return stat.S_ISDIR(self.mode)


text:
class DownloadTestObserverNotInProgress : public content::DownloadTestObserver {
 public:
  DownloadTestObserverNotInProgress(content::DownloadManager* download_manager,
                                    size_t count);

  DownloadTestObserverNotInProgress(const DownloadTestObserverNotInProgress&) =
      delete;
  DownloadTestObserverNotInProgress& operator=(
      const DownloadTestObserverNotInProgress&) = delete;

  ~DownloadTestObserverNotInProgress() override;

  void StartObserving();

 private:
  bool IsDownloadInFinalState(download::DownloadItem* download) override;

  bool started_observing_;
};

#endif  // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_BROWSERTEST_H_

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nouv. Mem. Soc. Imp. nat. Moscou 15(no. 20): 370 (1898)

#### Original name
Sphaeronaema capillare Ellis & Harkn.

### Remarks
null


text:
/*
 * PreferencesWindowController.m
 *
 * Created by Sajid Anwar.
 *
 * Subject to terms and conditions in LICENSE.md.
 *
 */

#import "PreferencesWindowController.h"

@implementation PreferencesWindowController

@synthesize generalController;
@synthesize lastFmController;
@synthesize navigationController;

- (id)init
{
    self = [self initWithViewControllers:[NSMutableArray array] title:@"Preferences"];

    if (self) {
        [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([PreferencesWindowController class]) owner:self topLevelObjects:nil];
        [self loadControllers];
        [self.window setStyleMask:([self.window styleMask])];
    }

    return self;
}

- (void)loadControllers
{
    [self addViewController:generalController];
    [self addViewController:navigationController];
    [self addViewController:lastFmController];
    [self selectControllerAtIndex:0];
}

@end


text:
<?php

use LawnGnome\Questionator\QuestionRepository;
use Silex\Application;
use Symfony\Component\HttpFoundation\{Request, Response};

use function LawnGnome\Questionator\dsn;

require_once __DIR__.'/../vendor/autoload.php';

$app = new Application;

$app['db'] = $app->share(function (): PDO {
  $db = new PDO(dsn());
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  return $db;
});

$app['questions'] = $app->share(function (Application $app): QuestionRepository {
  return new QuestionRepository($app['db']);
});

$app->get('/', function (Request $request) use ($app): Response {
  return $app->redirect('/submit.html');
});

$app->get('/questions', function (Request $request) use ($app): Response {
  return $app->json($app['questions']->all());
});

$app->post('/question', function (Request $request) use ($app): Response {
  $question = $app['questions']->create();
  $question->setName(substr($request->request->get('name'), 0, 50));
  $question->setQuestion(substr($request->request->get('question'), 0, 500));
  $app['questions']->save($question);

  return $app->redirect('/thanks.html');
});

$app->run();


text:
import amazonproduct
# https://github.com/ligyxy/MySQLTool
from DictMySQLdb import DictMySQLdb
import random
import time

class IdCache:
    def __init__(self, con):
        """
        Pass in the mysql connection from mysqltool
        :param con: DB()
        """
        self.con = con
        self.cache = {}

    def __call__(self, tablename, value):
        keys = '_'.join([tablename.lower()] + [str(k).lower() + '_' + str(v).lower() for k, v in value.iteritems()])

        if self.cache.get(keys):
            return self.cache.get(keys)
        else:
            id_db = self.con.get(tablename, value)
            self.cache[keys] = id_db
            return id_db

pd_db = DictMySQLdb(user='root', passwd='', host='127.0.0.1', db='product')
cache = IdCache(pd_db)

api = amazonproduct.API(locale='us')
# Initialize the starting keywords
keywordlist = ['Microsoft', 'GPS', 'Security', 'Tourister', 'Filter', 'Storage', 'intel', 'Conditioner', 'windows', 'Bicycle',
               'Foldable', 'TB', 'Remote', 'hair', 'Cutlery', 'Inch', 'USB', 'Bluetooth', 'Android', 'Vacuum',
               'Quart', 'TV', 'IPS', 'bose', 'Closet', 'Colgate', 'Dishwasher', 'Box', 'Inkjet', 'Nikon', 'Gigabit',
               'Beauty', 'Cooker', 'Camera', 'pump', 'Mixer', 'Macbook', 'Language', 'Pack', 'HTC']
keyword = random.sample(keywordlist, 1)[0]
count = 0

def get_cat_id(pd_asin):
    try:
        nodes = api.item_lookup(pd_asin, ResponseGroup='BrowseNodes')
        nodeid = nodes.Items.Item.BrowseNodes.BrowseNode.BrowseNodeId
        node = api.browse_node_lookup(nodeid).BrowseNodes
    except amazonproduct.errors.InvalidParameterValue:
        return None
    # Get the root category
    cat_list = []
    while True:
        try:
            name = node.BrowseNode.Name
            node = node.BrowseNode.Ancestors
            if node is not None:
                cat_list.append(name)
        except AttributeError:
            try:
                # The last category is the root cat
                pd_root_cat = node.BrowseNode.Name
                cat_list.append(pd_root_cat)
                # Root cats' upper_level is 1
                level = 1
                for cat in cat_list[::-1]:
                    level = cache('category', {'name': cat, 'upper_level': level})
                return {'root': cache('category', {'name': pd_root_cat, 'upper_level': 1}),
                        'leaf': level}
            except Exception:
                return None
while True:
    result = []
    value_list = []
    # Assume the similar search will return product in same root category
    root_cat_list = {}
    leaf_cat_list = {}
    try:
        print 'Keyword: ' + keyword
        for item in api.item_search('All', Keywords=keyword):
            pd_asin = unicode(item.ASIN)
            pd_title = unicode(item.ItemAttributes.Title)
            pd_cat = unicode(item.ItemAttributes.ProductGroup)
            result.append(pd_asin)
            if pd_asin and pd_title and pd_cat:
                # pd_root_cat_id & pd_leaf_cat_id is the cache for categories with their ids
                # We assume the leaf categories are unique
                if root_cat_list.get(pd_cat) and leaf_cat_list.get(pd_cat):
                    pd_root_cat_id = root_cat_list.get(pd_cat)
                    pd_leaf_cat_id = leaf_cat_list.get(pd_cat)
                    print 'Get id from cache'
                # If not in cache, get the id through browsenode API and store them into cache
                else:
                    cat_id = get_cat_id(pd_asin)
                    if cat_id:
                        pd_root_cat_id = cat_id.get('root')
                        pd_leaf_cat_id = cat_id.get('leaf')
                        root_cat_list[pd_cat] = pd_root_cat_id
                        leaf_cat_list[pd_cat] = pd_leaf_cat_id
                        print 'Get id through API'
                    # Skip it if no category id returns
                    else:
                        print 'Cannot get root category'
                        continue
                if pd_root_cat_id and pd_leaf_cat_id:
                    value_list.append((pd_asin, pd_title, pd_leaf_cat_id, pd_root_cat_id))
        if value_list:
            # asin is UNIQUE in database
            pd_db.cur.executemany('INSERT IGNORE INTO item (asin, title, category_id, root_category_id) VALUES (%s, %s, %s, %s)',
                                  value_list)
            pd_db.conn.commit()
            print 'Insert a new list! length: %d\n' % len(value_list)
        if len(result) > 5:
            try:
                pick = random.sample(result, 2)
                # Pick two product randomly to perform similarity searching
                title = api.similarity_lookup(pick[0], pick[1], SimilarityType='Random').Items.Item.ItemAttributes.Title
                keyword = ' '.join(unicode(title).split(' ')[-2::])
            except amazonproduct.errors.NoSimilarityForASIN:
                keyword = random.sample(keywordlist, 1)[0]
        else:
            keyword = random.sample(keywordlist, 1)[0]
    except Exception:
        # The API and the package are not rubust enough
        del api
        api = amazonproduct.API(locale='us')
        print 'TIMEOUT ERROR'
        time.sleep(50)
        keyword = random.sample(keywordlist, 1)[0]
    count += 1

pd_db.close()


text:
/* eslint-disable @typescript-eslint/no-explicit-any */

// This old component doesn't have typings, so we put our own typings in place!
declare module '@scottnonnenberg/notate' {
  type NotateType = {
    (
      cb: (error?: Error | null, result?: any) => unknown,
      error?: Error,
      additionalProperties?: any
    ): string;
    prettyPrint: (error: Error) => string;
  };

  const notate: NotateType;

  export default notate;
}


text:
<link rel="import" href="../polymer/polymer.html">
<dom-module id="paper-date-utils">
  <style>
    :host {
      display: none;
    }
  </style>
</dom-module>
<script>
  Polymer({
    is: 'paper-date-utils',

    addDays: function(d, days) {
      var newDate = this.clone(d);
      newDate.setDate(d.getDate() + days);
      return newDate;
    },

    addMonths: function(d, months) {
      var newDate = this.clone(d);
      newDate.setMonth(d.getMonth() + months);
      return newDate;
    },

    clone: function(d) {
      return new Date(d.getTime());
    },

    getDaysInMonth: function(d) {
      var resultDate = this.getFirstDayOfMonth(d);

      resultDate.setMonth(resultDate.getMonth() + 1);
      resultDate.setDate(resultDate.getDate() - 1);

      return resultDate.getDate();
    },

    getFirstDayOfMonth: function(d) {
      return new Date(d.getFullYear(), d.getMonth(), 1);
    },

    getWeekArray: function(d) {
      var dayArray = [];
      var daysInMonth = this.getDaysInMonth(d);
      var daysInWeek;
      var emptyDays;
      var firstDayOfWeek;
      var week;
      var weekArray = [];

      for (var i = 1; i <= daysInMonth; i++) {
        dayArray.push(new Date(d.getFullYear(), d.getMonth(), i));
      }

      while (dayArray.length) {
        firstDayOfWeek = dayArray[0].getDay();
        daysInWeek = 7 - firstDayOfWeek;
        emptyDays = 7 - daysInWeek;
        week = dayArray.splice(0, daysInWeek);

        for (var j = 0; j < emptyDays; j++) {
          week.unshift(null);
        }

        weekArray.push(week);
      }

      return weekArray;
    },

    isEqualDate: function(d1, d2) {
      return d1 && d2 &&
        (d1.getFullYear() === d2.getFullYear()) &&
        (d1.getMonth() === d2.getMonth()) &&
        (d1.getDate() === d2.getDate());
    },

    isEqualMonth: function(d1, d2) {
      return d1 && d2 &&
        (d1.getFullYear() === d2.getFullYear()) &&
        (d1.getMonth() === d2.getMonth());
    },

    monthDiff: function(d1, d2) {
      var m;
      m = (d1.getFullYear() - d2.getFullYear()) * 12;
      m += d1.getMonth();
      m -= d2.getMonth();
      return m;
    }

  });

  /**
  * Transform a supplied input date using a specified format
  * @param  {date} input
  * @param  {string} format
  * @return {date}
  */
  Polymer.Base.date = function (input, format) {
    var date = new Date(input),
        day = date.getDate(),
        month = date.getMonth() + 1,
        year = date.getFullYear(),
        hours = date.getHours(),
        minutes = date.getMinutes(),
        seconds = date.getSeconds();

    if (!format) {
      format = 'MM/dd/yyyy';
    }

    format = format.replace('MM', month.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf('yyyy') > -1) {
        format = format.replace('yyyy', year.toString());
    } else if (format.indexOf('yy') > -1) {
        format = format.replace('yy', year.toString().substr(2, 2));
    }

    format = format.replace('dd', day.toString().replace(/^(\d)$/, '0$1'));

    if (format.indexOf('t') > -1) {
        if (hours > 11) {
            format = format.replace('t', 'pm');
        } else {
            format = format.replace('t', 'am');
        }
    }

    if (format.indexOf('HH') > -1) {
        format = format.replace('HH', hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf('hh') > -1) {
        if (hours > 12) {
            hours -= 12;
        }

        if (hours === 0) {
            hours = 12;
        }
        format = format.replace('hh', hours.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf('mm') > -1) {
        format = format.replace('mm', minutes.toString().replace(/^(\d)$/, '0$1'));
    }

    if (format.indexOf('ss') > -1) {
        format = format.replace('ss', seconds.toString().replace(/^(\d)$/, '0$1'));
    }

    return format;
  };
</script>


text:
import { configure, addDecorator } from '@storybook/react'
import { withKnobs } from '@storybook/addon-knobs'
import { setOptions } from '@storybook/addon-options'

setOptions({
    name: '@mozaik/ui',
    addonPanelInRight: true,
})

addDecorator(withKnobs)

function loadStories() {
    require('../stories/text.js')
    require('../stories/widget_header')
    require('../stories/widget_label')
    require('../stories/widget_list_item')
    require('../stories/widget_counter')
    require('../stories/widget_status_badge')
}

configure(loadStories, module)


text:
<archimate:Product
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="gremlin-rs"
    id="c3be1907-ae12-4ae0-a143-56540f061152"
    documentation="https://github.com/wolf4ood/gremlin-rs
A Rust client for Apache TinkerPop™."/>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 468 (1898)

#### Original name
Puccinia congregata Ellis & Harkn.

### Remarks
null


text:
<?php
/*
 *
 */

namespace RDF\JobDefinitionFormatBundle\Model\JDF\Resource\Link;

use Doctrine\OXM\Mapping as OXM;

/**
 * RDF\JobDefinitionFormatBundle\Model\JDF\Resource\Link\CustomerInfo
 *
 * @OXM\XmlEntity(xml="CustomerInfoLink")
 */
class CustomerInfoLink extends ResourceLink
{

}


text:
package com.example.android.supportv13.app;

import com.example.android.supportv13.R;

import android.app.Fragment;
import android.os.Bundle;
import android.support.v13.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentTabsFragment extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.pager);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("array").setIndicator("Array"),
                FragmentPagerSupport.ArrayListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("cursor").setIndicator("Cursor"),
                CursorFragment.class, null);

        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}
//END_INCLUDE(complete)


text:
<component name="ProjectDictionaryState">
  <dictionary name="gronostaj">
    <words>
      <w>mqttc</w>
      <w>protoc</w>
    </words>
  </dictionary>
</component>


text:
<?php

declare(strict_types=1);

namespace Humbug\PhpScoper\Patcher;

use function Safe\preg_replace;
use function Safe\sprintf;
use function strpos;

final class SymfonyPatcher
{
    private const PATHS = [
        'src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php',
        'symfony/dependency-injection/Dumper/PhpDumper.php',
    ];

    public function __invoke(string $filePath, string $prefix, string $contents): string
    {
        if (!$this->isValidPath($filePath)) {
            return $contents;
        }

        return (string) preg_replace(
            '/use (Symfony(\\\\(?:\\\\)?)Component\\\\.+?;)/',
            sprintf(
                'use %s$2$1',
                $prefix
            ),
            $contents
        );
    }

    private function isValidPath(string $filePath): bool
    {
        foreach (self::PATHS as $path) {
            if (false !== strpos($filePath, $path)) {
                return true;
            }
        }

        return false;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.iit.cs445.s2016.aahmed22.delectable;

import edu.iit.cs445.s2016.aahmed22.delectable.model.Menu;
import edu.iit.cs445.s2016.aahmed22.delectable.repository.MenuRepository;
import edu.iit.cs445.s2016.aahmed22.delectable.repository.MenuRepositoryStub;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.*;

/**
 *
 * @author adeeb
 */

@Path("/menu")
public class MenuResource {

    private MenuRepository mr = new MenuRepositoryStub();
    private List<Menu> menus = mr.getMenus();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getMenuItems(){
        return Response.ok(menus).build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/{mid : .+}")
    public Response getMenuItemsById(@PathParam("mid") int menuid){
            for(int i =0; i<menus.size(); i++)
                if (menus.get(i).getMenuid() == menuid)
                    return Response.ok(menus.get(i)).build();

            return Response.status(Response.Status.BAD_REQUEST).build();
    }

}


text:
module.exports = {
  watchFolder: 'test/testFiles/',
  db: 'mongodb://localhost/test'
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Pages */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->input([]) ?>

    <?= $form->field($model, 'slug')->input([]) ?>

    <?= $form->field($model, 'keyword_page')->input([]) ?>

    <?= $form->field($model, 'desc_page')->input([]) ?>

    <?= $form->field($model, 'content_page')->textarea(['rows' => 10]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?xml version="1.0" encoding="UTF-8"?>

BURN JEL PLUS - lidocaine hydrochloride gel
Water-Jel Technologies

Disclaimer: Most OTC drugs are not reviewed and approved by FDA, however they may be marketed if they comply with applicable regulations and policies. FDA has not evaluated whether this product complies.

Burn Jel Plus

Active ingredient

Lidocaine HCl 2.5%

Purpose

External analgesic

Uses

for the temporary relief of pain associated with minor burns

Warnings

For external use only

Do not use

in large quantities, particularly over raw surfaces or blistered areas

When using this product

avoid contact with eyes

Stop use and ask a doctor if

conditions worsens

symptoms persist for more than 7 days

condition clears up and occurs again within a few days

Keep out of reach of children.

If swallowed, get medical help or contact a Poison Control Center right away.

Directions

adults and children 2 years of age and older; apply to affected area not more than 3 to 4 times daily

children under 2 years of age: consult a doctor

Other information

spread a thick even layer of Burn Jel Plus over affected area.

Inactive ingredients

carbomer 940, carbomer 1342, diazolidinyl urea, edetate disodium, glycerin, methylparaben, octoxynol 9, propylene glycol, propylparaben, purified water, tea tree oil, trolamine, vitamin E acetate

Questions ?

1-800-275-3433 Weekdays 9 AM - 5 PM EST

Principal Display Panel

BURN JEL PLUS

gel for burns gel

Product Information

Product Type
HUMAN OTC DRUG LABEL
Item Code (Source)
NDC:59898-205

Route of Administration
TOPICAL
DEA Schedule

Active Ingredient/Active Moiety

Ingredient Name
Basis of Strength
Strength

LIDOCAINE HYDROCHLORIDE (LIDOCAINE)
LIDOCAINE HYDROCHLORIDE
2.5 g  in 100 mL

Inactive Ingredients

Ingredient Name
Strength

CARBOMER HOMOPOLYMER TYPE C

GLYCERIN

PROPYLENE GLYCOL

METHYLPARABEN

TEA TREE OIL

DIAZOLIDINYLUREA

Trolamine

OCTOXYNOL 9

CARBOMER COPOLYMER TYPE B

EDETATE DISODIUM

ALPHA-TOCOPHEROL ACETATE

PROPYLPARABEN

WATER

Packaging

#
Item Code
Package Description
Marketing Start Date
Marketing End Date

1
NDC:59898-205-10
1  in 1 CARTON

1

59 mL in 1 BOTTLE, PLASTIC

2
NDC:59898-205-11
24  in 1 CARTON

2

59 mL in 1 BOTTLE, PLASTIC

3
NDC:59898-205-12
1  in 1 CARTON

3

118 mL in 1 BOTTLE, PLASTIC

4
NDC:59898-205-13
24  in 1 CARTON

4

118 mL in 1 BOTTLE, PLASTIC

Marketing Information

Marketing Category
Application Number or Monograph Citation
Marketing Start Date
Marketing End Date

OTC monograph not final
part348
04/10/2010

Labeler - Water-Jel Technologies
							(155522589)

Registrant - Water-Jel Technologies (155522589)

Establishment

Name
Address
ID/FEI
Business Operations

Water-Jel Technologies

155522589
manufacture

Revised: 4/2010

Document Id: 16f671ef-268c-4e20-93bf-0376885e3b16

Set id: 401023a5-6634-4c04-b6a6-55b78a9c79fe

Version: 2

Effective Time: 20100420

Water-Jel Technologies


text:
from axelrod import Actions, Player, obey_axelrod
from ._strategies import strategies
from .hunter import DefectorHunter, AlternatorHunter, RandomHunter, MathConstantHunter, CycleHunter, EventualCycleHunter
from .cooperator import Cooperator
from numpy.random import choice

# Needs to be computed manually to prevent circular dependency
ordinary_strategies = [s for s in strategies if obey_axelrod(s)]
C, D = Actions.C, Actions.D

class MetaPlayer(Player):
    """A generic player that has its own team of players."""

    name = "Meta Player"

    team = [Cooperator]
    classifier = {
        'memory_depth': float('inf'),  # Long memory
        'stochastic': False,
        'makes_use_of': set(),
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def __init__(self):

        super(MetaPlayer, self).__init__()

        # Make sure we don't use any meta players to avoid infinite recursion.
        self.team = [t for t in self.team if not issubclass(t, MetaPlayer)]
        self.nteam = len(self.team)

        # Initiate all the player in out team.
        self.team = [t() for t in self.team]

        # This player inherits the classifiers of its team.
        for key in ['stochastic',
                    'inspects_source',
                    'manipulates_source',
                    'manipulates_state']:
            self.classifier[key] = (any(t.classifier[key] for t in self.team))

        for t in self.team:
            self.classifier['makes_use_of'].update(t.classifier['makes_use_of'])

    def strategy(self, opponent):

        # Make sure the history of all hunters is current.
        for ih in range(len(self.team)):
            self.team[ih].history = self.history

        # Get the results of all our players.
        results = [player.strategy(opponent) for player in self.team]

        # A subclass should just define a way to choose the result based on team results.
        return self.meta_strategy(results, opponent)

    def meta_strategy(self, results, opponent):
        """Determine the meta result based on results of all players."""
        pass

    def reset(self):
        Player.reset(self)
        # Reset each player as well
        for player in self.team:
            player.reset()

class MetaMajority(MetaPlayer):
    """A player who goes by the majority vote of all other non-meta players."""

    name = "Meta Majority"

    def __init__(self, team=None):
        if team:
            self.team = team
        else:
            # Needs to be computed manually to prevent circular dependency
            self.team = ordinary_strategies
        super(MetaMajority, self).__init__()
        self.init_args = (team,)
        self.classifier['memory_depth'] = float('inf')

    @staticmethod
    def meta_strategy(results, opponent):
        if results.count(D) > results.count(C):
            return D
        return C

class MetaMinority(MetaPlayer):
    """A player who goes by the minority vote of all other non-meta players."""

    name = "Meta Minority"

    def __init__(self, team=None):
        if team:
            self.team = team
        else:
            # Needs to be computed manually to prevent circular dependency
            self.team = ordinary_strategies
        super(MetaMinority, self).__init__()
        self.init_args = (team,)
        self.classifier['memory_depth'] = float('inf')

    @staticmethod
    def meta_strategy(results, opponent):
        if results.count(D) < results.count(C):
            return D
        return C

class MetaWinner(MetaPlayer):
    """A player who goes by the strategy of the current winner."""

    name = "Meta Winner"

    def __init__(self, team=None):

        # The default is to use all strategies available, but we need to import the list
        # at runtime, since _strategies import also _this_ module before defining the list.
        if team:
            self.team = team
        else:
            # Needs to be computed manually to prevent circular dependency
            self.team = ordinary_strategies

        super(MetaWinner, self).__init__()
        self.init_args = (team,)

        # For each player, we will keep the history of proposed moves and
        # a running score since the beginning of the game.
        for t in self.team:
            t.proposed_history = []
            t.score = 0

    def strategy(self, opponent):

        # Update the running score for each player, before determining the next move.
        if len(self.history):
            for player in self.team:
                game = self.match_attributes["game"]
                last_round = (player.proposed_history[-1], opponent.history[-1])
                s = game.scores[last_round][0]
                player.score += s
        return super(MetaWinner, self).strategy(opponent)

    def meta_strategy(self, results, opponent):

        scores = [pl.score for pl in self.team]
        bestscore = max(scores)
        beststrategies = [i for i, pl in enumerate(self.team) if pl.score == bestscore]
        bestproposals = [results[i] for i in beststrategies]
        bestresult = C if C in bestproposals else D

        # Update each player's proposed history with his proposed result, but always after
        # the new result has been settled based on scores accumulated until now.
        for r, t in zip(results, self.team):
            t.proposed_history.append(r)

        if opponent.defections == 0:
            # Don't poke the bear
            return C

        return bestresult

class MetaHunter(MetaPlayer):
    """A player who uses a selection of hunters."""

    name = "Meta Hunter"
    classifier = {
        'memory_depth': float('inf'),  # Long memory
        'stochastic': False,
        'makes_use_of': set(),
        'inspects_source': False,
        'manipulates_source': False,
        'manipulates_state': False
    }

    def __init__(self):
        # Notice that we don't include the cooperator hunter, because it leads to excessive
        # defection and therefore bad performance against unforgiving strategies. We will stick
        # to hunters that use defections as cues. However, a really tangible benefit comes from
        # combining Random Hunter and Math Constant Hunter, since together they catch strategies
        # that are lightly randomized but still quite constant (the tricky/suspecious ones).
        self.team = [DefectorHunter, AlternatorHunter, RandomHunter, MathConstantHunter, CycleHunter, EventualCycleHunter]

        super(MetaHunter, self).__init__()

    @staticmethod
    def meta_strategy(results, opponent):

        # If any of the hunters smells prey, then defect!
        if D in results:
            return D

        # Tit-for-tat might seem like a better default choice, but in many cases it complicates
        # the heuristics of hunting and creates fale-positives. So go ahead and use it, but only
        # for longer histories.
        if len(opponent.history) > 100:
            return D if opponent.history[-1:] == [D] else C
        else:
            return C

class MetaMajorityMemoryOne(MetaMajority):
    """MetaMajority with the team of Memory One players"""

    name = "Meta Majority Memory One"

    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth'] <= 1]
        super(MetaMajorityMemoryOne, self).__init__(team=team)
        self.init_args = ()

class MetaWinnerMemoryOne(MetaWinner):
    """MetaWinner with the team of Memory One players"""

    name = "Meta Winner Memory One"

    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth'] <= 1]
        super(MetaWinnerMemoryOne, self).__init__(team=team)
        self.init_args = ()

class MetaMajorityFiniteMemory(MetaMajority):
    """MetaMajority with the team of Finite Memory Players"""

    name = "Meta Majority Finite Memory"
    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth']
                < float('inf')]
        super(MetaMajorityFiniteMemory, self).__init__(team=team)
        self.init_args = ()

class MetaWinnerFiniteMemory(MetaWinner):
    """MetaWinner with the team of Finite Memory Players"""

    name = "Meta Winner Finite Memory"
    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth']
                < float('inf')]
        super(MetaWinnerFiniteMemory, self).__init__(team=team)
        self.init_args = ()

class MetaMajorityLongMemory(MetaMajority):
    """MetaMajority with the team of Long (infinite) Memory Players"""

    name = "Meta Majority Long Memory"
    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth']
                == float('inf')]
        super(MetaMajorityLongMemory, self).__init__(team=team)
        self.init_args = ()

class MetaWinnerLongMemory(MetaWinner):
    """MetaWinner with the team of Long (infinite) Memory Players"""

    name = "Meta Winner Long Memory"
    def __init__(self):
        team = [s for s in ordinary_strategies if s().classifier['memory_depth']
                == float('inf')]
        super(MetaWinnerLongMemory, self).__init__(team=team)
        self.init_args = ()

class MetaMixer(MetaPlayer):
    """A player who randomly switches between a team of players.
    If no distribution is passed then the player will uniformly choose between
    sub players.

    In essence this is creating a Mixed strategy.

    Parameters

    team : list of strategy classes, optional
        Team of strategies that are to be randomly played
        If none is passed will select the ordinary strategies.
    distribution : list representing a probability distribution, optional
        This gives the distribution from which to select the players.
        If none is passed will select uniformly.
    """

    name = "Meta Mixer"

    def __init__(self, team=None, distribution=None):

        # The default is to use all strategies available, but we need to import the list
        # at runtime, since _strategies import also _this_ module before defining the list.
        if team:
            self.team = team
        else:
            # Needs to be computed manually to prevent circular dependency
            self.team = ordinary_strategies

        self.distribution = distribution

        super(MetaMixer, self).__init__()
        self.init_args = (team, distribution)

    def meta_strategy(self, results, opponent):
        """Using the numpy.random choice function to sample with weights"""
        return choice(results, p=self.distribution)


text:
#include "Graphics/GraphicsSystem.h"
#include "Graphics/IRenderer.h"
#include "Graphics/GraphicsRenderer.h"
#include "Graphics/SceneManager.h"
#include "Graphics/Light.h"
#include "Graphics/Camera.h"
#include "Assets/AssetSystem.h"
#include "Assets/Asset.h"
#include "Toolbox/Logger.h"
#include "Logic/LogicSystemEvents.h"

namespace alpha
{
    GraphicsSystem::GraphicsSystem()
        : AlphaSystem(30)
        , m_pAssets(nullptr)
        , m_pRenderer(nullptr)
        , m_pSceneManager(nullptr)
        , m_pCamera(nullptr)
        , m_fWindowWidth(1024.f)
        , m_fWindowHeight(768.f)
    { }
    GraphicsSystem::~GraphicsSystem() { }

    bool GraphicsSystem::VInitialize()
    {
        // OS specific renderer
        m_pRenderer = new GraphicsRenderer();
        if (!m_pRenderer->Initialize(m_pAssets, static_cast<int>(m_fWindowWidth), static_cast<int>(m_fWindowHeight)))
        {
            return false;
        }

        // Scene renerable manager
        m_pSceneManager = new SceneManager(m_pAssets);

        // register event handlers
        this->AddEventHandler(AEvent::GetIDFromName(Event_EntityCreated::sk_name), [this](AEvent * pEvent) { this->HandleEntityCreatedEvent(pEvent); });
        this->AddEventHandler(AEvent::GetIDFromName(Event_EntityUpdated::sk_name), [this](AEvent * pEvent) { this->HandleEntityUpdatedEvent(pEvent); });
        this->AddEventHandler(AEvent::GetIDFromName(Event_SetActiveCamera::sk_name), [this](AEvent * pEvent) { this->HandleSetActiveCameraEvent(pEvent); });

        // create a default camera for the scene
        m_pCamera = std::make_shared<Camera>(Vector3(0.f, 0.f, 20.f));

        return true;
    }

    bool GraphicsSystem::VShutdown()
    {
        if (m_pSceneManager) { delete m_pSceneManager; }

        if (m_pRenderer)
        {
            m_pRenderer->Shutdown();
            delete m_pRenderer;
        }
        return true;
    }

    void GraphicsSystem::Render()
    {
        // prepare the scene data for rendering
        m_pSceneManager->PreRender();

        // udpate the camera pre-render, so it can adjust to any game logic changes
        m_pCamera->Update(m_fWindowWidth, m_fWindowHeight);

        // XXX TODO - pass camera into scene manager so the renderables can be frustum culled ... maybe ?
        const std::vector<RenderSet *> renderables = m_pSceneManager->GetRenderData();
        const std::vector<Light *> lights = m_pSceneManager->GetLightData();

        // Prep current set of renderables
        for (auto rs : renderables)
        {
            m_pRenderer->PreRender(rs);
        }

        // Render the array of renderables from the given camera viewpoint
        m_pRenderer->Render(m_pCamera, renderables, lights);
    }

    bool GraphicsSystem::VUpdate(double currentTime, double elapsedTime)
    {
        // udpate scene manager, produces the current
        // set of objects that should be rendered in the
        // scene.
        m_pSceneManager->Update(currentTime, elapsedTime);

        // Prep current set of renderables, make sure that
        // the objects to be rendered are ready, and contain
        // and renderer specific data variables
        const std::vector<RenderSet *> renderables = m_pSceneManager->GetRenderData();
        for (auto rs : renderables)
        {
            m_pRenderer->PreRender(rs);
        }

        return m_pRenderer->Update(currentTime, elapsedTime);
    }

    void GraphicsSystem::SetAssetSystem(AssetSystem * const pAssets)
    {
        m_pAssets = pAssets;
    }

    void GraphicsSystem::HandleEntityCreatedEvent(AEvent * pEvent)
    {
        LOG("Graphics system received Event_EntityCreated");
        if (auto pEntityCreatedEvent = dynamic_cast<Event_EntityCreated *>(pEvent))
        {
            this->m_pSceneManager->Add(pEntityCreatedEvent->GetEntity());
        }
    }

    void GraphicsSystem::HandleEntityUpdatedEvent(AEvent * pEvent)
    {
        //LOG("Graphics system received Event_EntityUpdated");
        if (auto pUpdateEvent = dynamic_cast<Event_EntityUpdated *>(pEvent))
        {
            this->m_pSceneManager->Update(pUpdateEvent->GetEntity());
        }
    }

    void GraphicsSystem::HandleSetActiveCameraEvent(AEvent * pEvent)
    {
        LOG("Graphics system received Event_SetActiveCamera.");
        if (auto pSetActiveCameraEvent = dynamic_cast<Event_SetActiveCamera *>(pEvent))
        {
            this->m_pCamera->SetCameraComponent(pSetActiveCameraEvent->GetCameraComponent());
        }
    }
}


text:
package main_test

import (
	"strings" // really ../vendor/strings
	"testing"
)

func TestMsgExternal(t *testing.T) {
	if strings.Msg != "hello, world" {
		t.Fatalf("unexpected msg: %v", strings.Msg)
	}
}


text:
package com.example.test.coolweather.utility;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.example.test.coolweather.db.CoolWeatherDB;
import com.example.test.coolweather.model.City;
import com.example.test.coolweather.model.County;
import com.example.test.coolweather.model.Province;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by test on 8/12/2015.
 */
public class Utility {
    public static void handleWeatherResponse(Context context, String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONObject weatherInfo = jsonObject.getJSONObject("weatherinfo");
            String city_name = weatherInfo.getString("city");
            String weather_code = weatherInfo.getString("cityid");
            String high_temp = weatherInfo.getString("temp1");
            String low_temp = weatherInfo.getString("temp2");
            String weather_des = weatherInfo.getString("weather");
            String public_time = weatherInfo.getString("ptime");
            saveWeatherInfo(context,city_name,weather_code,
                    high_temp,low_temp,weather_des,public_time);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private static void saveWeatherInfo
            (Context context, String city_name, String weather_code,
             String high_temp, String low_temp, String weather_des, String public_time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CHINA);
        SharedPreferences.Editor editor =
                PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.putBoolean("city_seleted", true);
        editor.putString("city_name", city_name);
        editor.putString("weather_code", weather_code);
        editor.putString("high_temp", high_temp);
        editor.putString("low_temp", low_temp);
        editor.putString("weather_des", weather_des);
        editor.putString("public_time", public_time);
        editor.putString("current_date", sdf.format(new Date()));
        editor.commit();
    }

    public synchronized static boolean handleProvinceResponse
            (CoolWeatherDB coolWeatherDB,String response) {
        if (!TextUtils.isEmpty(response)) {
            String[] allProvinces = response.split(",");
            if (allProvinces != null && allProvinces.length > 0) {
                for (String p : allProvinces) {
                    String[] array = p.split("\\|");
                    Province province = new Province();
                    province.setProvince_code(array[0]);
                    province.setProvince_name(array[1]);
                    coolWeatherDB.saveProvince(province);
                }
                return true;
            }
        }
        return false;
    }

    public synchronized static boolean handleCityResponse
            (CoolWeatherDB coolWeatherDB, String response, int province_id) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCitys = response.split(",");
            if (allCitys != null && allCitys.length > 0) {
                for (String c : allCitys) {
                    City city = new City();
                    String[] array = c.split("\\|");
                    city.setCity_code(array[0]);
                    city.setCity_name(array[1]);
                    city.setProvince_id(province_id);
                    coolWeatherDB.saveCity(city);
                }
                return true;
            }
        }
        return false;
    }

    public synchronized static boolean handleCountyResponse
            (CoolWeatherDB coolWeatherDB, String response, int city_id) {
        if (!TextUtils.isEmpty(response)) {
            String[] allCountys = response.split(",");
            if (allCountys != null && allCountys.length > 0) {
                for (String co : allCountys) {
                    County county = new County();
                    String[] array = co.split("\\|");
                    county.setCounty_code(array[0]);
                    county.setCounty_name(array[1]);
                    county.setCity_id(city_id);
                    coolWeatherDB.saveCounty(county);
                }
                return true;
            }
        }
        return false;
    }
}


text:
<?php

/**
 * @namespace
 */
namespace PopTest\Validator;

use Pop\Loader\Autoloader;
use Pop\Validator\Included;

// Require the library's autoloader.
require_once __DIR__ . '/../../../src/Pop/Loader/Autoloader.php';

// Call the autoloader's bootstrap function.
Autoloader::factory()->splAutoloadRegister();

class IncludedTest extends \PHPUnit_Framework_TestCase
{

    public function testEvaluateTrue()
    {
        $v = new Included(3);
        $this->assertTrue($v->evaluate(array(1, 2, 3)));
        $v = new Included(4);
        $this->assertFalse($v->evaluate(array(1, 2, 3)));
    }

    public function testEvaluateFalse()
    {
        $v = new Included(3, null, false);
        $this->assertFalse($v->evaluate(array(1, 2, 3)));
        $v = new Included(4, null, false);
        $this->assertTrue($v->evaluate(array(1, 2, 3)));
    }

    public function testEvaluateStringTrue()
    {
        $v = new Included(3);
        $this->assertTrue($v->evaluate(123));
        $v = new Included(4);
        $this->assertFalse($v->evaluate(123));
    }

    public function testEvaluateStringFalse()
    {
        $v = new Included(3, null, false);
        $this->assertFalse($v->evaluate(123));
        $v = new Included(4, null, false);
        $this->assertTrue($v->evaluate(123));
        $v = new Included(array(4, 5), null, false);
        $this->assertTrue($v->evaluate(123));
    }

}


text:
var exists = require('101/exists')

module.exports = directInstanceOf

function directInstanceOf (val, Class) {
  if (!exists(val)) {
    return false
  }
  if (!exists(Class)) {
    throw new TypeError('`Class` is required')
  }
  return val.constructor === Class &&
    getPrototypeOf(val) === Class.prototype
}

// cross-node/browser compatible getPrototypeOf
function getPrototypeOf (val) {
  var proto
  try {
    proto = Object.getPrototypeOf(val)
  } catch (e) {
    /* eslint-disable */
    proto = val.__proto__
    /* eslint-enable */
  }
  return proto
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.ops4j.gaderian</groupId>
    <artifactId>gaderian-project</artifactId>
    <version>1.1-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <artifactId>gaderian-util</artifactId>
  <packaging>jar</packaging>
  <name>Gaderian Util</name>
  <inceptionYear>2009</inceptionYear>

  <dependencies>

    <dependency>
      <groupId>org.ops4j.gaderian</groupId>
      <artifactId>gaderian</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>org.ops4j.gaderian</groupId>
      <artifactId>gaderian-test-util</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.ops4j.gaderian</groupId>
      <artifactId>gaderian</artifactId>
      <version>${project.version}</version>
      <classifier>tests</classifier>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>

    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
    </dependency>

    <dependency>
      <groupId>org.codehaus.groovy</groupId>
      <artifactId>groovy-all</artifactId>
      <version>1.6.3</version>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>jboss</groupId>
      <artifactId>jboss-j2ee</artifactId>
      <version>4.0.2</version>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>2.5.6.SEC01</version>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
      <optional>true</optional>
    </dependency>

  </dependencies>

</project>


text:
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">

</button>

成本测算

                             项目名称*

                                 <input type="text" class="form-control" id="projectName" name="projectName" >

                             预算名称*

                                 <input type="text" class="form-control" id="budgetName" name="budgetName" >

人

材

机

                               <input type="search" name="bl.budget_tx_id" id="budgetLabourID" class="form-control" operator="eq" style="display:none;">

                                   <button type="button" class="btn btn-primary" data-btn-type="search" id="refresh" style="display:none;">查询</button>

                               <input type="search" name="be.budget_tx_id" id="budgetTxID" class="form-control" operator="eq" style="display:none;">

                                   <button type="button" class="btn btn-primary" data-btn-type="search" id="refresh" style="display:none;">查询</button>

                               <input type="search" name="bm.budget_tx_id" id="budgetMechID" class="form-control" operator="eq" style="display:none;">

                                   <button type="button" class="btn btn-primary" data-btn-type="search" id="refresh" style="display:none;">查询</button>


text:
define([
    "hr/hr",
    "utils/dialogs",
    "views/visualizations/all"
], function(hr, dialogs, allVisualizations) {
    var Visualization = hr.Model.extend({
        defaults: {
            type: null,
            eventName: null,
            configuration: {}
        },

        initialize: function() {
            Visualization.__super__.initialize.apply(this, arguments);

            this.report = this.collection.report;
        },

        // Open configuration dialogs
        configure: function() {
            var that = this;
            var visu = allVisualizations[this.get("type")];

            return dialogs.fields("Edit", [
                {
                    "title": {
                        'label': "Title",
                        'type': "text"
                    },
                    "size": {
                        'label': "Layout",
                        'type': "select",
                        'default': "small",
                        'options': {
                            'big': "Large",
                            'small': "Normal"
                        }
                    }
                },
                visu.config
            ], this.get("configuration"))
            .then(function(data) {
                that.set("configuration", data);
                return that.report.edit();
            });
        },

        // Return a configuration
        getConf: function(k, d) {
            return this.get("configuration."+k, d);
        }
    });

    return Visualization;
});


text:
package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"

	"github.com/astaxie/beego/orm"
)

type FeCategoryMaster struct {
	Id       int    `orm:"column(id);auto"`
	Name     string `orm:"column(name);size(50)"`
	ImageUrl string `orm:"column(image_url);size(500);null"`
	Priority int    `orm:"column(priority);null"`
	ParentId int    `orm:"column(parent_id);null"`
	Level    int    `orm:"column(level);null"`
}

func init() {
	orm.RegisterModel(new(FeCategoryMaster))
}

// AddFeCategoryMaster insert a new FeCategoryMaster into database and returns
// last inserted Id on success.
func AddFeCategoryMaster(m *FeCategoryMaster) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetFeCategoryMasterById retrieves FeCategoryMaster by Id. Returns error if
// Id doesn't exist
func GetFeCategoryMasterById(id int) (v *FeCategoryMaster, err error) {
	o := orm.NewOrm()
	v = &FeCategoryMaster{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllFeCategoryMaster retrieves all FeCategoryMaster matches certain condition. Returns empty list if
// no records exist
func GetAllFeCategoryMaster(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(FeCategoryMaster))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []FeCategoryMaster
	qs = qs.OrderBy(sortFields...)
	if _, err := qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateFeCategoryMaster updates FeCategoryMaster by Id and returns error if
// the record to be updated doesn't exist
func UpdateFeCategoryMasterById(m *FeCategoryMaster) (err error) {
	o := orm.NewOrm()
	v := FeCategoryMaster{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteFeCategoryMaster deletes FeCategoryMaster by Id and returns error if
// the record to be deleted doesn't exist
func DeleteFeCategoryMaster(id int) (err error) {
	o := orm.NewOrm()
	v := FeCategoryMaster{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&FeCategoryMaster{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}


text:
<?php
include 'core/init.php';
protect_page();

   include 'include/overall/all_header.php' ;

?>

 Contact Info

sagir.sagir@gmail.com

 We are in Developing mode ??

Learn more »

Photography

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

View details »

Short Films

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

View details »

Designs

Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

View details »

<?php  include 'include/overall/all_footer.php' ;   ?>