<commit_before># Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from os import getcwd, makedirs
from os.path import isdir, isfile, join
from shutil import copyfile

import click

from platformio import exception, util
from platformio.commands.platform import \
    platform_install as cli_platform_install
from platformio.ide.projectgenerator import ProjectGenerator
from platformio.managers.platform import PlatformManager

def validate_boards(ctx, param, value):  # pylint: disable=W0613
    pm = PlatformManager()
    # check installed boards
    known_boards = set([b['id'] for b in pm.get_installed_boards()])
    # if boards are not listed as installed, check registered boards
    if set(value) - known_boards:
        known_boards = set([b['id'] for b in pm.get_registered_boards()])
    unknown_boards = set(value) - known_boards
    try:
        assert not unknown_boards
        return value
    except AssertionError:
        raise click.BadParameter("%s. Please search for the board ID using "
                                 "`platformio boards` command" %
                                 ", ".join(unknown_boards))

@click.command("init", short_help="Initialize new PlatformIO based project")
@click.option(
    "--project-dir",
    "-d",
    default=getcwd,
    type=click.Path(
        exists=True,
        file_okay=False,
        dir_okay=True,
        writable=True,
        resolve_path=True))
@click.option(
    "-b", "--board", multiple=True, metavar="ID", callback=validate_boards)
@click.option(
    "--ide", type=click.Choice(ProjectGenerator.get_supported_ides()))
@click.option("--enable-auto-uploading", is_flag=True)
@click.option("--env-prefix", default="")
@click.pass_context
def cli(ctx,  # pylint: disable=R0913
        project_dir,
        board,
        ide,
        enable_auto_uploading,
        env_prefix):

    if project_dir == getcwd():
        click.secho("\nThe current working directory", fg="yellow", nl=False)
        click.secho(" %s " % project_dir, fg="cyan", nl=False)
        click.secho(
            "will be used for project.\n"
            "You can specify another project directory via\n"
            "`platformio init -d %PATH_TO_THE_PROJECT_DIR%` command.",
            fg="yellow")
        click.echo("")

    click.echo("The next files/directories have been created in %s" %
               click.style(
                   project_dir, fg="cyan"))
    click.echo("%s - Project Configuration File" %
               click.style(
                   "platformio.ini", fg="cyan"))
    click.echo("%s - Put your source files here" % click.style(
        "src", fg="cyan"))
    click.echo("%s - Put here project specific (private) libraries" %
               click.style(
                   "lib", fg="cyan"))

    init_base_project(project_dir)

    if board:
        fill_project_envs(ctx, project_dir, board, enable_auto_uploading,
                          env_prefix, ide is not None)

    if ide:
        if not board:
            board = get_first_board(project_dir)
            if board:
                board = [board]
        if not board:
            raise exception.BoardNotDefined()
        if len(board) > 1:
            click.secho(
                "Warning! You have initialised project with more than 1 board"
                " for the specified IDE.\n"
                "However, the IDE features (code autocompletion, syntax "
                "linter) have been configured for the first board '%s' from "
                "your list '%s'." % (board[0], ", ".join(board)),
                fg="yellow")
        pg = ProjectGenerator(project_dir, ide, board[0])
        pg.generate()

    click.secho(
        "\nProject has been successfully initialized!\nUseful commands:\n"
        "`platformio run` - process/build project from the current "
        "directory\n"
        "`platformio run --target upload` or `platformio run -t upload` "
        "- upload firmware to embedded board\n"
        "`platformio run --target clean` - clean project (remove compiled "
        "files)\n"
        "`platformio run --help` - additional information",
        fg="green")

def get_first_board(project_dir):
    config = util.load_project_config(project_dir)
    for section in config.sections():
        if not section.startswith("env:"):
            continue
        elif config.has_option(section, "board"):
            return config.get(section, "board")
    return None

def init_base_project(project_dir):
    if not util.is_platformio_project(project_dir):
        copyfile(
            join(util.get_source_dir(), "projectconftpl.ini"),
            join(project_dir, "platformio.ini"))

    lib_dir = join(project_dir, "lib")
    src_dir = join(project_dir, "src")
    config = util.load_project_config(project_dir)
    if config.has_option("platformio", "src_dir"):
        src_dir = join(project_dir, config.get("platformio", "src_dir"))

    for d in (src_dir, lib_dir):
        if not isdir(d):
            makedirs(d)

    init_lib_readme(lib_dir)
    init_ci_conf(project_dir)
    init_cvs_ignore(project_dir)

def init_lib_readme(lib_dir):
    if isfile(join(lib_dir, "readme.txt")):
        return
    with open(join(lib_dir, "readme.txt"), "w") as f:
        f.write("""
This directory is intended for the project specific (private) libraries.
PlatformIO will compile them to static libraries and link to executable file.

The source code of each library should be placed in separate directory, like
"lib/private_lib/[here are source files]".

For example, see how can be organized `Foo` and `Bar` libraries:

|--lib
|  |--Bar
|  |  |--docs
|  |  |--examples
|  |  |--src
|  |     |- Bar.c
|  |     |- Bar.h
|  |--Foo
|  |  |- Foo.c
|  |  |- Foo.h
|  |- readme.txt --> THIS FILE
|- platformio.ini
|--src
   |- main.c

Then in `src/main.c` you should use:

#include <Foo.h>
#include <Bar.h>

// rest H/C/CPP code

PlatformIO will find your libraries automatically, configure preprocessor's
include paths and build them.

More information about PlatformIO Library Dependency Finder
- http://docs.platformio.org/en/stable/librarymanager/ldf.html
""")

def init_ci_conf(project_dir):
    if isfile(join(project_dir, ".travis.yml")):
        return
    with open(join(project_dir, ".travis.yml"), "w") as f:
        f.write("""# Continuous Integration (CI) is the practice, in software
# engineering, of merging all developer working copies with a shared mainline
# several times a day < http://docs.platformio.org/en/stable/ci/index.html >
#
# Documentation:
#
# * Travis CI Embedded Builds with PlatformIO
#   < https://docs.travis-ci.com/user/integration/platformio/ >
#
# * PlatformIO integration with Travis CI
#   < http://docs.platformio.org/en/stable/ci/travis.html >
#
# * User Guide for `platformio ci` command
#   < http://docs.platformio.org/en/stable/userguide/cmd_ci.html >
#
#
# Please choice one of the following templates (proposed below) and uncomment
# it (remove "# " before each line) or use own configuration according to the
# Travis CI documentation (see above).
#

#
# Template #1: General project. Test it using existing `platformio.ini`.
#

# language: python
# python:
#     - "2.7"
#
# sudo: false
# cache:
#     directories:
#         - "~/.platformio"
#
# install:
#     - pip install -U platformio
#
# script:
#     - platformio run

#
# Template #2: The project is intended to by used as a library with examples
#

# language: python
# python:
#     - "2.7"
#
# sudo: false
# cache:
#     directories:
#         - "~/.platformio"
#
# env:
#     - PLATFORMIO_CI_SRC=path/to/test/file.c
#     - PLATFORMIO_CI_SRC=examples/file.ino
#     - PLATFORMIO_CI_SRC=path/to/test/directory
#
# install:
#     - pip install -U platformio
#
# script:
#     - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N
""")

def init_cvs_ignore(project_dir):
    ignore_path = join(project_dir, ".gitignore")
    default = [
        ".pioenvs\n",
        ".piolibdeps\n"
    ]
    current = []
    if isfile(ignore_path):
        with open(ignore_path) as fp:
            current = fp.readlines()
    print 13, current
    for d in default:
        if d not in current:
            current.append(d)
    with open(ignore_path, "w") as fp:
        fp.writelines(current)

def fill_project_envs(  # pylint: disable=too-many-arguments,too-many-locals
        ctx, project_dir, board_ids, enable_auto_uploading, env_prefix,
        force_download):
    installed_boards = PlatformManager().get_installed_boards()
    content = []
    used_boards = []
    used_platforms = []

    config = util.load_project_config(project_dir)
    for section in config.sections():
        if not all([section.startswith("env:"),
                    config.has_option(section, "board")]):
            continue
        used_boards.append(config.get(section, "board"))

    for id_ in board_ids:
        manifest = None
        for boards in (installed_boards,
                       PlatformManager.get_registered_boards()):
            for b in boards:
                if b['id'] == id_:
                    manifest = b
                    break
        assert manifest is not None

        used_platforms.append(manifest['platform'])
        if id_ in used_boards:
            continue

        content.append("")
        content.append("[env:%s%s]" % (env_prefix, id_))
        content.append("platform = %s" % manifest['platform'])

        # find default framework for board
        frameworks = manifest.get("frameworks")
        if frameworks:
            content.append("framework = %s" % frameworks[0])

        content.append("board = %s" % id_)
        if enable_auto_uploading:
            content.append("targets = upload")

    if force_download and used_platforms:
        _install_dependent_platforms(ctx, used_platforms)

    if not content:
        return

    with open(join(project_dir, "platformio.ini"), "a") as f:
        content.append("")
        f.write("\n".join(content))

def _install_dependent_platforms(ctx, platforms):
    installed_platforms = [
        p['name'] for p in PlatformManager().get_installed()
    ]
    if set(platforms) <= set(installed_platforms):
        return
    ctx.invoke(
        cli_platform_install,
        platforms=list(set(platforms) - set(installed_platforms)))
<commit_msg>Remove debug code<commit_after># Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from os import getcwd, makedirs
from os.path import isdir, isfile, join
from shutil import copyfile

import click

from platformio import exception, util
from platformio.commands.platform import \
    platform_install as cli_platform_install
from platformio.ide.projectgenerator import ProjectGenerator
from platformio.managers.platform import PlatformManager

def validate_boards(ctx, param, value):  # pylint: disable=W0613
    pm = PlatformManager()
    # check installed boards
    known_boards = set([b['id'] for b in pm.get_installed_boards()])
    # if boards are not listed as installed, check registered boards
    if set(value) - known_boards:
        known_boards = set([b['id'] for b in pm.get_registered_boards()])
    unknown_boards = set(value) - known_boards
    try:
        assert not unknown_boards
        return value
    except AssertionError:
        raise click.BadParameter("%s. Please search for the board ID using "
                                 "`platformio boards` command" %
                                 ", ".join(unknown_boards))

@click.command("init", short_help="Initialize new PlatformIO based project")
@click.option(
    "--project-dir",
    "-d",
    default=getcwd,
    type=click.Path(
        exists=True,
        file_okay=False,
        dir_okay=True,
        writable=True,
        resolve_path=True))
@click.option(
    "-b", "--board", multiple=True, metavar="ID", callback=validate_boards)
@click.option(
    "--ide", type=click.Choice(ProjectGenerator.get_supported_ides()))
@click.option("--enable-auto-uploading", is_flag=True)
@click.option("--env-prefix", default="")
@click.pass_context
def cli(ctx,  # pylint: disable=R0913
        project_dir,
        board,
        ide,
        enable_auto_uploading,
        env_prefix):

    if project_dir == getcwd():
        click.secho("\nThe current working directory", fg="yellow", nl=False)
        click.secho(" %s " % project_dir, fg="cyan", nl=False)
        click.secho(
            "will be used for project.\n"
            "You can specify another project directory via\n"
            "`platformio init -d %PATH_TO_THE_PROJECT_DIR%` command.",
            fg="yellow")
        click.echo("")

    click.echo("The next files/directories have been created in %s" %
               click.style(
                   project_dir, fg="cyan"))
    click.echo("%s - Project Configuration File" %
               click.style(
                   "platformio.ini", fg="cyan"))
    click.echo("%s - Put your source files here" % click.style(
        "src", fg="cyan"))
    click.echo("%s - Put here project specific (private) libraries" %
               click.style(
                   "lib", fg="cyan"))

    init_base_project(project_dir)

    if board:
        fill_project_envs(ctx, project_dir, board, enable_auto_uploading,
                          env_prefix, ide is not None)

    if ide:
        if not board:
            board = get_first_board(project_dir)
            if board:
                board = [board]
        if not board:
            raise exception.BoardNotDefined()
        if len(board) > 1:
            click.secho(
                "Warning! You have initialised project with more than 1 board"
                " for the specified IDE.\n"
                "However, the IDE features (code autocompletion, syntax "
                "linter) have been configured for the first board '%s' from "
                "your list '%s'." % (board[0], ", ".join(board)),
                fg="yellow")
        pg = ProjectGenerator(project_dir, ide, board[0])
        pg.generate()

    click.secho(
        "\nProject has been successfully initialized!\nUseful commands:\n"
        "`platformio run` - process/build project from the current "
        "directory\n"
        "`platformio run --target upload` or `platformio run -t upload` "
        "- upload firmware to embedded board\n"
        "`platformio run --target clean` - clean project (remove compiled "
        "files)\n"
        "`platformio run --help` - additional information",
        fg="green")

def get_first_board(project_dir):
    config = util.load_project_config(project_dir)
    for section in config.sections():
        if not section.startswith("env:"):
            continue
        elif config.has_option(section, "board"):
            return config.get(section, "board")
    return None

def init_base_project(project_dir):
    if not util.is_platformio_project(project_dir):
        copyfile(
            join(util.get_source_dir(), "projectconftpl.ini"),
            join(project_dir, "platformio.ini"))

    lib_dir = join(project_dir, "lib")
    src_dir = join(project_dir, "src")
    config = util.load_project_config(project_dir)
    if config.has_option("platformio", "src_dir"):
        src_dir = join(project_dir, config.get("platformio", "src_dir"))

    for d in (src_dir, lib_dir):
        if not isdir(d):
            makedirs(d)

    init_lib_readme(lib_dir)
    init_ci_conf(project_dir)
    init_cvs_ignore(project_dir)

def init_lib_readme(lib_dir):
    if isfile(join(lib_dir, "readme.txt")):
        return
    with open(join(lib_dir, "readme.txt"), "w") as f:
        f.write("""
This directory is intended for the project specific (private) libraries.
PlatformIO will compile them to static libraries and link to executable file.

The source code of each library should be placed in separate directory, like
"lib/private_lib/[here are source files]".

For example, see how can be organized `Foo` and `Bar` libraries:

|--lib
|  |--Bar
|  |  |--docs
|  |  |--examples
|  |  |--src
|  |     |- Bar.c
|  |     |- Bar.h
|  |--Foo
|  |  |- Foo.c
|  |  |- Foo.h
|  |- readme.txt --> THIS FILE
|- platformio.ini
|--src
   |- main.c

Then in `src/main.c` you should use:

#include <Foo.h>
#include <Bar.h>

// rest H/C/CPP code

PlatformIO will find your libraries automatically, configure preprocessor's
include paths and build them.

More information about PlatformIO Library Dependency Finder
- http://docs.platformio.org/en/stable/librarymanager/ldf.html
""")

def init_ci_conf(project_dir):
    if isfile(join(project_dir, ".travis.yml")):
        return
    with open(join(project_dir, ".travis.yml"), "w") as f:
        f.write("""# Continuous Integration (CI) is the practice, in software
# engineering, of merging all developer working copies with a shared mainline
# several times a day < http://docs.platformio.org/en/stable/ci/index.html >
#
# Documentation:
#
# * Travis CI Embedded Builds with PlatformIO
#   < https://docs.travis-ci.com/user/integration/platformio/ >
#
# * PlatformIO integration with Travis CI
#   < http://docs.platformio.org/en/stable/ci/travis.html >
#
# * User Guide for `platformio ci` command
#   < http://docs.platformio.org/en/stable/userguide/cmd_ci.html >
#
#
# Please choice one of the following templates (proposed below) and uncomment
# it (remove "# " before each line) or use own configuration according to the
# Travis CI documentation (see above).
#

#
# Template #1: General project. Test it using existing `platformio.ini`.
#

# language: python
# python:
#     - "2.7"
#
# sudo: false
# cache:
#     directories:
#         - "~/.platformio"
#
# install:
#     - pip install -U platformio
#
# script:
#     - platformio run

#
# Template #2: The project is intended to by used as a library with examples
#

# language: python
# python:
#     - "2.7"
#
# sudo: false
# cache:
#     directories:
#         - "~/.platformio"
#
# env:
#     - PLATFORMIO_CI_SRC=path/to/test/file.c
#     - PLATFORMIO_CI_SRC=examples/file.ino
#     - PLATFORMIO_CI_SRC=path/to/test/directory
#
# install:
#     - pip install -U platformio
#
# script:
#     - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N
""")

def init_cvs_ignore(project_dir):
    ignore_path = join(project_dir, ".gitignore")
    default = [
        ".pioenvs\n",
        ".piolibdeps\n"
    ]
    current = []
    if isfile(ignore_path):
        with open(ignore_path) as fp:
            current = fp.readlines()
    for d in default:
        if d not in current:
            current.append(d)
    with open(ignore_path, "w") as fp:
        fp.writelines(current)

def fill_project_envs(  # pylint: disable=too-many-arguments,too-many-locals
        ctx, project_dir, board_ids, enable_auto_uploading, env_prefix,
        force_download):
    installed_boards = PlatformManager().get_installed_boards()
    content = []
    used_boards = []
    used_platforms = []

    config = util.load_project_config(project_dir)
    for section in config.sections():
        if not all([section.startswith("env:"),
                    config.has_option(section, "board")]):
            continue
        used_boards.append(config.get(section, "board"))

    for id_ in board_ids:
        manifest = None
        for boards in (installed_boards,
                       PlatformManager.get_registered_boards()):
            for b in boards:
                if b['id'] == id_:
                    manifest = b
                    break
        assert manifest is not None

        used_platforms.append(manifest['platform'])
        if id_ in used_boards:
            continue

        content.append("")
        content.append("[env:%s%s]" % (env_prefix, id_))
        content.append("platform = %s" % manifest['platform'])

        # find default framework for board
        frameworks = manifest.get("frameworks")
        if frameworks:
            content.append("framework = %s" % frameworks[0])

        content.append("board = %s" % id_)
        if enable_auto_uploading:
            content.append("targets = upload")

    if force_download and used_platforms:
        _install_dependent_platforms(ctx, used_platforms)

    if not content:
        return

    with open(join(project_dir, "platformio.ini"), "a") as f:
        content.append("")
        f.write("\n".join(content))

def _install_dependent_platforms(ctx, platforms):
    installed_platforms = [
        p['name'] for p in PlatformManager().get_installed()
    ]
    if set(platforms) <= set(installed_platforms):
        return
    ctx.invoke(
        cli_platform_install,
        platforms=list(set(platforms) - set(installed_platforms)))
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This project is hosted on https://github.com/Trollhammaren/pywakeonlan
#
# Copyright (c) 2012 Remco Haszing
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# Except as contained in this notice, the name(s) of the above
# copyright holders shall not be used in advertising or otherwise
# to promote the sale, use or other dealings in this Software
# without prior written authorization.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import re
import socket

help_message = \
"""
Usage:
    %s [-i ip_address] [-p port] mac_address

  Options:
    -h              Show this help message.

    -i ip address   The broadcast ip address the magic packet should be
                    sent to.

    -p port         The port to which the package should be sent.

    mac_address     The mac address or hardware address of the computer
                    you are trying to wake.
"""

def send_magic_packet(mac_address, ip_address="255.255.255.255", port=7):
    """
    Wakes the computer with the given mac address if wake on lan is
    enabled on that host.

    Keyword arguments:
    mac_address -- the mac address of the host machine to wake
    ip_address -- the ip address of the host to send the magic packet to
            (default "255.255.255.255")
    port -- the port of the host to send the magic packet to (default 7)

    """
    hex = "[a-fA-F0-9]"
    if re.compile("^(%s{2}[:|\-]?){6}$" % hex).match(mac_address):
        regex = "%s{2}" % hex
    elif re.compile("^%s{12}$" % hex).match(mac_address):
        regex = ".."
    else:
        return False

    mac_address = re.findall(regex, mac_address)
    packet = "\xFF" * 6 +\
            "".join(map(lambda x: chr(int('0x%s' % x, 0)), mac_address)) * 16

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(packet, (ip_address, port))
    return True

def wake_multi(mac_addresses, ip_address="255.255.255.255", port=7):
    """
    Send the magic packet to multiple machines.

    Keyword arguments:
    mac_addresses -- the mac addresses of the machines to wake
    ip_address -- the ip address of the host to send the magic packet to
            (default "255.255.255.255")
    port -- the port of the host to send the magic packet to (default 7)

    """
    for mac_address in mac_addresses:
        send_magic_packet(macaddress, ip_address=ip_address, port=port)

if __name__ == "__main__":
    import sys
    args = sys.argv
    ip_address = "255.255.255.255"
    port = 7
    mac_address = ""
    for i in range(1, len(args), 2):
        if args[i] == "-i":
            ip_address = args[i + 1]
        elif args[i] == "-p":
            port = int(args[i + 1])
        elif i is len(args) - 1:
            mac_address = args[i]
        else:
            sys.exit(help_message)

    success = send_magic_packet(mac_address, ip_address=ip_address, port=port)
    print("Magic packet sent succesfully." if success else help_message)

<commit_msg>help message %s is now shown as args[0]<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This project is hosted on https://github.com/Trollhammaren/pywakeonlan
#
# Copyright (c) 2012 Remco Haszing
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# Except as contained in this notice, the name(s) of the above
# copyright holders shall not be used in advertising or otherwise
# to promote the sale, use or other dealings in this Software
# without prior written authorization.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import re
import socket

help_message = \
"""
Usage:
    %s [-i ip_address] [-p port] mac_address

  Options:
    -h              Show this help message.

    -i ip address   The broadcast ip address the magic packet should be
                    sent to.

    -p port         The port to which the package should be sent.

    mac_address     The mac address or hardware address of the computer
                    you are trying to wake.
"""

def send_magic_packet(mac_address, ip_address="255.255.255.255", port=7):
    """
    Wakes the computer with the given mac address if wake on lan is
    enabled on that host.

    Keyword arguments:
    mac_address -- the mac address of the host machine to wake
    ip_address -- the ip address of the host to send the magic packet to
            (default "255.255.255.255")
    port -- the port of the host to send the magic packet to (default 7)

    """
    hex = "[a-fA-F0-9]"
    if re.compile("^(%s{2}[:|\-]?){6}$" % hex).match(mac_address):
        regex = "%s{2}" % hex
    elif re.compile("^%s{12}$" % hex).match(mac_address):
        regex = ".."
    else:
        return False

    mac_address = re.findall(regex, mac_address)
    packet = "\xFF" * 6 +\
            "".join(map(lambda x: chr(int('0x%s' % x, 0)), mac_address)) * 16

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(packet, (ip_address, port))
    return True

def wake_multi(mac_addresses, ip_address="255.255.255.255", port=7):
    """
    Send the magic packet to multiple machines.

    Keyword arguments:
    mac_addresses -- the mac addresses of the machines to wake
    ip_address -- the ip address of the host to send the magic packet to
            (default "255.255.255.255")
    port -- the port of the host to send the magic packet to (default 7)

    """
    for mac_address in mac_addresses:
        send_magic_packet(macaddress, ip_address=ip_address, port=port)

if __name__ == "__main__":
    import sys
    args = sys.argv
    ip_address = "255.255.255.255"
    port = 7
    mac_address = ""
    for i in range(1, len(args), 2):
        if args[i] == "-i":
            ip_address = args[i + 1]
        elif args[i] == "-p":
            port = int(args[i + 1])
        elif i is len(args) - 1:
            mac_address = args[i]
        else:
            sys.exit(help_message % args[0])

    success = send_magic_packet(mac_address, ip_address=ip_address, port=port)
    print("Magic packet sent succesfully." if success else help_message % args[0])

<|endoftext|>


<commit_before>"""
Django settings for KISS project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j5e(n@lk-l(%1j@v8cm2+-u%k@s3avkw+s$xrhl#k)$6jd809o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'content',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'KISS.urls'

WSGI_APPLICATION = 'KISS.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
<commit_msg>renamed app<commit_after>"""
Django settings for KISS project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j5e(n@lk-l(%1j@v8cm2+-u%k@s3avkw+s$xrhl#k)$6jd809o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'slides',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'KISS.urls'

WSGI_APPLICATION = 'KISS.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'
<|endoftext|>


<commit_before>"""
TTYPE (MTTS) - Mud Terminal Type Standard

This module implements the TTYPE telnet protocol as per
http://tintin.sourceforge.net/mtts/. It allows the server to ask the
client about its capabilities. If the client also supports TTYPE, it
will return with information such as its name, if it supports colour
etc. If the client does not support TTYPE, this will be ignored.

All data will be stored on the protocol's protocol_flags dictionary,
under the 'TTYPE' key.
"""

# telnet option codes
TTYPE = chr(24)
IS = chr(0)
SEND = chr(1)

# terminal capabilities and their codes
MTTS = [(128, 'PROXY'),
        (64, 'SCREEN READER'),
        (32, 'OSC COLOR PALETTE'),
        (16, 'MOUSE TRACKING'),
        (8, '256 COLORS'),
        (4, 'UTF-8'),
        (2, 'VT100'),
        (1, 'ANSI')]
# some clients sends erroneous strings instead
# of capability numbers. We try to convert back.
MTTS_invert = {"PROXY": 128,
               "SCREEN COLOR PALETTE": 64,
               "OSC COLOR PALETTE": 32,
               "MOUSE TRACKING": 16,
               "256 COLORS": 8,
               "UTF-8": 4,
               "VT100": 2,
               "ANSI": 1}

class Ttype(object):
    """
    Handles ttype negotiations. Called and initiated by the
    telnet protocol.
    """
    def __init__(self, protocol):
        """
        initialize ttype by storing protocol on ourselves and calling
        the client to see if it supporst ttype.

        the ttype_step indicates how far in the data retrieval we've
        gotten.
        """
        self.ttype_step = 0
        self.protocol = protocol
        self.protocol.protocol_flags['TTYPE'] = {"init_done": False}
        # setup protocol to handle ttype initialization and negotiation
        self.protocol.negotiationMap[TTYPE] = self.do_ttype
        # ask if client will ttype, connect callback if it does.
        self.protocol.will(TTYPE).addCallbacks(self.do_ttype, self.no_ttype)

    def no_ttype(self, option):
        """
        Callback if ttype is not supported by client.
        """
        self.protocol.protocol_flags['TTYPE'] = {"init_done": True}

    def do_ttype(self, option):
        """
        Handles negotiation of the ttype protocol once the
        client has confirmed that it supports the ttype
        protocol.

        The negotiation proceeds in several steps, each returning a
        certain piece of information about the client. All data is
        stored on protocol.protocol_flags under the TTYPE key.
        """
        options = self.protocol.protocol_flags.get('TTYPE')
        if options and options.get('init_done'):
            return

        self.ttype_step += 1

        if self.ttype_step == 1:
            # set up info storage and initialize subnegotiation
            self.protocol.requestNegotiation(TTYPE, SEND)
        else:
            # receive data
            option = "".join(option).lstrip(IS)
            if self.ttype_step == 2:
                self.protocol.protocol_flags['TTYPE']['CLIENTNAME'] = option
                self.protocol.requestNegotiation(TTYPE, SEND)
            elif self.ttype_step == 3:
                self.protocol.protocol_flags['TTYPE']['TERM'] = option
                self.protocol.requestNegotiation(TTYPE, SEND)
            elif self.ttype_step == 4:
                try:
                    option = int(option.strip('MTTS '))
                except ValueError:
                    # it seems some clients don't send MTTS according to
                    # protocol specification, but instead just sends
                    # the data as plain strings. We try to convert back.
                    option = MTTS_invert.get(option.strip('MTTS ').upper())
                    if not option:
                        # no conversion possible. Give up.
                        self.protocol.protocol_flags['TTYPE']['init_done'] = True
                        return
                self.protocol.protocol_flags['TTYPE']['MTTS'] = option
                for codenum, standard in MTTS:
                    if option == 0:
                        break
                    status = option & codenum
                    self.protocol.protocol_flags['TTYPE'][standard] = status
                    #if status:
                    #    option = option % codenum
                self.protocol.protocol_flags['TTYPE']['init_done'] = True

            #print "ttype results:", self.protocol.protocol_flags['TTYPE'],id(self.protocol)
<commit_msg>Implemented better client identification in telnet TTYPE, including a long-standing reversal of DO TTYPE and WILL TTYPE which is due to a typo in the tintin++ TTYPE specification and which was only fixable by going to the original Telnet TTYPE specification from 1989. Should now correctly identify the most common clients that supports e.g. xterm256 colors.<commit_after>"""
TTYPE (MTTS) - Mud Terminal Type Standard

This module implements the TTYPE telnet protocol as per
http://tintin.sourceforge.net/mtts/. It allows the server to ask the
client about its capabilities. If the client also supports TTYPE, it
will return with information such as its name, if it supports colour
etc. If the client does not support TTYPE, this will be ignored.

All data will be stored on the protocol's protocol_flags dictionary,
under the 'TTYPE' key.
"""

# telnet option codes
TTYPE = chr(24)
IS = chr(0)
SEND = chr(1)

# terminal capabilities and their codes
MTTS = [(128, 'PROXY'),
        (64, 'SCREEN READER'),
        (32, 'OSC COLOR PALETTE'),
        (16, 'MOUSE TRACKING'),
        (8, '256 COLORS'),
        (4, 'UTF-8'),
        (2, 'VT100'),
        (1, 'ANSI')]

class Ttype(object):
    """
    Handles ttype negotiations. Called and initiated by the
    telnet protocol.
    """
    def __init__(self, protocol):
        """
        initialize ttype by storing protocol on ourselves and calling
        the client to see if it supporst ttype.

        the ttype_step indicates how far in the data retrieval we've
        gotten.
        """
        self.ttype_step = 0
        self.protocol = protocol
        self.protocol.protocol_flags['TTYPE'] = {"init_done": False}
        # is it a safe bet to assume ANSI is always supported?
        self.protocol.protocol_flags['TTYPE']['ANSI'] = True
        # setup protocol to handle ttype initialization and negotiation
        self.protocol.negotiationMap[TTYPE] = self.will_ttype
        # ask if client will ttype, connect callback if it does.
        self.protocol.do(TTYPE).addCallbacks(self.will_ttype, self.wont_ttype)

    def wont_ttype(self, option):
        """
        Callback if ttype is not supported by client.
        """
        self.protocol.protocol_flags['TTYPE']["init_done"] = True

    def will_ttype(self, option):
        """
        Handles negotiation of the ttype protocol once the
        client has confirmed that it will respond with the ttype
        protocol.

        The negotiation proceeds in several steps, each returning a
        certain piece of information about the client. All data is
        stored on protocol.protocol_flags under the TTYPE key.
        """

        options = self.protocol.protocol_flags.get('TTYPE')

        if options and options.get('init_done') or self.ttype_step > 3:
            return

        try:
            option = "".join(option).lstrip(IS)
        except TypeError:
            pass

        #print "incoming TTYPE option:", option

        if self.ttype_step == 0:
            # just start the request chain
            self.protocol.requestNegotiation(TTYPE, SEND)

        elif self.ttype_step == 1:
            # this is supposed to be the name of the client/terminal.
            # For clients not supporting the extended TTYPE
            # definition, subsequent calls will just repeat-return this.
            clientname = option.upper()
            # use name to identify support for xterm256. Many of these
            # only support after a certain version, but all support
            # it since at least 4 years. We assume recent client here for now.
            xterm256 = False
            if clientname.startswith("MUDLET"):
                # supports xterm256 stably since 1.1 (2010?)
                xterm256 = clientname.split("MUDLET",1)[1].strip() >= "1.1"
            else:
                xterm256 = (clientname.startswith("XTERM") or
                            clientname.endswith("-256COLOR") or
                            clientname in ("ATLANTIS",      # > 0.9.9.0 (aug 2009)
                                           "CMUD",          # > 3.04 (mar 2009)
                                           "KILDCLIENT",    # > 2.2.0 (sep 2005)
                                           "MUDLET",        # > beta 15 (sep 2009)
                                           "MUSHCLIENT",    # > 4.02 (apr 2007)
                                           "PUTTY"))        # > 0.58 (apr 2005)

            # all clients supporting TTYPE at all seem to support ANSI
            self.protocol.protocol_flags['TTYPE']['ANSI'] = True
            self.protocol.protocol_flags['TTYPE']['256 COLORS'] = xterm256
            self.protocol.protocol_flags['TTYPE']['CLIENTNAME'] = clientname
            self.protocol.requestNegotiation(TTYPE, SEND)

        elif self.ttype_step == 2:
            # this is a term capabilities flag
            term = option
            # identify xterm256 based on flag
            xterm256 = (term.endswith("-256color")         # Apple Terminal, old Tintin
                        or term.endswith("xterm") and      # old Tintin, Putty
                        not term.endswith("-color"))
            if xterm256:
                self.protocol.protocol_flags['TTYPE']['ANSI'] = True
                self.protocol.protocol_flags['TTYPE']['256 COLORS'] = xterm256
            self.protocol.protocol_flags['TTYPE']['TERM'] = term
            # request next information
            self.protocol.requestNegotiation(TTYPE, SEND)

        elif self.ttype_step == 3:
            # the MTTS bitstring identifying term capabilities
            if option.startswith("MTTS"):
                option = option.split(" ")[1]
                if option.isdigit():
                    # a number - determine the actual capabilities
                    option = int(option)
                    support = dict((capability, True) for bitval, capability in MTTS if option & bitval > 0)
                    self.protocol.protocol_flags['TTYPE'].update(support)
                else:
                    # some clients send erroneous MTTS as a string. Add directly.
                    self.protocol.protocol_flags['TTYPE'][option.upper()] = True

            self.protocol.protocol_flags['TTYPE']['init_done'] = True
            #print "TTYPE final:", self.protocol.protocol_flags['TTYPE']
        self.ttype_step += 1
<|endoftext|>


<commit_before>import argparse
import logging
import yara
import sys
import os

class yara(object):
  pass

def getPath(path):
  pass

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Uses yara to scan a given path for any known malware/viruses.')
  parser.add_argument('-v',version="%(prog)s 1.0",help='prints out version')
  parser.add_argument('-s',dest='inputPath',help='Scan the specified path')
  args = parser.parse_args()
  getPath(args.inputPath)
<commit_msg>Added config file reader, need to test<commit_after>import argparse
import glob
import logging
import yara
import sys
import os

yaraCfg = None #global yara Object

class yaraConfig(object):

  def __init__(self,filePath,source,
               filePaths, sources):
    self.filePath = filePath
    self.filePaths = filePaths
    self.source = source
    self.sources = sources

def getPath(path):
  pass

def checkForPath():
  pass

def loadConfig(file):
  global yaraCfg
  fPath = None
  fPaths = None
  src = None
  srcs = None

  cfgFile = open(file, 'r')
  for line in cfgFile.readlines():
    if 'Yara folderPath' in line:
      string = line.split('=')
      fPath = string[1].strip() #White space needs to be a goner

    elif 'Yara folderPaths' in line:
      string = line.split('=')
      fPaths = string[1].strip()

    elif 'Yara source' in line:
      string = line.split('=')
      src = string[1].strip()

    elif 'Yara sources' in line:
      string  = line.split('=')
      srcs = string[1].strip()

  yaraCfg = yaraConfig(fPath,fPaths,src,srcs)

  try:
    getattr(yaraCfg, yaraCfg.filePath)
    getattr(yaraCfg, yaraCfg.filePaths)
    getattr(yaraCfg, yaraCfg.source)
    getattr(yaraCfg, yaraCfg.sources)
  except Exception as e:
    print ("Missing an attribute!")
    print (e)

def bootUp():
  for file in glob.glob("config.txt"):
    if file is not None:
      loadConfig(file)
    else:
      print("Configuration file was not found! Please redownload from repo")
      exit(0)

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Uses yara to scan a given path for any known malware/viruses.')
  parser.add_argument('-v',version="%(prog)s 1.0",help='prints out version')
  parser.add_argument('-s',dest='inputPath',help='Scan the specified path')
  args = parser.parse_args()
  bootup()

<|endoftext|>


<commit_before>from .adapters import Adaptation
from .conversation import Statement, Response
from .utils.module_loading import import_module

class ChatBot(Adaptation):

    def __init__(self, name, **kwargs):
        super(ChatBot, self).__init__(**kwargs)

        kwargs["name"] = name
        self.recent_statements = []

        storage_adapter = kwargs.get("storage_adapter",
            "chatterbot.adapters.storage.JsonDatabaseAdapter"
        )

        logic_adapter = kwargs.get("logic_adapter",
            "chatterbot.adapters.logic.ClosestMatchAdapter"
        )

        io_adapter = kwargs.get("io_adapter",
            "chatterbot.adapters.io.TerminalAdapter"
        )

        PluginChooser = import_module("chatterbot.adapters.plugins.PluginChooser")
        self.plugin_chooser = PluginChooser(**kwargs)

        self.add_adapter(storage_adapter, **kwargs)
        self.add_adapter(logic_adapter, **kwargs)
        self.add_adapter(io_adapter, **kwargs)

        self.storage.set_context(self)
        self.logic.set_context(self)
        self.io.set_context(self)

    @property
    def storage(self):
        return self.storage_adapters[0]

    @property
    def io(self):
        return self.io_adapters[0]

    def get_last_statement(self):
        """
        Return the last statement that was received.
        """
        if self.recent_statements:
            return self.recent_statements[-1]
        return None

    def get_input(self):
        return self.io.process_input()

    def get_response(self, input_text):
        """
        Return the bot's response based on the input.
        """
        input_statement = Statement(input_text)

        # Applying plugin logic to see whether the chatbot should respond in this way
        plugin_response = self.plugin_chooser.choose(input_statement)

        if not plugin_response is False:
            return self.io.process_response(Statement(plugin_response))

        # If no responses exist, return the input statement
        if not self.storage.count():
            self.storage.update(input_statement)
            self.recent_statements.append(input_statement)

            # Process the response output with the IO adapter
            return self.io.process_response(input_statement)

        # Select a response to the input statement
        confidence, response = self.logic.process(input_statement)

        existing_statement = self.storage.find(input_statement.text)

        if existing_statement:
            input_statement = existing_statement

        previous_statement = self.get_last_statement()

        if previous_statement:
            input_statement.add_response(previous_statement)

        # Update the database after selecting a response
        self.storage.update(input_statement)

        self.recent_statements.append(response)

        # Process the response output with the IO adapter
        return self.io.process_response(response)

    def train(self, conversation=None, *args, **kwargs):
        """
        Train the chatbot based on input data.
        """
        from .training import Trainer

        trainer = Trainer(self.storage)

        if isinstance(conversation, str):
            corpora = list(args)
            corpora.append(conversation)

            if corpora:
                trainer.train_from_corpora(corpora)
        else:
            trainer.train_from_list(conversation)

<commit_msg>Added check for multiple logic adapters.<commit_after>from .adapters import Adaptation
from .conversation import Statement, Response
from .utils.module_loading import import_module

class ChatBot(Adaptation):

    def __init__(self, name, **kwargs):
        super(ChatBot, self).__init__(**kwargs)

        kwargs["name"] = name
        self.recent_statements = []

        storage_adapter = kwargs.get("storage_adapter",
            "chatterbot.adapters.storage.JsonDatabaseAdapter"
        )

        logic_adapter = kwargs.get("logic_adapter",
            "chatterbot.adapters.logic.ClosestMatchAdapter"
        )

        logic_adapters = kwargs.get("logic_adapters", [
            logic_adapter
        ])

        io_adapter = kwargs.get("io_adapter",
            "chatterbot.adapters.io.TerminalAdapter"
        )

        PluginChooser = import_module("chatterbot.adapters.plugins.PluginChooser")
        self.plugin_chooser = PluginChooser(**kwargs)

        self.add_adapter(storage_adapter, **kwargs)
        self.add_adapter(io_adapter, **kwargs)

        for adapter in logic_adapters:
            self.add_adapter(adapter, **kwargs)

        self.storage.set_context(self)
        self.logic.set_context(self)
        self.io.set_context(self)

    @property
    def storage(self):
        return self.storage_adapters[0]

    @property
    def io(self):
        return self.io_adapters[0]

    def get_last_statement(self):
        """
        Return the last statement that was received.
        """
        if self.recent_statements:
            return self.recent_statements[-1]
        return None

    def get_input(self):
        return self.io.process_input()

    def get_response(self, input_text):
        """
        Return the bot's response based on the input.
        """
        input_statement = Statement(input_text)

        # Applying plugin logic to see whether the chatbot should respond in this way
        plugin_response = self.plugin_chooser.choose(input_statement)

        if not plugin_response is False:
            return self.io.process_response(Statement(plugin_response))

        # If no responses exist, return the input statement
        if not self.storage.count():
            self.storage.update(input_statement)
            self.recent_statements.append(input_statement)

            # Process the response output with the IO adapter
            return self.io.process_response(input_statement)

        # Select a response to the input statement
        confidence, response = self.logic.process(input_statement)

        existing_statement = self.storage.find(input_statement.text)

        if existing_statement:
            input_statement = existing_statement

        previous_statement = self.get_last_statement()

        if previous_statement:
            input_statement.add_response(previous_statement)

        # Update the database after selecting a response
        self.storage.update(input_statement)

        self.recent_statements.append(response)

        # Process the response output with the IO adapter
        return self.io.process_response(response)

    def train(self, conversation=None, *args, **kwargs):
        """
        Train the chatbot based on input data.
        """
        from .training import Trainer

        trainer = Trainer(self.storage)

        if isinstance(conversation, str):
            corpora = list(args)
            corpora.append(conversation)

            if corpora:
                trainer.train_from_corpora(corpora)
        else:
            trainer.train_from_list(conversation)

<|endoftext|>


<commit_before># !/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import math
import traceback
from datetime import datetime

import pytz
import requests
from podgen import Media, Podcast, Person, Category

class Ximalaya():
    def __init__(self, album_id):
        self.podcast = None
        self.album_id = album_id
        self.page_size = 30
        self.album_info_url = "https://www.ximalaya.com/revision/album?albumId={}"
        self.album_list_url = "https://www.ximalaya.com/revision/play/album?albumId={}&pageNum={}&pageSize={}"
        self.detail_url = "https://mobile.ximalaya.com/v1/track/baseInfo?device=android&trackId={}"
        self.album_url = "https://www.ximalaya.com/album/{}"
        self.header = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': self.album_url.format(self.album_id),
            'Cookie': '_ga=GA1.2.1628478964.1476015684; _gat=1',
        }

    def album(self):
        album_info = requests.get(self.album_info_url.format(self.album_id), headers=self.header).content
        album_info_content = json.loads(album_info.decode('utf-8'))
        if album_info_content['ret'] == 200:
            album_info_data = album_info_content['data']

            # 初始化
            self.podcast = Podcast()
            self.podcast.name = album_info_data['mainInfo']['albumTitle']
            self.podcast.authors.append(Person("Powered by forecho", 'caizhenghai@gmail.com'))
            self.podcast.website = self.album_url.format(self.album_id)
            self.podcast.copyright = 'cc-by'
            if album_info_data['mainInfo']['richIntro']:
                self.podcast.description = album_info_data['mainInfo']['richIntro']
            else:
                self.podcast.description = self.podcast.name
            self.podcast.language = 'cn'
            self.podcast.image = album_info_data['mainInfo']['cover'].split('!')[0]
            self.podcast.feed_url = 'http://podcast.forecho.com/ximalaya/%s.rss' % self.album_id
            self.podcast.category = Category('Technology', 'Podcasting')
            self.podcast.explicit = False
            self.podcast.complete = False
            self.podcast.owner = Person("forecho", 'caizhenghai@gmail.com')
            page_num = 1
            # py2 +1
            track_total_count = math.ceil(album_info_data['tracksInfo']['trackTotalCount'] / self.page_size) + 1
            while page_num <= track_total_count:
                album_list = requests.get(self.album_list_url.format(self.album_id, page_num, self.page_size),
                                          headers=self.header).content
                album_list_content = json.loads(album_list.decode('utf-8'))
                count = len(album_list_content['data']['tracksAudioPlay'])
                for each in album_list_content['data']['tracksAudioPlay']:
                    try:
                        detail = requests.get(self.detail_url.format(each['trackId']), headers=self.header).content
                        detail_content = json.loads(detail.decode('utf-8'))
                        episode = self.podcast.add_episode()
                        episode.id = str(each['index'])
                        episode.title = each['trackName']
                        print(self.podcast.name + '=====' + each['trackName'])
                        image = each['trackCoverPath'].split('!')[0]
                        if image[-4:] == '.png' or image[-4:] == '.jpg':
                            episode.image = image
                        else:
                            episode.image = self.podcast.image
                        if 'intro' in detail_content:
                            episode.summary = detail_content['intro'].replace('\r\n', '')
                        else:
                            episode.summary = each['trackName']
                        episode.link = 'http://www.ximalaya.com%s' % each['albumUrl']
                        episode.authors = [Person("forecho", 'caizhenghai@gmail.com')]
                        episode.publication_date = self.reduction_time(detail_content['createdAt'])
                        episode.media = Media(each['src'], each['duration'])
                        episode.position = count - each['index'] + 1
                    except Exception as e:
                        print('异常:', e)
                        print('异常 URL:', 'https://www.ximalaya.com%s' % each['trackUrl'])
                        traceback.print_exc()
                # 生成文件
                # print self.podcast.rss_str()
                page_num = page_num + 1
            self.podcast.rss_file('ximalaya/%s.rss' % self.album_id, minimize=True)

    # 时间转换 参数 毫秒时间戳
    @staticmethod
    def reduction_time(time):
        timestamp = datetime.fromtimestamp(time / 1000)
        return datetime(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute,
                        tzinfo=pytz.utc)
<commit_msg>fix: 修复图片url<commit_after># !/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import math
import traceback
from datetime import datetime

import pytz
import requests
from podgen import Media, Podcast, Person, Category

class Ximalaya():
    def __init__(self, album_id):
        self.podcast = None
        self.album_id = album_id
        self.page_size = 30
        self.album_info_url = "https://www.ximalaya.com/revision/album?albumId={}"
        self.album_list_url = "https://www.ximalaya.com/revision/play/album?albumId={}&pageNum={}&pageSize={}"
        self.detail_url = "https://mobile.ximalaya.com/v1/track/baseInfo?device=android&trackId={}"
        self.album_url = "https://www.ximalaya.com/album/{}"
        self.header = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': self.album_url.format(self.album_id),
            'Cookie': '_ga=GA1.2.1628478964.1476015684; _gat=1',
        }

    def album(self):
        album_info = requests.get(self.album_info_url.format(self.album_id), headers=self.header).content
        album_info_content = json.loads(album_info.decode('utf-8'))
        if album_info_content['ret'] == 200:
            album_info_data = album_info_content['data']

            # 初始化
            self.podcast = Podcast()
            self.podcast.name = album_info_data['mainInfo']['albumTitle']
            self.podcast.authors.append(Person("Powered by forecho", 'caizhenghai@gmail.com'))
            self.podcast.website = self.album_url.format(self.album_id)
            self.podcast.copyright = 'cc-by'
            if album_info_data['mainInfo']['richIntro']:
                self.podcast.description = album_info_data['mainInfo']['richIntro']
            else:
                self.podcast.description = self.podcast.name
            self.podcast.language = 'cn'
            self.podcast.image = 'https:' + album_info_data['mainInfo']['cover'].split('!')[0]
            self.podcast.feed_url = 'http://podcast.forecho.com/ximalaya/%s.rss' % self.album_id
            self.podcast.category = Category('Technology', 'Podcasting')
            self.podcast.explicit = False
            self.podcast.complete = False
            self.podcast.owner = Person("forecho", 'caizhenghai@gmail.com')
            page_num = 1
            # py2 +1
            track_total_count = math.ceil(album_info_data['tracksInfo']['trackTotalCount'] / self.page_size) + 1
            while page_num <= track_total_count:
                album_list = requests.get(self.album_list_url.format(self.album_id, page_num, self.page_size),
                                          headers=self.header).content
                album_list_content = json.loads(album_list.decode('utf-8'))
                count = len(album_list_content['data']['tracksAudioPlay'])
                for each in album_list_content['data']['tracksAudioPlay']:
                    try:
                        detail = requests.get(self.detail_url.format(each['trackId']), headers=self.header).content
                        detail_content = json.loads(detail.decode('utf-8'))
                        episode = self.podcast.add_episode()
                        episode.id = str(each['index'])
                        episode.title = each['trackName']
                        print(self.podcast.name + '=====' + each['trackName'])
                        image = each['trackCoverPath'].split('!')[0]
                        if image[-4:] == '.png' or image[-4:] == '.jpg':
                            episode.image = 'https:' + image
                        else:
                            episode.image = self.podcast.image
                        if 'intro' in detail_content:
                            episode.summary = detail_content['intro'].replace('\r\n', '')
                        else:
                            episode.summary = each['trackName']
                        episode.link = 'http://www.ximalaya.com%s' % each['albumUrl']
                        episode.authors = [Person("forecho", 'caizhenghai@gmail.com')]
                        episode.publication_date = self.reduction_time(detail_content['createdAt'])
                        episode.media = Media(each['src'], each['duration'])
                        episode.position = count - each['index'] + 1
                    except Exception as e:
                        print('异常:', e)
                        print('异常 URL:', 'https://www.ximalaya.com%s' % each['trackUrl'])
                        traceback.print_exc()
                # 生成文件
                # print self.podcast.rss_str()
                page_num = page_num + 1
            self.podcast.rss_file('ximalaya/%s.rss' % self.album_id, minimize=True)

    # 时间转换 参数 毫秒时间戳
    @staticmethod
    def reduction_time(time):
        timestamp = datetime.fromtimestamp(time / 1000)
        return datetime(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute,
                        tzinfo=pytz.utc)
<|endoftext|>


<commit_before># Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
from os.path import dirname, join
from time import sleep

import requests

from platformio import __version__, exception, util
from platformio.managers.package import PackageManager

CORE_PACKAGES = {
    "contrib-piohome": "^2.0.0",
    "contrib-pysite": "~2.%d%d.0" % (sys.version_info[0], sys.version_info[1]),
    "tool-pioplus": "^2.0.0",
    "tool-unity": "~1.20403.0",
    "tool-scons": "~2.20501.7"
}

PIOPLUS_AUTO_UPDATES_MAX = 100

# pylint: disable=arguments-differ

class CorePackageManager(PackageManager):

    def __init__(self):
        super(CorePackageManager, self).__init__(
            join(util.get_home_dir(), "packages"), [
                "https://dl.bintray.com/platformio/dl-packages/manifest.json",
                "http%s://dl.platformio.org/packages/manifest.json" %
                ("" if sys.version_info < (2, 7, 9) else "s")
            ])

    def install(  # pylint: disable=keyword-arg-before-vararg
            self,
            name,
            requirements=None,
            *args,
            **kwargs):
        PackageManager.install(self, name, requirements, *args, **kwargs)
        self.cleanup_packages()
        return self.get_package_dir(name, requirements)

    def update(self, *args, **kwargs):
        result = PackageManager.update(self, *args, **kwargs)
        self.cleanup_packages()
        return result

    def cleanup_packages(self):
        self.cache_reset()
        best_pkg_versions = {}
        for name, requirements in CORE_PACKAGES.items():
            pkg_dir = self.get_package_dir(name, requirements)
            if not pkg_dir:
                continue
            best_pkg_versions[name] = self.load_manifest(pkg_dir)['version']
        for manifest in self.get_installed():
            if manifest['name'] not in best_pkg_versions:
                continue
            if manifest['version'] != best_pkg_versions[manifest['name']]:
                self.uninstall(manifest['__pkg_dir'], after_update=True)
        self.cache_reset()
        return True

def get_core_package_dir(name):
    if name not in CORE_PACKAGES:
        raise exception.PlatformioException("Please upgrade PIO Core")
    requirements = CORE_PACKAGES[name]
    pm = CorePackageManager()
    pkg_dir = pm.get_package_dir(name, requirements)
    if pkg_dir:
        return pkg_dir
    return pm.install(name, requirements)

def update_core_packages(only_check=False, silent=False):
    pm = CorePackageManager()
    for name, requirements in CORE_PACKAGES.items():
        pkg_dir = pm.get_package_dir(name)
        if not pkg_dir:
            continue
        if not silent or pm.outdated(pkg_dir, requirements):
            if name == "tool-pioplus" and not only_check:
                shutdown_piohome_servers()
                if "windows" in util.get_systype():
                    sleep(1)
            pm.update(name, requirements, only_check=only_check)
    return True

def shutdown_piohome_servers():
    port = 8010
    while port < 8050:
        try:
            requests.get(
                "http://127.0.0.1:%d?__shutdown__=1" % port, timeout=0.01)
        except:  # pylint: disable=bare-except
            pass
        port += 1

def pioplus_call(args, **kwargs):
    if "windows" in util.get_systype() and sys.version_info < (2, 7, 6):
        raise exception.PlatformioException(
            "PlatformIO Core Plus v%s does not run under Python version %s.\n"
            "Minimum supported version is 2.7.6, please upgrade Python.\n"
            "Python 3 is not yet supported.\n" % (__version__, sys.version))

    pioplus_path = join(get_core_package_dir("tool-pioplus"), "pioplus")
    pythonexe_path = util.get_pythonexe_path()
    os.environ['PYTHONEXEPATH'] = pythonexe_path
    os.environ['PYTHONPYSITEDIR'] = get_core_package_dir("contrib-pysite")
    os.environ['PIOCOREPYSITEDIR'] = dirname(util.get_source_dir() or "")
    os.environ['PATH'] = (os.pathsep).join(
        [dirname(pythonexe_path), os.environ['PATH']])
    util.copy_pythonpath_to_osenv()
    code = subprocess.call([pioplus_path] + args, **kwargs)

    # handle remote update request
    if code == 13:
        count_attr = "_update_count"
        try:
            count_value = getattr(pioplus_call, count_attr)
        except AttributeError:
            count_value = 0
            setattr(pioplus_call, count_attr, 1)
        count_value += 1
        setattr(pioplus_call, count_attr, count_value)
        if count_value < PIOPLUS_AUTO_UPDATES_MAX:
            update_core_packages()
            return pioplus_call(args, **kwargs)

    # handle reload request
    elif code == 14:
        return pioplus_call(args, **kwargs)

    if code != 0:
        raise exception.ReturnErrorCode(1)

    return True
<commit_msg>Update core package dependencies<commit_after># Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
from os.path import dirname, join
from time import sleep

import requests

from platformio import __version__, exception, util
from platformio.managers.package import PackageManager

CORE_PACKAGES = {
    "contrib-piohome": "^2.0.1",
    "contrib-pysite":
    "~2.%d%d.190418" % (sys.version_info[0], sys.version_info[1]),
    "tool-pioplus": "^2.1.4",
    "tool-unity": "~1.20403.0",
    "tool-scons": "~2.20501.7"
}

PIOPLUS_AUTO_UPDATES_MAX = 100

# pylint: disable=arguments-differ

class CorePackageManager(PackageManager):

    def __init__(self):
        super(CorePackageManager, self).__init__(
            join(util.get_home_dir(), "packages"), [
                "https://dl.bintray.com/platformio/dl-packages/manifest.json",
                "http%s://dl.platformio.org/packages/manifest.json" %
                ("" if sys.version_info < (2, 7, 9) else "s")
            ])

    def install(  # pylint: disable=keyword-arg-before-vararg
            self,
            name,
            requirements=None,
            *args,
            **kwargs):
        PackageManager.install(self, name, requirements, *args, **kwargs)
        self.cleanup_packages()
        return self.get_package_dir(name, requirements)

    def update(self, *args, **kwargs):
        result = PackageManager.update(self, *args, **kwargs)
        self.cleanup_packages()
        return result

    def cleanup_packages(self):
        self.cache_reset()
        best_pkg_versions = {}
        for name, requirements in CORE_PACKAGES.items():
            pkg_dir = self.get_package_dir(name, requirements)
            if not pkg_dir:
                continue
            best_pkg_versions[name] = self.load_manifest(pkg_dir)['version']
        for manifest in self.get_installed():
            if manifest['name'] not in best_pkg_versions:
                continue
            if manifest['version'] != best_pkg_versions[manifest['name']]:
                self.uninstall(manifest['__pkg_dir'], after_update=True)
        self.cache_reset()
        return True

def get_core_package_dir(name):
    if name not in CORE_PACKAGES:
        raise exception.PlatformioException("Please upgrade PIO Core")
    requirements = CORE_PACKAGES[name]
    pm = CorePackageManager()
    pkg_dir = pm.get_package_dir(name, requirements)
    if pkg_dir:
        return pkg_dir
    return pm.install(name, requirements)

def update_core_packages(only_check=False, silent=False):
    pm = CorePackageManager()
    for name, requirements in CORE_PACKAGES.items():
        pkg_dir = pm.get_package_dir(name)
        if not pkg_dir:
            continue
        if not silent or pm.outdated(pkg_dir, requirements):
            if name == "tool-pioplus" and not only_check:
                shutdown_piohome_servers()
                if "windows" in util.get_systype():
                    sleep(1)
            pm.update(name, requirements, only_check=only_check)
    return True

def shutdown_piohome_servers():
    port = 8010
    while port < 8050:
        try:
            requests.get(
                "http://127.0.0.1:%d?__shutdown__=1" % port, timeout=0.01)
        except:  # pylint: disable=bare-except
            pass
        port += 1

def pioplus_call(args, **kwargs):
    if "windows" in util.get_systype() and sys.version_info < (2, 7, 6):
        raise exception.PlatformioException(
            "PlatformIO Core Plus v%s does not run under Python version %s.\n"
            "Minimum supported version is 2.7.6, please upgrade Python.\n"
            "Python 3 is not yet supported.\n" % (__version__, sys.version))

    pioplus_path = join(get_core_package_dir("tool-pioplus"), "pioplus")
    pythonexe_path = util.get_pythonexe_path()
    os.environ['PYTHONEXEPATH'] = pythonexe_path
    os.environ['PYTHONPYSITEDIR'] = get_core_package_dir("contrib-pysite")
    os.environ['PIOCOREPYSITEDIR'] = dirname(util.get_source_dir() or "")
    os.environ['PATH'] = (os.pathsep).join(
        [dirname(pythonexe_path), os.environ['PATH']])
    util.copy_pythonpath_to_osenv()
    code = subprocess.call([pioplus_path] + args, **kwargs)

    # handle remote update request
    if code == 13:
        count_attr = "_update_count"
        try:
            count_value = getattr(pioplus_call, count_attr)
        except AttributeError:
            count_value = 0
            setattr(pioplus_call, count_attr, 1)
        count_value += 1
        setattr(pioplus_call, count_attr, count_value)
        if count_value < PIOPLUS_AUTO_UPDATES_MAX:
            update_core_packages()
            return pioplus_call(args, **kwargs)

    # handle reload request
    elif code == 14:
        return pioplus_call(args, **kwargs)

    if code != 0:
        raise exception.ReturnErrorCode(1)

    return True
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-

import pygame
import time
from scenes import scene
from scenes import intro_scene
from game_logic import helper
from game_logic import monte_carlo_player as mc

class GameScene(scene.Scene):
    """ Game scene that shows up when a game is active and running """

    def __init__(self, director, board, font, initial_turn, players, ntrials):
        scene.Scene.__init__(self, director)
        self.board = board
        self.font = font
        self.__draw_empty_board(self.board.get_dim(
        ), self.director.screen, helper.WIDTH, helper.HEIGHT)
        self.turn = initial_turn
        self.players = players
        self.trials = ntrials
        self.move = None
        self.winner = None

    def __draw_empty_board(self, board_dim, screen, width, height):
        """
        Function that takes a board dimension, a pygame display window,
        the width and height of the window and draws an empty board
        """
        screen.fill(helper.WHITE)
        for line_num in range(1, board_dim):
            # Vertical lines
            pygame.draw.line(screen, helper.BLACK, (line_num * width / board_dim, helper.HEIGHT),
                             (line_num * width / board_dim, 0), helper.LINE_WIDTH)
            # Horizontal lines
            pygame.draw.line(screen, helper.BLACK, (0, line_num * height / board_dim),
                             (width, line_num * height / board_dim), helper.LINE_WIDTH)

    def __draw_player_symbol(self, player, square_width, square_height):
        """
        Function that returns a pygame surface that contains a drawing of the symbol of the given player
        """
        player_symbol = {helper.PLAYERO: 'O', helper.PLAYERX: 'X'}
        font = pygame.font.SysFont(*self.font)
        square = pygame.Surface(
            (square_width, square_height), pygame.SRCALPHA, 32)
        square.convert_alpha()
        text = font.render(player_symbol[player], True, helper.BLACK)
        text_width, text_height = text.get_size()
        square.blit(text, ((square_width - text_width) /
                           2, (square_height - text_height) / 2))
        return square

    def on_event(self, events):
        if self.winner:
            time.sleep(1)
            scene = intro_scene.IntroScene(self.director, start_game=True)
            self.director.change_scene(scene)
            return
        if self.players[self.turn] == helper.HUMAN:
            for event in events:
                if event.type == pygame.MOUSEBUTTONUP:
                    x_coord, y_coord = pygame.mouse.get_pos()
                    row, col = helper.get_square_from_coordinates(
                        self.board.get_dim(), x_coord, y_coord)
                    if (row, col) in self.board.get_empty_squares():
                        self.move = (row, col)
        else:
            self.move = mc.mc_move(self.board, self.turn, self.trials)

    def on_update(self):
        if self.move is not None:
            self.board.move(self.move[0], self.move[1], self.turn)
            self.turn = helper.switch_player(self.turn)
            self.move = None
        self.winner = self.board.check_win()

    def on_draw(self, screen):
        # draw move
        for row, col in self.board.get_used_squares():
            tile = self.__draw_player_symbol(self.board.square(row, col), helper.WIDTH/self.board.get_dim(),
                                             helper.HEIGHT/self.board.get_dim())
            screen.blit(tile, helper.get_coordinates_from_square(
                self.board.get_dim(), row, col))
        # If there is a winner,draw winning combination
        if self.winner in [helper.PLAYERX, helper.PLAYERO]:
            color_line = (255, 0, 0)
            line_points = [helper.get_center_coordinates_from_square(
                self.board.get_dim(), *cell) for cell in self.board.winning_combination]
            pygame.draw.line(
                screen, color_line, line_points[0], line_points[2], helper.WINNING_LINE_WIDTH)
<commit_msg>Add method to restart game<commit_after># -*- encoding: utf-8 -*-

import pygame
import time
from scenes import scene
from scenes import intro_scene
from game_logic import helper
from game_logic import monte_carlo_player as mc

class GameScene(scene.Scene):
    """ Game scene that shows up when a game is active and running """

    def __init__(self, director, board, font, initial_turn, players, ntrials):
        scene.Scene.__init__(self, director)
        self.board = board
        self.font = font
        self.__draw_empty_board(self.board.get_dim(
        ), self.director.screen, helper.WIDTH, helper.HEIGHT)
        self.turn = initial_turn
        self.players = players
        self.trials = ntrials
        self.move = None
        self.winner = None

    def __draw_empty_board(self, board_dim, screen, width, height):
        """
        Function that takes a board dimension, a pygame display window,
        the width and height of the window and draws an empty board
        """
        screen.fill(helper.WHITE)
        for line_num in range(1, board_dim):
            # Vertical lines
            pygame.draw.line(screen, helper.BLACK, (line_num * width / board_dim, helper.HEIGHT),
                             (line_num * width / board_dim, 0), helper.LINE_WIDTH)
            # Horizontal lines
            pygame.draw.line(screen, helper.BLACK, (0, line_num * height / board_dim),
                             (width, line_num * height / board_dim), helper.LINE_WIDTH)

    def __draw_player_symbol(self, player, square_width, square_height):
        """
        Function that returns a pygame surface that contains a drawing of the symbol of the given player
        """
        player_symbol = {helper.PLAYERO: 'O', helper.PLAYERX: 'X'}
        font = pygame.font.SysFont(*self.font)
        square = pygame.Surface(
            (square_width, square_height), pygame.SRCALPHA, 32)
        square.convert_alpha()
        text = font.render(player_symbol[player], True, helper.BLACK)
        text_width, text_height = text.get_size()
        square.blit(text, ((square_width - text_width) /
                           2, (square_height - text_height) / 2))
        return square

    def __restart_game(self):
        time.sleep(1)
        scene = intro_scene.IntroScene(self.director, start_game=True)
        self.director.change_scene(scene)

    def on_event(self, events):
        if self.winner is not None:
            self.__restart_game()
            return
        if self.players[self.turn] == helper.HUMAN:
            for event in events:
                if event.type == pygame.MOUSEBUTTONUP:
                    x_coord, y_coord = pygame.mouse.get_pos()
                    row, col = helper.get_square_from_coordinates(
                        self.board.get_dim(), x_coord, y_coord)
                    if (row, col) in self.board.get_empty_squares():
                        self.move = (row, col)
        else:
            self.move = mc.mc_move(self.board, self.turn, self.trials)

    def on_update(self):
        if self.move is not None:
            self.board.move(self.move[0], self.move[1], self.turn)
            self.turn = helper.switch_player(self.turn)
            self.move = None
        self.winner = self.board.check_win()

    def on_draw(self, screen):
        # draw move
        for row, col in self.board.get_used_squares():
            tile = self.__draw_player_symbol(self.board.square(row, col), helper.WIDTH/self.board.get_dim(),
                                             helper.HEIGHT/self.board.get_dim())
            screen.blit(tile, helper.get_coordinates_from_square(
                self.board.get_dim(), row, col))
        # If there is a winner,draw winning combination
        if self.winner in [helper.PLAYERX, helper.PLAYERO]:
            color_line = (255, 0, 0)
            line_points = [helper.get_center_coordinates_from_square(
                self.board.get_dim(), *cell) for cell in self.board.winning_combination]
            pygame.draw.line(
                screen, color_line, line_points[0], line_points[2], helper.WINNING_LINE_WIDTH)
<|endoftext|>


<commit_before>#!/usr/local/bin/python

import argparse
import os
import wget
import re
import shutil
import logging

class ArsenalWallpaperExtractor(object):

    def __init__(self):
        self.file = ""
        self.arsenal_wallpapers_link = "http://www.arsenal.com/fanzone/wallpapers"
        self.wallpaper_directory = self._get_wallpaper_directory()
        self.latest_picture_number = self._get_latest_picture_number()

    def _get_wallpaper_directory(self):
        directory = os.path.abspath(args.dir)
        if not os.path.isdir(directory):
            os.makedirs(directory)
        return directory

    def _get_latest_picture_number(self):
        files = os.listdir(self.wallpaper_directory)
        logging.info('Current files in wallpaper directory: ' + str(files))
        picture_numbers = []
        for filename in files: # TODO: try and make this a list comprehension
            m = re.search(r'gun__(\d+)_3.jpg', filename)
            if m:
                picture_numbers.append(m.group(1))
        if not picture_numbers:
            return 0 # TODO: Still need to fix bugs for directory with no new pictures
        picture_numbers.sort(reverse=True)
        return picture_numbers[0]

    def _download_html_file(self):
        # TODO: check if file already exists
        self.file = wget.download(self.arsenal_wallpapers_link, bar=None)

    def _delete_html_file(self):
        os.remove(os.path.join(os.getcwd(), self.file))

    def _sort_by_picture_number(self, date_and_number_tuples):
        return sorted(date_and_number_tuples, key=lambda pair: pair[1])

    def _parse_html_file(self):
        with open(self.file, 'r') as f:
            file_contents = f.read()
        regex = '/assets/_files/desktops/(\w+_\d+)/gun__(\d+)_3.jpg'
        date_and_number_tuples = self._sort_by_picture_number(re.findall(regex, file_contents))
        return date_and_number_tuples

    def _get_newer_pictures(self, date_and_number_tuples):
        if date_and_number_tuples[0][1] <= self.latest_picture_number:
            print('No new pictures found!')
            return
        picture_count = 0
        for date_and_number_tuple in date_and_number_tuples:
            if date_and_number_tuples[1] > self.latest_picture_number:
                url = 'http://www.arsenal.com/assets/_files/desktops/%s/gun__%s_3.jpg' % (date_and_number_tuple)
                logging.info('Fetching image from url %s', url)
                picture_name = wget.download(url, bar=None)
                logging.info('Copying picture %s to %s ....', picture_name, self.wallpaper_directory)
                if self._not_current_directory():
                    shutil.copy(picture_name, self.wallpaper_directory)
                    os.remove(os.path.join(os.getcwd(), picture_name))
                picture_count += 1
            else:
                break
        print('%d pictures downloaded!' % picture_count)

    def _not_current_directory(self):
        return os.getcwd() != self.wallpaper_directory

    def _extract_wallpapers(self):
        self._download_html_file()
        self._get_newer_pictures(self._parse_html_file())
        self._delete_html_file()

def get_new_wallpapers():
    extractor = ArsenalWallpaperExtractor()
    extractor._extract_wallpapers()

def main():
    print 'Extracting wallpapers from arsenal.com .....'
    get_new_wallpapers()

# set logging level and log file
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', filename='wallpaper.log', level=logging.DEBUG)

# parse command line arguments
parser = argparse.ArgumentParser(description='Tool to obtain new arsenal.com wallpapers')
parser.add_argument('-d', '--dir',  required=True, help='Directory in which wallpapers will be downloaded to.')
args = parser.parse_args()

if __name__ == "__main__":
    main()
<commit_msg>Fixed couple of bugs<commit_after>#!/usr/local/bin/python

import argparse
import os
import wget
import re
import shutil
import logging

class ArsenalWallpaperExtractor(object):

    def __init__(self):
        self.file = ""
        self.arsenal_wallpapers_link = "http://www.arsenal.com/fanzone/wallpapers"
        self.wallpaper_directory = self._get_wallpaper_directory()
        self.latest_picture_number = self._get_latest_picture_number()

    def _get_wallpaper_directory(self):
        directory = os.path.abspath(args.dir)
        if not os.path.isdir(directory):
            os.makedirs(directory)
        return directory

    def _get_latest_picture_number(self):
        files = os.listdir(self.wallpaper_directory)
        logging.info('Current files in wallpaper directory: ' + str(files))
        picture_numbers = []
        for filename in files: # TODO: try and make this a list comprehension
            m = re.search(r'gun__(\d+)_3.jpg', filename)
            if m:
                picture_numbers.append(m.group(1))
        if not picture_numbers:
            return 0 # TODO: Still need to fix bugs for directory with no new pictures
        picture_numbers.sort(reverse=True)
        return picture_numbers[0]

    def _download_html_file(self):
        # TODO: check if file already exists
        self.file = wget.download(self.arsenal_wallpapers_link, bar=None)

    def _delete_html_file(self):
        os.remove(os.path.join(os.getcwd(), self.file))

    def _sort_by_picture_number(self, date_and_number_tuples):
        return sorted(date_and_number_tuples, key=lambda pair: pair[1], reverse=True)

    def _parse_html_file(self):
        with open(self.file, 'r') as f:
            file_contents = f.read()
        regex = '/assets/_files/desktops/(\w+_\d+)/gun__(\d+)_3.jpg'
        date_and_number_tuples = self._sort_by_picture_number(re.findall(regex, file_contents))
        return date_and_number_tuples

    def _get_newer_pictures(self, date_and_number_tuples):
        if date_and_number_tuples[0][1] <= self.latest_picture_number:
            print('No new pictures found!')
            return
        picture_count = 0
        for date_and_number_tuple in date_and_number_tuples:
            if date_and_number_tuple[1] > self.latest_picture_number:
                url = 'http://www.arsenal.com/assets/_files/desktops/%s/gun__%s_3.jpg' % (date_and_number_tuple)
                logging.info('Fetching image from url %s', url)
                picture_name = wget.download(url, bar=None)
                logging.info('Copying picture %s to %s ....', picture_name, self.wallpaper_directory)
                if self._not_current_directory():
                    shutil.copy(picture_name, self.wallpaper_directory)
                    os.remove(os.path.join(os.getcwd(), picture_name))
                picture_count += 1
            else:
                break
        print('%d pictures downloaded!' % picture_count)

    def _not_current_directory(self):
        return os.getcwd() != self.wallpaper_directory

    def _extract_wallpapers(self):
        self._download_html_file()
        self._get_newer_pictures(self._parse_html_file())
        self._delete_html_file()

def get_new_wallpapers():
    extractor = ArsenalWallpaperExtractor()
    extractor._extract_wallpapers()

def main():
    print 'Extracting wallpapers from arsenal.com .....'
    get_new_wallpapers()

# set logging level and log file
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', filename='wallpaper.log', level=logging.DEBUG)

# parse command line arguments
parser = argparse.ArgumentParser(description='Tool to obtain new arsenal.com wallpapers')
parser.add_argument('-d', '--dir',  required=True, help='Directory in which wallpapers will be downloaded to.')
args = parser.parse_args()

if __name__ == "__main__":
    main()
<|endoftext|>