<commit_before>import sys

import sublime

from .color_schemes import clear_color_schemes, select_color_scheme

package_name = "MarkdownEditing"

def get_ingored_packages():
    settings = sublime.load_settings("Preferences.sublime-settings")
    return settings.get("ignored_packages", [])

def save_ingored_packages(ignored_packages):
    settings = sublime.load_settings("Preferences.sublime-settings")
    settings.set("ignored_packages", ignored_packages)
    sublime.save_settings("Preferences.sublime-settings")

def disable_native_markdown_package():
    ignored_packages = get_ingored_packages()
    if "Markdown" not in ignored_packages:
        reassign_syntax(
            "Packages/Markdown/Markdown.sublime-syntax",
            "Packages/MarkdownEditing/syntaxes/Markdown.sublime-syntax",
        )
        reassign_syntax(
            "Packages/Markdown/MultiMarkdown.sublime-syntax",
            "Packages/MarkdownEditing/syntaxes/MultiMarkdown.sublime-syntax",
        )
        ignored_packages.append("Markdown")
        save_ingored_packages(ignored_packages)

def enable_native_markdown_package():
    ignored_packages = get_ingored_packages()
    if "Markdown" in ignored_packages:
        ignored_packages.remove("Markdown")
        save_ingored_packages(ignored_packages)

        def reassign():
            reassign_syntax(
                "Packages/MarkdownEditing/syntaxes/Markdown.sublime-syntax",
                "Packages/Markdown/Markdown.sublime-syntax",
            )
            reassign_syntax(
                "Packages/MarkdownEditing/syntaxes/MultiMarkdown.sublime-syntax",
                "Packages/Markdown/MultiMarkdown.sublime-syntax",
            )

        sublime.set_timeout(reassign, 100)

def reassign_syntax(current_syntax, new_syntax):
    for window in sublime.windows():
        for view in window.views():
            syntax = view.settings().get("syntax")
            if syntax and syntax == current_syntax:
                view.assign_syntax(new_syntax)

def on_after_install():
    if "package_control" in sys.modules:
        from package_control import events

        if events.install(package_name):
            # Native package causes some conflicts.
            disable_native_markdown_package()
            # Prompts to select a color scheme.
            select_color_scheme()

def on_before_uninstall():
    if "package_control" in sys.modules:
        from package_control import events

        if events.remove(package_name):
            # Native package causes some conflicts.
            enable_native_markdown_package()
            # Remove syntax specific color schemes.
            clear_color_schemes()
<commit_msg>Plugins: More robust bootstrapping trigger<commit_after>import sys

import sublime

from .color_schemes import clear_color_schemes, select_color_scheme

BOOTSTRAP_VERSION = 3.0

package_name = "MarkdownEditing"

def get_ingored_packages():
    settings = sublime.load_settings("Preferences.sublime-settings")
    return settings.get("ignored_packages") or []

def save_ingored_packages(ignored_packages):
    settings = sublime.load_settings("Preferences.sublime-settings")
    settings.set("ignored_packages", ignored_packages)
    sublime.save_settings("Preferences.sublime-settings")

def disable_native_markdown_package():
    ignored_packages = get_ingored_packages()
    if "Markdown" not in ignored_packages:
        reassign_syntax(
            "Packages/Markdown/Markdown.sublime-syntax",
            "Packages/MarkdownEditing/syntaxes/Markdown.sublime-syntax",
        )
        reassign_syntax(
            "Packages/Markdown/MultiMarkdown.sublime-syntax",
            "Packages/MarkdownEditing/syntaxes/MultiMarkdown.sublime-syntax",
        )
        ignored_packages.append("Markdown")
        save_ingored_packages(ignored_packages)

def enable_native_markdown_package():
    ignored_packages = get_ingored_packages()
    if "Markdown" in ignored_packages:
        ignored_packages.remove("Markdown")
        save_ingored_packages(ignored_packages)

        def reassign():
            reassign_syntax(
                "Packages/MarkdownEditing/syntaxes/Markdown.sublime-syntax",
                "Packages/Markdown/Markdown.sublime-syntax",
            )
            reassign_syntax(
                "Packages/MarkdownEditing/syntaxes/MultiMarkdown.sublime-syntax",
                "Packages/Markdown/MultiMarkdown.sublime-syntax",
            )

        sublime.set_timeout(reassign, 100)

def reassign_syntax(current_syntax, new_syntax):
    for window in sublime.windows():
        for view in window.views():
            syntax = view.settings().get("syntax")
            if syntax and syntax == current_syntax:
                view.assign_syntax(new_syntax)

def on_after_install():
    mde_settings = sublime.load_settings("MarkdownEditing.sublime-syntax")
    bootstrapped = mde_settings.get("bootstrapped")
    if bootstrapped is not None and bootstrapped == BOOTSTRAP_VERSION:
        return

    # Native package causes some conflicts.
    disable_native_markdown_package()
    # Prompts to select a color scheme.
    select_color_scheme()

    mde_settings.set("bootstrapped", BOOTSTRAP_VERSION)
    sublime.save_settings("MarkdownEditing.sublime-syntax")

def on_before_uninstall():
    if "package_control" in sys.modules:
        from package_control import events

        if events.remove(package_name):
            # Native package causes some conflicts.
            enable_native_markdown_package()
            # Remove syntax specific color schemes.
            clear_color_schemes()
<|endoftext|>


<commit_before>import random
from plugin import Plugin

class Eightball(Plugin):
  def help_text(self):
    return "fragen beantworten in Form: <soll/kann/darf/muss> ich * [<oder> *]"
  def on_msg(self, bot, user_nick, host, channel, message):
    keywords = ["kann ich", "darf ich", "soll ich", "muss ich"]
    if any(message.lower().startswith(k) for k in keywords):
      if "oder" in message:
        bot.send_message(channel, user_nick + ": " + random.choice(list(open('lists/alternate_answers.txt'))))
      else:
        bot.send_message(channel, user_nick + ": " + random.choice(list(open('lists/polar_answers.txt'))))
<commit_msg>Eightball questions are being answered in query as well<commit_after>import random
from plugin import Plugin

class Eightball(Plugin):
  def help_text(self):
    return "fragen beantworten in Form: <soll/kann/darf/muss> ich * [<oder> *]"

  def answer(self, bot, msg, recipient, nick=None):
    keywords = ["kann ich", "darf ich", "soll ich", "muss ich"]
    if any(msg.lower().startswith(k) for k in keywords):
      adressee = (nick + ": ") if nick else ""

      if "oder" in msg:
        bot.send_message(recipient, adressee + random.choice(list(open('lists/alternate_answers.txt'))))
      else:
        bot.send_message(recipient, adressee + random.choice(list(open('lists/polar_answers.txt'))))

  def on_msg(self, bot, user_nick, host, channel, message):
    self.answer(bot, message, channel, user_nick)

  def on_privmsg(self, bot, user_nick, host, message):
    self.answer(bot, message, user_nick)
<|endoftext|>


<commit_before>#
# Copyright (c) SAS Institute Inc.
#
# 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.
#

'''
image definitions
'''
import itertools

from xobj import xobj

from rbuild import errors
from rbuild import pluginapi
from rbuild.productstore.decorators import requiresProduct
from rbuild.pluginapi import command

DESCRIPTOR_PREFIX = 'options.'

class MissingImageDefError(errors.RbuildError):
    """Raised when we don't find an imagedef"""
    template = ("Unable to find imagedef with id '%(image)s' on %(stage)s stage"
        " of %(project)s project")
    params = ["image", "project", "stage"]

class CreateImageDefCommand(command.BaseCommand):
    help = 'Create a image defintion on a SAS App Engine'
    commands = ['imagedef']
    paramHelp = '<TYPE> <ARCH>'
    docs = {'from-file': 'Load config from file',
            'to-file': 'Write config to file',
            }

    def addLocalParameters(self, argDef):
        argDef['message'] = '-m', command.ONE_PARAM
        argDef['from-file'] = '-f', command.ONE_PARAM
        argDef['to-file'] = '-o', command.ONE_PARAM

    def runCommand(self, handle, argSet, args):
        ui = handle.ui
        rb = handle.facade.rbuilder

        message = argSet.pop('message', None)
        fromFile = argSet.pop('from-file', None)
        toFile = argSet.pop('to-file', None)

        if fromFile:
            handle.DescriptorConfig.readConfig(fromFile)

        _, type, arch = self.requireParameters(
            args, expected=['TYPE', 'ARCH'])

        imageType = [i for i in rb.getImageTypes() if i.name == type]
        if not imageType:
            raise errors.PluginError("No such image type '%s'."
                " Run `rbuild list imagetypes` to see valid image types" % type)
        imageType = imageType[0]

        if arch not in ['x86', 'x86_64']:
            raise errors.PluginError(
                "No such architecture '%s'. Valid architectures are: x86 and"
                " x86_64" % arch)

        handle.ImageDefs.create(imageType, arch, message)

        if toFile:
            handle.DescriptorConfig.writeConfig(toFile)

class DeleteImageDefsCommand(command.BaseCommand):
    help = 'Delete image definitions'
    paramHelp = '<imagedef id or name>+'

    def runCommand(self, handle, argSet, args):
        _, imagedefIds = self.requireParameters(
            args, expected=['ID'], appendExtra=True)
        for imagedefId in imagedefIds:
            handle.ImageDefs.delete(imagedefId)

class ListImageDefsCommand(command.ListCommand):
    help = 'list image definitions'
    resource = 'imagedefs'
    listFields = ('id', 'name', 'container', 'architecture')

    def _generateTypeDisplayName(i):
        try:
            if i.options.ebsBacked == 'true':
                extra = " (EBS)"
            else:
                extra = ""
        except AttributeError:  # no 'ebsBacked' attribute for non-AMI images
            extra = ""

        return i.container.displayName + extra

    listFieldMap = dict(
        id=dict(accessor=lambda i: i.id.rsplit('/')[-1]),
        container=dict(
            display_name='Type',
            accessor=_generateTypeDisplayName,
            ),
        architecture=dict(
            accessor=lambda i: i.architecture.displayName,
            ),
        )
    showFieldMap = dict(
        descriptor=dict(hidden=True),
        flavorSet=dict(
            display_name="Flavor Set",
            accessor=lambda i: i.flavorSet.displayName,
            ),
        options=dict(
            display_name="Options",
            accessor=lambda i: ''.join(
                '\n  %s: %s' % (k, getattr(i.options, k))
                for k in i.options._xobj.attributes.keys()
                if getattr(i.options, k)),
            ),
        stage=dict(
            display_name='Stages',
            accessor=lambda i: ', '.join(stage.href.rsplit('/')[-1] for stage in i.stage)
                if isinstance(i.stage, list) else i.stage.name,
            ),
        **listFieldMap
        )

class ImageDefs(pluginapi.Plugin):
    name = 'imagedefs'

    def _checkBuildDef(self, *args):
        assert len(args) == 3
        prodDef = self.handle.product

        if prodDef.platform:
            templateIter = itertools.chain(
                prodDef.getBuildTemplates(),
                prodDef.platform.getBuildTemplates(),
                )
        else:
            # It is valid for the platform to be missing (although not
            # terribly useful)
            templateIter = prodDef.getBuildTemplates()
        allowedCombinations = set(
            (bt.containerTemplateRef, bt.architectureRef, bt.flavorSetRef)
            for bt in templateIter)
        if args not in allowedCombinations:
            raise errors.PluginError(
                "Invalid combination of container template, architecture and "
                "flavor set (%s, %s, %s)" % args)
        return True

    def create(self, imageType, arch, message):
        '''
            Create an image definition

            @param imageType: type of image defintion to create
            @type imageType: rObj(image_type)
            @return: image defintion
            @rtype: rObj(...)
        '''
        dc = self.handle.DescriptorConfig
        rb = self.handle.facade.rbuilder
        pd = self.handle.product
        ps = self.handle.productStore

        descriptor = xobj.toxml(imageType.descriptor._root)
        ddata = dc.createDescriptorData(fromStream=descriptor)

        imageTypeDef = rb.getImageTypeDef(imageType.name, arch)
        containerRef = imageTypeDef.container.name
        flavorSetRef = imageTypeDef.flavorSet.name
        architectureRef = imageTypeDef.architecture.name

        self._checkBuildDef(containerRef, architectureRef, flavorSetRef)

        imageFields = {}
        for field in imageTypeDef.options._xobj.attributes:
            imageFields[field] = getattr(imageTypeDef.options, field)

        for field in ddata.getFields():
            name = field.getName()
            if name.startswith(DESCRIPTOR_PREFIX):
                name = name.replace(DESCRIPTOR_PREFIX, '')
                imageFields[name] = field.getValue()

        # FIXME: Map allowSnapshots -> vmSnapshots since the smartform and
        #        proddef differ. (RCE-2743)
        if 'allowSnapshots' in imageFields:
            imageFields['vmSnapshots'] = imageFields.pop('allowSnapshots')

        stages = [s.name for s in pd.getStages()]

        pd.addBuildDefinition(
            name=ddata.getField('displayName'),
            containerTemplateRef=containerRef,
            architectureRef=architectureRef,
            flavorSetRef=flavorSetRef,
            image=pd.imageType(None, imageFields),
            stages=stages,
            )
        with open(ps.getProductDefinitionXmlPath(), 'w') as fh:
            pd.serialize(fh, validate=True)

        if message is None:
            message = 'Add image def %s' % ddata.getField('displayName')
        ps.commit(message=message)
        ps.update()

    def delete(self, imageDefId):
        shortName = self.handle.product.getProductShortname()
        version = self.handle.product.getProductVersion()

        imageDefs = self.handle.facade.rbuilder.getImageDefs(id=imageDefId, product=shortName,
            version=version)

        if imageDefs:
            if self.handle.ui.getYn("Delete {0}?".format(imageDefs[0].name), default=False):
                imageDefs[0].delete()
        else:
            raise MissingImageError(image=imageId, project=shortName, version=version)

    def initialize(self):
        self.handle.Commands.getCommandClass('create').registerSubCommand(
            'imagedef', CreateImageDefCommand)
        self.handle.Commands.getCommandClass('list').registerSubCommand(
            'imagedefs', ListImageDefsCommand)
        self.handle.Commands.getCommandClass('delete').registerSubCommand(
            'imagedefs', DeleteImageDefsCommand)

    @requiresProduct
    def list(self):
        return self.handle.facade.rbuilder.getImageDefs(
            product=self.handle.product.getProductShortname(),
            version=self.handle.product.getProductVersion(),
            )

    def show(self, imageDefId):
        self.handle.Build.checkProductStore()
        imageDef = self.handle.facade.rbuilder.getImageDefs(
            id=imageDefId,
            product=self.handle.product.getProductShortname(),
            version=self.handle.product.getProductVersion(),
            )
        if imageDef:
            return imageDef[0]
<commit_msg>Fix showing a specific image definition<commit_after>#
# Copyright (c) SAS Institute Inc.
#
# 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.
#

'''
image definitions
'''
import itertools

from xobj import xobj

from rbuild import errors
from rbuild import pluginapi
from rbuild.productstore.decorators import requiresProduct
from rbuild.pluginapi import command

DESCRIPTOR_PREFIX = 'options.'

class MissingImageDefError(errors.RbuildError):
    """Raised when we don't find an imagedef"""
    template = ("Unable to find imagedef with id '%(image)s' on %(stage)s stage"
        " of %(project)s project")
    params = ["image", "project", "stage"]

class CreateImageDefCommand(command.BaseCommand):
    help = 'Create a image defintion on a SAS App Engine'
    commands = ['imagedef']
    paramHelp = '<TYPE> <ARCH>'
    docs = {'from-file': 'Load config from file',
            'to-file': 'Write config to file',
            }

    def addLocalParameters(self, argDef):
        argDef['message'] = '-m', command.ONE_PARAM
        argDef['from-file'] = '-f', command.ONE_PARAM
        argDef['to-file'] = '-o', command.ONE_PARAM

    def runCommand(self, handle, argSet, args):
        ui = handle.ui
        rb = handle.facade.rbuilder

        message = argSet.pop('message', None)
        fromFile = argSet.pop('from-file', None)
        toFile = argSet.pop('to-file', None)

        if fromFile:
            handle.DescriptorConfig.readConfig(fromFile)

        _, type, arch = self.requireParameters(
            args, expected=['TYPE', 'ARCH'])

        imageType = [i for i in rb.getImageTypes() if i.name == type]
        if not imageType:
            raise errors.PluginError("No such image type '%s'."
                " Run `rbuild list imagetypes` to see valid image types" % type)
        imageType = imageType[0]

        if arch not in ['x86', 'x86_64']:
            raise errors.PluginError(
                "No such architecture '%s'. Valid architectures are: x86 and"
                " x86_64" % arch)

        handle.ImageDefs.create(imageType, arch, message)

        if toFile:
            handle.DescriptorConfig.writeConfig(toFile)

class DeleteImageDefsCommand(command.BaseCommand):
    help = 'Delete image definitions'
    paramHelp = '<imagedef id or name>+'

    def runCommand(self, handle, argSet, args):
        _, imagedefIds = self.requireParameters(
            args, expected=['ID'], appendExtra=True)
        for imagedefId in imagedefIds:
            handle.ImageDefs.delete(imagedefId)

class ListImageDefsCommand(command.ListCommand):
    help = 'list image definitions'
    resource = 'imagedefs'
    listFields = ('id', 'name', 'container', 'architecture')

    def _generateTypeDisplayName(i):
        try:
            if i.options.ebsBacked == 'true':
                extra = " (EBS)"
            else:
                extra = ""
        except AttributeError:  # no 'ebsBacked' attribute for non-AMI images
            extra = ""

        return i.container.displayName + extra

    listFieldMap = dict(
        id=dict(accessor=lambda i: i.id.rsplit('/')[-1]),
        container=dict(
            display_name='Type',
            accessor=_generateTypeDisplayName,
            ),
        architecture=dict(
            accessor=lambda i: i.architecture.displayName,
            ),
        )
    showFieldMap = dict(
        descriptor=dict(hidden=True),
        flavorSet=dict(
            display_name="Flavor Set",
            accessor=lambda i: i.flavorSet.displayName,
            ),
        options=dict(
            display_name="Options",
            accessor=lambda i: ''.join(
                '\n  %s: %s' % (k, getattr(i.options, k))
                for k in i.options._xobj.attributes.keys()
                if getattr(i.options, k)),
            ),
        stage=dict(
            display_name='Stages',
            accessor=lambda i: ', '.join(stage.href.rsplit('/')[-1] for stage in i.stage)
                if isinstance(i.stage, list) else i.stage.name,
            ),
        **listFieldMap
        )

class ImageDefs(pluginapi.Plugin):
    name = 'imagedefs'

    def _checkBuildDef(self, *args):
        assert len(args) == 3
        prodDef = self.handle.product

        if prodDef.platform:
            templateIter = itertools.chain(
                prodDef.getBuildTemplates(),
                prodDef.platform.getBuildTemplates(),
                )
        else:
            # It is valid for the platform to be missing (although not
            # terribly useful)
            templateIter = prodDef.getBuildTemplates()
        allowedCombinations = set(
            (bt.containerTemplateRef, bt.architectureRef, bt.flavorSetRef)
            for bt in templateIter)
        if args not in allowedCombinations:
            raise errors.PluginError(
                "Invalid combination of container template, architecture and "
                "flavor set (%s, %s, %s)" % args)
        return True

    def create(self, imageType, arch, message):
        '''
            Create an image definition

            @param imageType: type of image defintion to create
            @type imageType: rObj(image_type)
            @return: image defintion
            @rtype: rObj(...)
        '''
        dc = self.handle.DescriptorConfig
        rb = self.handle.facade.rbuilder
        pd = self.handle.product
        ps = self.handle.productStore

        descriptor = xobj.toxml(imageType.descriptor._root)
        ddata = dc.createDescriptorData(fromStream=descriptor)

        imageTypeDef = rb.getImageTypeDef(imageType.name, arch)
        containerRef = imageTypeDef.container.name
        flavorSetRef = imageTypeDef.flavorSet.name
        architectureRef = imageTypeDef.architecture.name

        self._checkBuildDef(containerRef, architectureRef, flavorSetRef)

        imageFields = {}
        for field in imageTypeDef.options._xobj.attributes:
            imageFields[field] = getattr(imageTypeDef.options, field)

        for field in ddata.getFields():
            name = field.getName()
            if name.startswith(DESCRIPTOR_PREFIX):
                name = name.replace(DESCRIPTOR_PREFIX, '')
                imageFields[name] = field.getValue()

        # FIXME: Map allowSnapshots -> vmSnapshots since the smartform and
        #        proddef differ. (RCE-2743)
        if 'allowSnapshots' in imageFields:
            imageFields['vmSnapshots'] = imageFields.pop('allowSnapshots')

        stages = [s.name for s in pd.getStages()]

        pd.addBuildDefinition(
            name=ddata.getField('displayName'),
            containerTemplateRef=containerRef,
            architectureRef=architectureRef,
            flavorSetRef=flavorSetRef,
            image=pd.imageType(None, imageFields),
            stages=stages,
            )
        with open(ps.getProductDefinitionXmlPath(), 'w') as fh:
            pd.serialize(fh, validate=True)

        if message is None:
            message = 'Add image def %s' % ddata.getField('displayName')
        ps.commit(message=message)
        ps.update()

    def delete(self, imageDefId):
        shortName = self.handle.product.getProductShortname()
        version = self.handle.product.getProductVersion()

        imageDefs = self.handle.facade.rbuilder.getImageDefs(id=imageDefId, product=shortName,
            version=version)

        if imageDefs:
            if self.handle.ui.getYn("Delete {0}?".format(imageDefs[0].name), default=False):
                imageDefs[0].delete()
        else:
            raise MissingImageError(image=imageId, project=shortName, version=version)

    def initialize(self):
        self.handle.Commands.getCommandClass('create').registerSubCommand(
            'imagedef', CreateImageDefCommand)
        self.handle.Commands.getCommandClass('list').registerSubCommand(
            'imagedefs', ListImageDefsCommand)
        self.handle.Commands.getCommandClass('delete').registerSubCommand(
            'imagedefs', DeleteImageDefsCommand)

    @requiresProduct
    def list(self):
        return self.handle.facade.rbuilder.getImageDefs(
            product=self.handle.product.getProductShortname(),
            version=self.handle.product.getProductVersion(),
            )

    @requiresProduct
    def show(self, imageDefId):
        imageDef = self.handle.facade.rbuilder.getImageDefs(
            id=imageDefId,
            product=self.handle.product.getProductShortname(),
            version=self.handle.product.getProductVersion(),
            )
        if imageDef:
            return imageDef[0]
<|endoftext|>


<commit_before>import socket
from os import environ
from threading import Thread

import simplejson as json
from injector import inject
from flask import Request

from hal.response import Envelope
from hal.user import User

def plugin(bot):
    @bot.web.route('/talk', methods=['POST'])
    @inject(request=Request)
    def talk(request):
        room = request.form['room']
        name = request.form.get('user') or None
        if name:
            user = User(id=name, name=name, room=room)
        else:
            user = None

        message = request.form['message']
        forward(room, message, user)
        return 'ok'

    def forward(room, message, user):
        envelope = Envelope(user=user, room=room)

        if user:
            method = bot.reply
        else:
            method = bot.send

        method(envelope, message)

    try:
        address = environ['HAL_MESSENGER_UDP_ADDRESS']
    except KeyError:
        pass
    else:
        address = address.split(':')
        address = (address[0], int(address[1]))
        receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        receive_socket.bind(address)

        def loop():
            while True:
                encoded_message, address = receive_socket.recvfrom(60000)
                try:
                    message = json.loads(encoded_message)
                    room = message['room']
                    message_text = message['message']
                except Exception:
                    pass
                else:
                    forward(room, message_text, None)

        thread = Thread(target=loop)
        thread.daemon = True
        thread.start()
<commit_msg>Kill bot in case messenger thread dies<commit_after>import socket
import sys
from os import environ
from threading import Thread

import simplejson as json
from injector import inject
from flask import Request

from hal.response import Envelope
from hal.user import User

def exit_after_finished(fun, exit_code_fun=lambda error: 1 if error else 0):
    def wrapper(*args, **kwargs):
        try:
            fun(*args, **kwargs)
            error = None
        except Exception as e:
            error = e
        finally:
            exit_code = exit_code_fun(error)
            sys.exit(exit_code)

def plugin(bot):
    @bot.web.route('/talk', methods=['POST'])
    @inject(request=Request)
    def talk(request):
        room = request.form['room']
        name = request.form.get('user') or None
        if name:
            user = User(id=name, name=name, room=room)
        else:
            user = None

        message = request.form['message']
        forward(room, message, user)
        return 'ok'

    def forward(room, message, user):
        envelope = Envelope(user=user, room=room)

        if user:
            method = bot.reply
        else:
            method = bot.send

        method(envelope, message)

    try:
        address = environ['HAL_MESSENGER_UDP_ADDRESS']
    except KeyError:
        pass
    else:
        address = address.split(':')
        address = (address[0], int(address[1]))
        receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        receive_socket.bind(address)

        def loop():
            while True:
                encoded_message, address = receive_socket.recvfrom(60000)
                try:
                    message = json.loads(encoded_message)
                    room = message['room']
                    message_text = message['message']
                except Exception:
                    pass
                else:
                    forward(room, message_text, None)

        thread = Thread(target=exit_after_finished(fun=loop))
        thread.daemon = True
        thread.start()
<|endoftext|>


<commit_before>from hal.response import Envelope

def plugin(bot):
	@bot.web.route('/echo')
	def echo():
		envelope = Envelope(user = None, room = 'staff')
		bot.send(envelope, 'echo!')
		return 'ok'
<commit_msg>Introduce messenger plugin<commit_after>from injector import inject
from flask import Request

from hal.response import Envelope
from hal.user import User

def plugin(bot):
	@bot.web.route('/talk', methods = ['POST'])
	@inject(request = Request)
	def talk(request):
		room = request.form['room']
		name = request.form.get('user') or None
		if name:
			user = User(id = name, name = name, room = room)
		else:
			user = None

		message = request.form['message']
		envelope = Envelope(user = user, room = room)

		if user:
			method = bot.reply
		else:
			method = bot.send

		method(envelope, message)
		return 'ok'
<|endoftext|>


<commit_before># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class M4(AutotoolsPackage):
    """GNU M4 is an implementation of the traditional Unix macro processor."""

    homepage = "https://www.gnu.org/software/m4/m4.html"
    url      = "https://ftpmirror.gnu.org/m4/m4-1.4.18.tar.gz"

    version('1.4.18', sha256='ab2633921a5cd38e48797bf5521ad259bdc4b979078034a3b790d7fec5493fab')
    version('1.4.17', sha256='3ce725133ee552b8b4baca7837fb772940b25e81b2a9dc92537aeaf733538c9e')

    patch('gnulib-pgi.patch', when='@1.4.18')
    patch('pgi.patch', when='@1.4.17')
    # from: https://github.com/Homebrew/homebrew-core/blob/master/Formula/m4.rb
    # Patch credit to Jeremy Huddleston Sequoia <jeremyhu@apple.com>
    patch('secure_snprintf.patch', when='platform_os = highsierra')
    # https://bugzilla.redhat.com/show_bug.cgi?id=1573342
    patch('https://src.fedoraproject.org/rpms/m4/raw/5d147168d4b93f38a4833f5dd1d650ad88af5a8a/f/m4-1.4.18-glibc-change-work-around.patch', sha256='fc9b61654a3ba1a8d6cd78ce087e7c96366c290bc8d2c299f09828d793b853c8', when='@1.4.18')

    variant('sigsegv', default=True,
            description="Build the libsigsegv dependency")

    depends_on('libsigsegv', when='+sigsegv')

    build_directory = 'spack-build'

    def configure_args(self):
        spec = self.spec
        args = ['--enable-c++']

        if spec.satisfies('%clang') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%arm') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%fj') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%intel'):
            args.append('CFLAGS=-no-gcc')

        if '+sigsegv' in spec:
            args.append('--with-libsigsegv-prefix={0}'.format(
                spec['libsigsegv'].prefix))
        else:
            args.append('--without-libsigsegv-prefix')

        # http://lists.gnu.org/archive/html/bug-m4/2016-09/msg00002.html
        arch = spec.architecture
        if (arch.platform == 'darwin' and arch.os == 'sierra' and
            '%gcc' in spec):
            args.append('ac_cv_type_struct_sched_param=yes')

        return args
<commit_msg>m4: fixed macOS version identification on patch (#13623)<commit_after># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class M4(AutotoolsPackage):
    """GNU M4 is an implementation of the traditional Unix macro processor."""

    homepage = "https://www.gnu.org/software/m4/m4.html"
    url      = "https://ftpmirror.gnu.org/m4/m4-1.4.18.tar.gz"

    version('1.4.18', sha256='ab2633921a5cd38e48797bf5521ad259bdc4b979078034a3b790d7fec5493fab')
    version('1.4.17', sha256='3ce725133ee552b8b4baca7837fb772940b25e81b2a9dc92537aeaf733538c9e')

    patch('gnulib-pgi.patch', when='@1.4.18')
    patch('pgi.patch', when='@1.4.17')
    # from: https://github.com/Homebrew/homebrew-core/blob/master/Formula/m4.rb
    # Patch credit to Jeremy Huddleston Sequoia <jeremyhu@apple.com>
    patch('secure_snprintf.patch', when='os = highsierra')
    patch('secure_snprintf.patch', when='os = mojave')
    patch('secure_snprintf.patch', when='os = catalina')
    # https://bugzilla.redhat.com/show_bug.cgi?id=1573342
    patch('https://src.fedoraproject.org/rpms/m4/raw/5d147168d4b93f38a4833f5dd1d650ad88af5a8a/f/m4-1.4.18-glibc-change-work-around.patch', sha256='fc9b61654a3ba1a8d6cd78ce087e7c96366c290bc8d2c299f09828d793b853c8', when='@1.4.18')

    variant('sigsegv', default=True,
            description="Build the libsigsegv dependency")

    depends_on('libsigsegv', when='+sigsegv')

    build_directory = 'spack-build'

    def configure_args(self):
        spec = self.spec
        args = ['--enable-c++']

        if spec.satisfies('%clang') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%arm') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%fj') and not spec.satisfies('platform=darwin'):
            args.append('LDFLAGS=-rtlib=compiler-rt')

        if spec.satisfies('%intel'):
            args.append('CFLAGS=-no-gcc')

        if '+sigsegv' in spec:
            args.append('--with-libsigsegv-prefix={0}'.format(
                spec['libsigsegv'].prefix))
        else:
            args.append('--without-libsigsegv-prefix')

        # http://lists.gnu.org/archive/html/bug-m4/2016-09/msg00002.html
        arch = spec.architecture
        if (arch.platform == 'darwin' and arch.os == 'sierra' and
            '%gcc' in spec):
            args.append('ac_cv_type_struct_sched_param=yes')

        return args
<|endoftext|>


<commit_before>import numpy as np
import cv2
from extract_feature import VGG16Extractor
from poisson_disc import PoissonDiskSampler
from datetime import datetime
from bsds500 import BSDS
from sklearn.externals import joblib
import xgboost as xgb
import os.path as path

def main():
    cache_path = 'cache/'
    batch_size = 50
    feat_batch_name = '_feat.dat'
    lbl_batch_name = '_lbl.dat'
    now = datetime.now()
    vgg = VGG16Extractor()
    pds = PoissonDiskSampler(vgg.image_width, vgg.image_height, 4)
    samples = pds.get_sample()
    Xtrain, ytrain, _ = BSDS.load(which='train')
    shapes = {}
    idx = -1
    for b in xrange(int(np.ceil(Xtrain.shape[0] * 1.0 / batch_size))):
        features = []
        labels = []
        for _ in xrange(batch_size):
            idx += 1
            if idx >= Xtrain.shape[0]:
                break
            hyperimage = vgg.transform(Xtrain[idx,...])
#            print idx, ' ', hyperimage.shape
            for y in xrange(hyperimage.shape[0]):
                for x in xrange(hyperimage.shape[1]):
                    if ytrain[idx, y, x] > 0:
                        features.append(hyperimage[y,x,:])
                        labels.append(ytrain[idx,y,x])
            for s in samples:
                if ytrain[idx, s[1], s[0]] == 0:
                    features.append(hyperimage[s[1],s[0],:])
                    labels.append(ytrain[idx,s[1], s[0]])
            hyperimage = None
        print 'transforming batch ', b, ' of training set took ', (datetime.now() - now)
        features = np.asarray(features, dtype=np.float32)
        print 'batch ', b, ' features.shape: ', features.shape
        shapes[b] = features.shape
        labels = np.asarray(labels, dtype=np.float32)
        print 'batch ', b, ' labels.shape: ', labels.shape
        feat_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, feat_batch_name))), dtype='float32', mode='w+', shape=features.shape)
        lbl_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, lbl_batch_name))), dtype='float32', mode='w+', shape=labels.shape)
        feat_memmap[:] = features
        del feat_memmap
        lbl_memmap[:] = labels
        del lbl_memmap

    feat_count = 0
    feat_len = 0
    for b in shapes.keys():
        feat_count += shapes[b][0]
        feat_len = shapes[b][1]
    print 'transforming all batches of training set finished'
    print 'creating the final training set'
    now = datetime.now()
    feat_memmap = np.memmap(path.join(cache_path, feat_batch_name[1:]), dtype='float32', mode='w+', shape=(feat_count, feat_len))
    lbl_memmap = np.memmap(path.join(cache_path, lbl_batch_name[1:]), dtype='float32', mode='w+', shape=(feat_count,))
    count = 0
    for b in xrange(int(np.ceil(Xtrain.shape[0] * 1.0 / batch_size))):
        bfeat_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, feat_batch_name))), dtype='float32', mode='r', shape=shapes[b])
        blbl_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, lbl_batch_name))), dtype='float32', mode='r', shape=(shapes[b][0],))
        feat_memmap[count:count + bfeat_memmap.shape[0],:] = bfeat_memmap
        lbl_memmap[count:count + bfeat_memmap.shape[0]] = blbl_memmap
        count += shapes[b][0]
        feat_memmap.flush()
        lbl_memmap.flush()
    print 'creating the final training set took: ', (datetime.now() - now)
    print 'fianl training set size: ', feat_memmap.shape
    now = datetime.now()
    print 'starting training XGBoost regressor'
    clf = xgb.XGBRegressor(max_depth=20, nthread=24, n_estimators=150, objective='reg:logistic')
    print 'XGBoost regressor Parameters: ', clf
    clf.fit(features, labels)
    print 'training xgboost regressor took: ', (datetime.now() - now)
    print 'saving trained regressor'
    joblib.dump(clf, '../../../Models/ondisk_XGBR.pkl', compress=True)

if __name__ == '__main__':
    main()
<commit_msg>[Code] Fixed the severe bug in ondisk_baseline_classifier<commit_after>import numpy as np
import cv2
from extract_feature import VGG16Extractor
from poisson_disc import PoissonDiskSampler
from datetime import datetime
from bsds500 import BSDS
from sklearn.externals import joblib
import xgboost as xgb
import os.path as path

def main():
    cache_path = 'cachelarge/'
    batch_size = 25
    feat_batch_name = '_feat.dat'
    lbl_batch_name = '_lbl.dat'
    now = datetime.now()
    vgg = VGG16Extractor()
    pds = PoissonDiskSampler(vgg.image_width, vgg.image_height, 3)
    samples = pds.get_sample()
    Xtrain, ytrain, _ = BSDS.load(which='train')
    shapes = {}
    idx = -1
    for b in xrange(int(np.ceil(Xtrain.shape[0] * 1.0 / batch_size))):
        features = []
        labels = []
        for _ in xrange(batch_size):
            idx += 1
            if idx >= Xtrain.shape[0]:
                break
            hyperimage = vgg.transform(Xtrain[idx,...])
#            print idx, ' ', hyperimage.shape
            for y in xrange(hyperimage.shape[0]):
                for x in xrange(hyperimage.shape[1]):
                    if ytrain[idx, y, x] > 0:
                        features.append(hyperimage[y,x,:])
                        labels.append(ytrain[idx,y,x])
            for s in samples:
                if ytrain[idx, s[1], s[0]] == 0:
                    features.append(hyperimage[s[1],s[0],:])
                    labels.append(ytrain[idx,s[1], s[0]])
            hyperimage = None
        print 'transforming batch ', b, ' of training set took ', (datetime.now() - now)
        features = np.asarray(features, dtype=np.float32)
        print 'batch ', b, ' features.shape: ', features.shape
        shapes[b] = features.shape
        labels = np.asarray(labels, dtype=np.float32)
        print 'batch ', b, ' labels.shape: ', labels.shape
        feat_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, feat_batch_name))), dtype='float32', mode='w+', shape=features.shape)
        lbl_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, lbl_batch_name))), dtype='uint8', mode='w+', shape=labels.shape)
        feat_memmap[:] = features
	feat_memmap.flush()
        del feat_memmap
	del features
        lbl_memmap[:] = (labels > 0.3).astype(np.uint8)
	lbl_memmap.flush()
        del lbl_memmap
	del labels

    feat_count = 0
    feat_len = 0
    for b in shapes.keys():
        feat_count += shapes[b][0]
        feat_len = shapes[b][1]
    print 'transforming all batches of training set finished'
    print 'creating the final training set'
    now = datetime.now()
    feat_memmap = np.memmap(path.join(cache_path, feat_batch_name[1:]), dtype='float32', mode='w+', shape=(feat_count, feat_len))
    lbl_memmap = np.memmap(path.join(cache_path, lbl_batch_name[1:]), dtype='uint8', mode='w+', shape=(feat_count,))
    count = 0
    for b in xrange(int(np.ceil(Xtrain.shape[0] * 1.0 / batch_size))):
        bfeat_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, feat_batch_name))), dtype='float32', mode='r', shape=shapes[b])
        blbl_memmap = np.memmap(path.join(cache_path, str.format('%d%s' % (b, lbl_batch_name))), dtype='uint8', mode='r', shape=(shapes[b][0],))
        feat_memmap[count:count + bfeat_memmap.shape[0],:] = bfeat_memmap
        lbl_memmap[count:count + bfeat_memmap.shape[0]] = blbl_memmap
        count += shapes[b][0]
        feat_memmap.flush()
        lbl_memmap.flush()
    print 'creating the final training set took: ', (datetime.now() - now)
    print 'final training set size: ', feat_memmap.shape
    now = datetime.now()
    print 'starting training the classifier'
    clf = xgb.XGBClassifier(max_depth=10, nthread=24, n_estimators=30)
    print 'Classifier parameters: ', clf
    clf.fit(feat_memmap, lbl_memmap)
    print 'training classifier took: ', (datetime.now() - now)
    print 'saving trained classifier'
    joblib.dump(clf, '../../../Models/ondisk16_25_XGBC_d10_n30_int_th.pkl', compress=True)

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


<commit_before>##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import os
import sys

class Qt(Package):
    """Qt is a comprehensive cross-platform C++ application framework."""
    homepage = 'http://qt.io'
    url      = 'http://download.qt.io/archive/qt/5.7/5.7.0/single/qt-everywhere-opensource-src-5.7.0.tar.gz'
    list_url = 'http://download.qt.io/archive/qt/'
    list_depth = 4

    version('5.7.0',  '9a46cce61fc64c20c3ac0a0e0fa41b42')
    version('5.5.1',  '59f0216819152b77536cf660b015d784')
    version('5.4.2',  'fa1c4d819b401b267eb246a543a63ea5')
    version('5.4.0',  'e8654e4b37dd98039ba20da7a53877e6')
    version('5.3.2',  'febb001129927a70174467ecb508a682')
    version('5.2.1',  'a78408c887c04c34ce615da690e0b4c8')
    version('4.8.6',  '2edbe4d6c2eff33ef91732602f3518eb')
    version('3.3.8b', '9f05b4125cfe477cc52c9742c3c09009')

    # Add patch for compile issues with qt3 found with use in the
    # OpenSpeedShop project
    variant('krellpatch', default=False, description="Build with openspeedshop based patch.")
    variant('mesa',       default=False, description="Depend on mesa.")
    variant('gtk',        default=False, description="Build with gtkplus.")
    variant('webkit',     default=False, description="Build the Webkit extension")
    variant('examples',   default=False, description="Build examples.")
    variant('dbus',       default=False, description="Build with D-Bus support.")
    variant('phonon',     default=False, description="Build with phonon support.")

    patch('qt3krell.patch', when='@3.3.8b+krellpatch')

    # https://github.com/xboxdrv/xboxdrv/issues/188
    patch('btn_trigger_happy.patch', when='@5.7.0:')

    patch('qt4-corewlan-new-osx.patch', when='@4')
    patch('qt4-pcre-include-conflict.patch', when='@4')
    patch('qt4-el-capitan.patch', when='@4')

    # Use system openssl for security.
    depends_on("openssl")
    depends_on("glib", when='@4:')
    depends_on("gtkplus", when='+gtk')
    depends_on("libxml2")
    depends_on("zlib")
    depends_on("dbus", when='@4:+dbus')
    depends_on("libtiff")
    depends_on("libpng@1.2.57", when='@3')
    depends_on("libpng", when='@4:')
    depends_on("libmng")
    depends_on("jpeg")
    depends_on("icu4c")

    # OpenGL hardware acceleration
    depends_on("mesa", when='@4:+mesa')
    depends_on("libxcb", when=sys.platform != 'darwin')

    # Webkit
    depends_on("flex", when='+webkit', type='build')
    depends_on("bison", when='+webkit', type='build')
    depends_on("gperf", when='+webkit')
    depends_on("fontconfig", when='+webkit')

    # Multimedia
    # depends_on("gstreamer", when='+multimedia')
    # depends_on("pulse", when='+multimedia')
    # depends_on("flac", when='+multimedia')
    # depends_on("ogg", when='+multimedia')

    use_xcode = True

    def url_for_version(self, version):
        # URL keeps getting more complicated with every release
        url = self.list_url

        if version >= Version('4.0'):
            url += version.up_to(2) + '/'
        else:
            url += version.up_to(1) + '/'

        if version >= Version('4.8'):
            url += str(version) + '/'

        if version >= Version('5'):
            url += 'single/'

        url += 'qt-'

        if version >= Version('4.6'):
            url += 'everywhere-'
        elif version >= Version('2.1'):
            url += 'x11-'

        if version >= Version('4.0'):
            url += 'opensource-src-'
        elif version >= Version('3'):
            url += 'free-'

        url += str(version) + '.tar.gz'

        return url

    def setup_environment(self, spack_env, run_env):
        run_env.set('QTDIR', self.prefix)

    def setup_dependent_environment(self, spack_env, run_env, dspec):
        spack_env.set('QTDIR', self.prefix)

    def setup_dependent_package(self, module, ext_spec):
        module.qmake = Executable(join_path(self.spec.prefix.bin, 'qmake'))

    def patch(self):
        if self.spec.satisfies('@4'):
            # Fix qmake compilers in the default mkspec
            filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
                        'mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
                        'mkspecs/common/g++-base.conf')

            # Necessary to build with GCC 6 and other modern compilers
            # http://stackoverflow.com/questions/10354371/
            filter_file('(^QMAKE_CXXFLAGS .*)', r'\1 -std=gnu++98',
                        'mkspecs/common/gcc-base.conf')

            filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
                        'mkspecs/common/g++-unix.conf')
        elif self.spec.satisfies('@5:'):
            # Fix qmake compilers in the default mkspec
            filter_file('^QMAKE_COMPILER .*', 'QMAKE_COMPILER = cc',
                        'qtbase/mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
                        'qtbase/mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
                        'qtbase/mkspecs/common/g++-base.conf')

            filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
                        'qtbase/mkspecs/common/g++-unix.conf')

    @property
    def common_config_args(self):
        config_args = [
            '-prefix', self.prefix,
            '-v',
            '-opensource',
            '-opengl',
            '-release',
            '-shared',
            '-confirm-license',
            '-openssl-linked',
            '-optimized-qmake',
            '-no-openvg',
            '-no-pch',
            # NIS is deprecated in more recent glibc
            '-no-nis'
        ]

        if '~examples' in self.spec:
            config_args.extend(['-nomake', 'examples'])

        if '@4' in self.spec and '~phonon' in self.spec:
            config_args.append('-no-phonon')

        if '+dbus' in self.spec:
            config_args.append('-dbus-linked')
        else:
            config_args.append('-no-dbus')

        if '@5:' in self.spec and sys.platform == 'darwin':
            config_args.extend([
                '-no-xinput2',
                '-no-xcb-xlib',
                '-no-pulseaudio',
                '-no-alsa',
            ])

        if '@4' in self.spec and sys.platform == 'darwin':
            sdkpath = which('xcrun')('--show-sdk-path',
                                     # XXX(macos): 10.11 SDK fails to configure
                                     '--sdk', 'macosx10.9',
                                     output=str)
            config_args.extend([
                '-sdk', sdkpath.strip(),
            ])
            use_clang_platform = False
            if self.spec.compiler.name == 'clang' and \
               str(self.spec.compiler.version).endwith('-apple'):
                use_clang_platform = True
            # No one uses gcc-4.2.1 anymore; this is clang.
            if self.spec.compiler.name == 'gcc' and \
               str(self.spec.compiler.version) == '4.2.1':
                use_clang_platform = True
            if use_clang_platform:
                config_args.extend([
                    '-platform', 'unsupported/macx-clang',
                ])

        return config_args

    # Don't disable all the database drivers, but should
    # really get them into spack at some point.

    @when('@3')
    def configure(self):
        # A user reported that this was necessary to link Qt3 on ubuntu
        os.environ['LD_LIBRARY_PATH'] += os.pathsep + os.getcwd() + '/lib'
        configure('-prefix', self.prefix,
                  '-v',
                  '-thread',
                  '-shared',
                  '-release',
                  '-fast')

    @when('@4')
    def configure(self):
        configure('-fast',
                  '-{0}gtkstyle'.format('' if '+gtk' in self.spec else 'no-'),
                  '-{0}webkit'.format('' if '+webkit' in self.spec else 'no-'),
                  '-arch', str(self.spec.architecture.target),
                  *self.common_config_args)

    @when('@5.0:5.6')
    def configure(self):
        webkit_args = [] if '+webkit' in self.spec else ['-skip', 'qtwebkit']
        configure('-no-eglfs',
                  '-no-directfb',
                  '-{0}gtkstyle'.format('' if '+gtk' in self.spec else 'no-'),
                  *(webkit_args + self.common_config_args))

    @when('@5.7:')
    def configure(self):
        config_args = self.common_config_args

        if not sys.platform == 'darwin':
            config_args.extend([
                '-qt-xcb',
            ])

        if '~webkit' in self.spec:
            config_args.extend([
                '-skip', 'webengine',
            ])

        configure('-no-eglfs',
                  '-no-directfb',
                  '-{0}gtk'.format('' if '+gtk' in self.spec else 'no-'),
                  *config_args)

    def install(self, spec, prefix):
        self.configure()
        make()
        make("install")
<commit_msg>Fix for qt3 specific qt build (#3063)<commit_after>##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import os
import sys

class Qt(Package):
    """Qt is a comprehensive cross-platform C++ application framework."""
    homepage = 'http://qt.io'
    url      = 'http://download.qt.io/archive/qt/5.7/5.7.0/single/qt-everywhere-opensource-src-5.7.0.tar.gz'
    list_url = 'http://download.qt.io/archive/qt/'
    list_depth = 4

    version('5.7.0',  '9a46cce61fc64c20c3ac0a0e0fa41b42')
    version('5.5.1',  '59f0216819152b77536cf660b015d784')
    version('5.4.2',  'fa1c4d819b401b267eb246a543a63ea5')
    version('5.4.0',  'e8654e4b37dd98039ba20da7a53877e6')
    version('5.3.2',  'febb001129927a70174467ecb508a682')
    version('5.2.1',  'a78408c887c04c34ce615da690e0b4c8')
    version('4.8.6',  '2edbe4d6c2eff33ef91732602f3518eb')
    version('3.3.8b', '9f05b4125cfe477cc52c9742c3c09009')

    # Add patch for compile issues with qt3 found with use in the
    # OpenSpeedShop project
    variant('krellpatch', default=False, description="Build with openspeedshop based patch.")
    variant('mesa',       default=False, description="Depend on mesa.")
    variant('gtk',        default=False, description="Build with gtkplus.")
    variant('webkit',     default=False, description="Build the Webkit extension")
    variant('examples',   default=False, description="Build examples.")
    variant('dbus',       default=False, description="Build with D-Bus support.")
    variant('phonon',     default=False, description="Build with phonon support.")

    patch('qt3krell.patch', when='@3.3.8b+krellpatch')

    # https://github.com/xboxdrv/xboxdrv/issues/188
    patch('btn_trigger_happy.patch', when='@5.7.0:')

    patch('qt4-corewlan-new-osx.patch', when='@4')
    patch('qt4-pcre-include-conflict.patch', when='@4')
    patch('qt4-el-capitan.patch', when='@4')

    # Use system openssl for security.
    depends_on("openssl")
    depends_on("glib", when='@4:')
    depends_on("gtkplus", when='+gtk')
    depends_on("libxml2")
    depends_on("zlib")
    depends_on("dbus", when='@4:+dbus')
    depends_on("libtiff")
    depends_on("libpng@1.2.57", when='@3')
    depends_on("libpng", when='@4:')
    depends_on("libmng")
    depends_on("jpeg")
    depends_on("icu4c")

    # OpenGL hardware acceleration
    depends_on("mesa", when='@4:+mesa')
    depends_on("libxcb", when=sys.platform != 'darwin')

    # Webkit
    depends_on("flex", when='+webkit', type='build')
    depends_on("bison", when='+webkit', type='build')
    depends_on("gperf", when='+webkit')
    depends_on("fontconfig", when='+webkit')

    # Multimedia
    # depends_on("gstreamer", when='+multimedia')
    # depends_on("pulse", when='+multimedia')
    # depends_on("flac", when='+multimedia')
    # depends_on("ogg", when='+multimedia')

    use_xcode = True

    def url_for_version(self, version):
        # URL keeps getting more complicated with every release
        url = self.list_url

        if version >= Version('4.0'):
            url += version.up_to(2) + '/'
        else:
            url += version.up_to(1) + '/'

        if version >= Version('4.8'):
            url += str(version) + '/'

        if version >= Version('5'):
            url += 'single/'

        url += 'qt-'

        if version >= Version('4.6'):
            url += 'everywhere-'
        elif version >= Version('2.1'):
            url += 'x11-'

        if version >= Version('4.0'):
            url += 'opensource-src-'
        elif version >= Version('3'):
            url += 'free-'

        url += str(version) + '.tar.gz'

        return url

    def setup_environment(self, spack_env, run_env):
        run_env.set('QTDIR', self.prefix)

    def setup_dependent_environment(self, spack_env, run_env, dspec):
        spack_env.set('QTDIR', self.prefix)

    def setup_dependent_package(self, module, ext_spec):
        module.qmake = Executable(join_path(self.spec.prefix.bin, 'qmake'))

    def patch(self):
        if self.spec.satisfies('@4'):
            # Fix qmake compilers in the default mkspec
            filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
                        'mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
                        'mkspecs/common/g++-base.conf')

            # Necessary to build with GCC 6 and other modern compilers
            # http://stackoverflow.com/questions/10354371/
            filter_file('(^QMAKE_CXXFLAGS .*)', r'\1 -std=gnu++98',
                        'mkspecs/common/gcc-base.conf')

            filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
                        'mkspecs/common/g++-unix.conf')
        elif self.spec.satisfies('@5:'):
            # Fix qmake compilers in the default mkspec
            filter_file('^QMAKE_COMPILER .*', 'QMAKE_COMPILER = cc',
                        'qtbase/mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
                        'qtbase/mkspecs/common/g++-base.conf')
            filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
                        'qtbase/mkspecs/common/g++-base.conf')

            filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
                        'qtbase/mkspecs/common/g++-unix.conf')

    @property
    def common_config_args(self):
        config_args = [
            '-prefix', self.prefix,
            '-v',
            '-opensource',
            '-opengl',
            '-release',
            '-shared',
            '-confirm-license',
            '-openssl-linked',
            '-optimized-qmake',
            '-no-openvg',
            '-no-pch',
            # NIS is deprecated in more recent glibc
            '-no-nis'
        ]

        if '~examples' in self.spec:
            config_args.extend(['-nomake', 'examples'])

        if '@4' in self.spec and '~phonon' in self.spec:
            config_args.append('-no-phonon')

        if '+dbus' in self.spec:
            config_args.append('-dbus-linked')
        else:
            config_args.append('-no-dbus')

        if '@5:' in self.spec and sys.platform == 'darwin':
            config_args.extend([
                '-no-xinput2',
                '-no-xcb-xlib',
                '-no-pulseaudio',
                '-no-alsa',
            ])

        if '@4' in self.spec and sys.platform == 'darwin':
            sdkpath = which('xcrun')('--show-sdk-path',
                                     # XXX(macos): 10.11 SDK fails to configure
                                     '--sdk', 'macosx10.9',
                                     output=str)
            config_args.extend([
                '-sdk', sdkpath.strip(),
            ])
            use_clang_platform = False
            if self.spec.compiler.name == 'clang' and \
               str(self.spec.compiler.version).endwith('-apple'):
                use_clang_platform = True
            # No one uses gcc-4.2.1 anymore; this is clang.
            if self.spec.compiler.name == 'gcc' and \
               str(self.spec.compiler.version) == '4.2.1':
                use_clang_platform = True
            if use_clang_platform:
                config_args.extend([
                    '-platform', 'unsupported/macx-clang',
                ])

        return config_args

    # Don't disable all the database drivers, but should
    # really get them into spack at some point.

    @when('@3')
    def configure(self):
        # A user reported that this was necessary to link Qt3 on ubuntu.
        # However, if LD_LIBRARY_PATH is not set the qt build fails, check
        # and set LD_LIBRARY_PATH if not set, update if it is set.
        if os.environ.get('LD_LIBRARY_PATH'):
            os.environ['LD_LIBRARY_PATH'] += os.pathsep + os.getcwd() + '/lib'
        else:
            os.environ['LD_LIBRARY_PATH'] = os.pathsep + os.getcwd() + '/lib'

        configure('-prefix', self.prefix,
                  '-v',
                  '-thread',
                  '-shared',
                  '-release',
                  '-fast')

    @when('@4')
    def configure(self):
        configure('-fast',
                  '-{0}gtkstyle'.format('' if '+gtk' in self.spec else 'no-'),
                  '-{0}webkit'.format('' if '+webkit' in self.spec else 'no-'),
                  '-arch', str(self.spec.architecture.target),
                  *self.common_config_args)

    @when('@5.0:5.6')
    def configure(self):
        webkit_args = [] if '+webkit' in self.spec else ['-skip', 'qtwebkit']
        configure('-no-eglfs',
                  '-no-directfb',
                  '-{0}gtkstyle'.format('' if '+gtk' in self.spec else 'no-'),
                  *(webkit_args + self.common_config_args))

    @when('@5.7:')
    def configure(self):
        config_args = self.common_config_args

        if not sys.platform == 'darwin':
            config_args.extend([
                '-qt-xcb',
            ])

        if '~webkit' in self.spec:
            config_args.extend([
                '-skip', 'webengine',
            ])

        configure('-no-eglfs',
                  '-no-directfb',
                  '-{0}gtk'.format('' if '+gtk' in self.spec else 'no-'),
                  *config_args)

    def install(self, spec, prefix):
        self.configure()
        make()
        make("install")
<|endoftext|>


<commit_before>import shelve, time, random
def main(connection, info, conf) :
    badwords = shelve.open("badwords.db", writeback=True)
    if badwords.has_key(connection.host) :
        if badwords[connection.host].has_key(info["channel"]) :
            nosay = badwords[connection.host][info["channel"]]["badwords"]
            for word in nosay :
                if word in info["message"].lower().replace(" ", "") :
                    if info["sender"] not in badwords[connection.host][info["channel"]]["users"] :
                        badwords[connection.host][info["channel"]]["users"][info["sender"]] = 0
                        badwords.sync()
                    if badwords[connection.host][info["channel"]]["users"][info["sender"]] > 0 :
                        if info["sender"] in connection.nicks.keys() :
                            target = "*!*@%s" % (connection.nicks[info["sender"]])
                        else : target = "%s*!*@*" % (info["sender"])
                        connection.rawsend("MODE %s +b %s\n" % (info["channel"], target))
                    connection.rawsend("KICK %s %s :%s\n" % (info["channel"], info["sender"], "Don't use that word!"))
                    badwords[connection.host][info["channel"]]["users"][info["sender"]] += 1
                    badwords.sync()
    badwords.close()
    args = info["message"].replace("\x01", "").split(" ")[1:]
    contextdb = shelve.open("context.db", writeback=True)
    if not contextdb.has_key(info["channel"]) and info["channel"].startswith("#") :
        contextdb[info["channel"]] = ["<%s> %s" % (info["sender"], info["message"])]
        contextdb.sync()
    elif contextdb.has_key(info["channel"]) :
        contextdb[info["channel"]].append("*%s %s" % (info["sender"], " ".join(args).replace("", "")))
        contextdb.sync()
        if len(contextdb[info["channel"]]) > 10 :
            contextdb[info["channel"]].pop(0)
            contextdb.sync()
    contextdb.close()
    seendb = shelve.open("seen.db", writeback=True)
    if not seendb.has_key("users") :
        seendb["users"] = {}
        seendb.sync()
    seendb["users"][info["sender"].lower()] = [time.time(), "*%s %s" % (info["sender"], " ".join(args).replace("", ""))]
    seendb.close()
    if args[0] in ["slaps", "punches", "stomps", "hurts", "rapes", "hits", "fucks", "smacks", "crunches", "kicks", "barfs", "forces", "force", "squishes", "bodyslams", "shoots", "compresses", "tackles"] :
        if args[1] == conf.nick or args[-1] == conf.nick :
            connection.ircsend(info["channel"], random.choice(["Oww!", "Ouch, that hurt!", "\x01ACTION curls up in fetal position\x01", "\x01ACTION slaps %s\x01" % (info["sender"]), "\x01ACTION smacks %s\x01" % (info["sender"]), "\x01ACTION kicks %s\x01" % (info["sender"])]))

<commit_msg>Added /me explodes to the list of things sonicbot says someone hurts him in a /me<commit_after>import shelve, time, random
def main(connection, info, conf) :
    badwords = shelve.open("badwords.db", writeback=True)
    if badwords.has_key(connection.host) :
        if badwords[connection.host].has_key(info["channel"]) :
            nosay = badwords[connection.host][info["channel"]]["badwords"]
            for word in nosay :
                if word in info["message"].lower().replace(" ", "") :
                    if info["sender"] not in badwords[connection.host][info["channel"]]["users"] :
                        badwords[connection.host][info["channel"]]["users"][info["sender"]] = 0
                        badwords.sync()
                    if badwords[connection.host][info["channel"]]["users"][info["sender"]] > 0 :
                        if info["sender"] in connection.nicks.keys() :
                            target = "*!*@%s" % (connection.nicks[info["sender"]])
                        else : target = "%s*!*@*" % (info["sender"])
                        connection.rawsend("MODE %s +b %s\n" % (info["channel"], target))
                    connection.rawsend("KICK %s %s :%s\n" % (info["channel"], info["sender"], "Don't use that word!"))
                    badwords[connection.host][info["channel"]]["users"][info["sender"]] += 1
                    badwords.sync()
    badwords.close()
    args = info["message"].replace("\x01", "").split(" ")[1:]
    contextdb = shelve.open("context.db", writeback=True)
    if not contextdb.has_key(info["channel"]) and info["channel"].startswith("#") :
        contextdb[info["channel"]] = ["<%s> %s" % (info["sender"], info["message"])]
        contextdb.sync()
    elif contextdb.has_key(info["channel"]) :
        contextdb[info["channel"]].append("*%s %s" % (info["sender"], " ".join(args).replace("", "")))
        contextdb.sync()
        if len(contextdb[info["channel"]]) > 10 :
            contextdb[info["channel"]].pop(0)
            contextdb.sync()
    contextdb.close()
    seendb = shelve.open("seen.db", writeback=True)
    if not seendb.has_key("users") :
        seendb["users"] = {}
        seendb.sync()
    seendb["users"][info["sender"].lower()] = [time.time(), "*%s %s" % (info["sender"], " ".join(args).replace("", ""))]
    seendb.close()
    if args[0] in ["slaps", "punches", "stomps", "hurts", "rapes", "hits", "fucks", "smacks", "crunches", "kicks", "barfs", "forces", "force", "squishes", "bodyslams", "shoots", "compresses", "tackles"] :
        if args[1] == conf.nick or args[-1] == conf.nick :
            connection.ircsend(info["channel"], random.choice(["Oww!", "Ouch, that hurt!", "\x01ACTION curls up in fetal position\x01", "\x01ACTION slaps %s\x01" % (info["sender"]), "\x01ACTION smacks %s\x01" % (info["sender"]), "\x01ACTION kicks %s\x01" % (info["sender"]), "\x01ACTION explodes\x01"]))

<|endoftext|>


<commit_before># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Z3(MakefilePackage):
    """Z3 is a theorem prover from Microsoft Research.
    It is licensed under the MIT license."""

    homepage = "https://github.com/Z3Prover/z3/wiki"
    url      = "https://github.com/Z3Prover/z3/archive/z3-4.5.0.tar.gz"

    version('4.5.0', sha256='aeae1d239c5e06ac183be7dd853775b84698db1265cb2258e5918a28372d4a0c')
    version('4.4.1', sha256='50967cca12c5c6e1612d0ccf8b6ebf5f99840a783d6cf5216336a2b59c37c0ce')
    version('4.4.0', sha256='65b72f9eb0af50949e504b47080fb3fc95f11c435633041d9a534473f3142cba')

    phases = ['bootstrap', 'build', 'install']

    variant('python', default=False, description='Enable python binding')
    depends_on('python', type=('build', 'run'))

    # Referenced: https://github.com/Z3Prover/z3/issues/1016
    patch('fix_1016_1.patch', when='@:4.4.1')
    patch('fix_1016_2.patch', when='@4.5.0')

    build_directory = 'build'

    def configure_args(self):
        spec = self.spec
        return [
            '--python' if '+python' in spec else ''
        ]

    def bootstrap(self, spec, prefix):
        options = ['--prefix={0}'.format(prefix)] + self.configure_args()
        spec['python'].command('scripts/mk_make.py', *options)
<commit_msg>configure z3+python to build python libraries in its own prefix (#14604)<commit_after># Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Z3(MakefilePackage):
    """Z3 is a theorem prover from Microsoft Research.
    It is licensed under the MIT license."""

    homepage = "https://github.com/Z3Prover/z3/wiki"
    url      = "https://github.com/Z3Prover/z3/archive/z3-4.5.0.tar.gz"

    version('4.5.0', sha256='aeae1d239c5e06ac183be7dd853775b84698db1265cb2258e5918a28372d4a0c')
    version('4.4.1', sha256='50967cca12c5c6e1612d0ccf8b6ebf5f99840a783d6cf5216336a2b59c37c0ce')
    version('4.4.0', sha256='65b72f9eb0af50949e504b47080fb3fc95f11c435633041d9a534473f3142cba')

    phases = ['bootstrap', 'build', 'install']

    variant('python', default=False, description='Enable python binding')
    depends_on('python', type=('build', 'run'))
    extends('python', when='+python')

    # Referenced: https://github.com/Z3Prover/z3/issues/1016
    patch('fix_1016_1.patch', when='@:4.4.1')
    patch('fix_1016_2.patch', when='@4.5.0')

    build_directory = 'build'

    def configure_args(self):
        spec = self.spec

        args = []

        if spec.satisfies('+python'):
            args.append('--python')
            args.append(
                '--pypkgdir=%s' % join_path(
                    prefix.lib,
                    'python%s' % spec['python'].version.up_to(2),
                    'site-packages'))

        return args

    def bootstrap(self, spec, prefix):
        options = ['--prefix={0}'.format(prefix)] + self.configure_args()
        spec['python'].command('scripts/mk_make.py', *options)
<|endoftext|>


<commit_before>from plugin import Plugin
from config import cmd_overwatch
import urllib.request
import wget
import os
import requests
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import json
from utils import create_logger

class Overwatch(Plugin):
    is_global = True
    log = create_logger(cmd_overwatch)

    async def on_message(self, message, pfx):

        # Overwatch API
        if message.content.startswith(pfx + cmd_overwatch + ' '):
            cmd_name = 'Overwatch'
            self.log.info('User %s [%s] on server %s [%s], used the ' + cmd_name + ' command on #%s channel',
                          message.author,
                          message.author.id, message.server.name, message.server.id, message.channel)
            await self.client.send_typing(message.channel)
            ow_input = (str(message.content[len(cmd_overwatch) + 1 + len(pfx):])).replace('#', '-')
            ow_region_x, ignore, ow_name = ow_input.partition(' ')
            ow_region = ow_region_x.replace('NA', 'US')
            if os.path.isfile('cache/ow/avatar_' + message.author.id + '.png'):
                os.remove('cache/ow/avatar_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/border_' + message.author.id + '.png'):
                os.remove('cache/ow/border_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/profile_' + message.author.id + '.png'):
                os.remove('cache/ow/profile_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/rank_' + message.author.id + '.png'):
                os.remove('cache/ow/rank_' + message.author.id + '.png')
            if ow_region.upper() == 'NA' or 'US' or 'EU':
                try:
                    profile = (
                        'http://127.0.0.1:9000/pc/' + ow_region.lower() + '/' + ow_name + '/profile').replace(' ', '')
                    profile_json_source = urllib.request.urlopen(profile).read().decode('utf-8')
                    profile_json = json.loads(profile_json_source)
                    champ_get_url = (
                        'http://127.0.0.1:9000/pc/' + ow_region.lower() + '/' + ow_name + '/quick-play/heroes').replace(' ', '')
                    champ_get_src = urllib.request.urlopen(champ_get_url).read().decode('utf-8')
                    champ_get = json.loads(champ_get_src)
                    avatar_link = profile_json['data']['avatar']
                    border_link = profile_json['data']['levelFrame']
                    if str(champ_get[0]['name']) == 'Lúcio':
                        top_champ = 'Lucio'
                    else:
                        top_champ = str(champ_get[0]['name'])
                    avaloc = 'cache/ow/avatar_' + message.author.id + '.png'
                    borloc = 'cache/ow/border_' + message.author.id + '.png'
                    wget.download(avatar_link, out=avaloc)
                    # avatar_link_base = 'https://blzgdapipro-a.akamaihd.net/game/unlocks/'
                    # avatar_name = str(profile_json['data']['avatar'])
                    # os.rename(avatar_name[len(avatar_link_base):], '/cache/ow/avatar_' + message.author.id + '.png')
                    wget.download(border_link, out=borloc)
                    # border_link_base = 'https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/'
                    # border_name = str(profile_json['data']['levelFrame'])
                    # os.rename(border_name[len(border_link_base):], '/cache/ow/border_' + message.author.id + '.png')
                    base = Image.open('img/ow/base.png')
                    overlay = Image.open('img/ow/overlay.png')
                    foreground = Image.open('cache/ow/border_' + message.author.id + '.png')
                    foreground_res = foreground.resize((128, 128), Image.ANTIALIAS)
                    background = Image.open('cache/ow/avatar_' + message.author.id + '.png')
                    background_res = background.resize((72, 72), Image.ANTIALIAS)
                    try:
                        rank_link = profile_json['data']['competitive']['rank_img']
                        rankloc = 'cache/ow/rank_' + message.author.id + '.png'
                        wget.download(rank_link, out=rankloc)
                        rankimg = Image.open('cache/ow/rank_' + message.author.id + '.png')
                        rankimg_res = rankimg.resize((64, 64), Image.ANTIALIAS)
                    except:
                        pass
                    base.paste(background_res, (28, 28))
                    base.paste(overlay, (0, 0), overlay)
                    base.paste(foreground_res, (0, 0), foreground_res)
                    try:
                        base.paste(rankimg_res, (310, 30), rankimg_res)
                    except:
                        pass
                    font = ImageFont.truetype("big_noodle_titling_oblique.ttf", 32)
                    font2 = ImageFont.truetype("big_noodle_titling_oblique.ttf", 16)
                    imgdraw = ImageDraw.Draw(base)
                    imgdraw.text((130, 38), profile_json['data']['username'], (255, 255, 255), font=font)
                    imgdraw.text((130, 70), 'Most Played: ' + top_champ, (255, 255, 255), font=font2)
                    base.save('cache\ow\profile_' + message.author.id + '.png')
                    name = profile_json['data']['username']
                    level = str(profile_json['data']['level'])
                    qg_played = str(profile_json['data']['games']['quick']['played'])
                    qg_won = str(profile_json['data']['games']['quick']['wins'])
                    qg_lost = str(profile_json['data']['games']['quick']['lost'])
                    qg_playtime = str(profile_json['data']['playtime']['quick'])
                    try:
                        cg_played = str(profile_json['data']['games']['competitive']['played'])
                    except:
                        cg_played = 'None'
                    try:
                        cg_won = str(profile_json['data']['games']['competitive']['wins'])
                    except:
                        cg_won = 'None'
                    try:
                        cg_lost = str(profile_json['data']['games']['competitive']['lost'])
                    except:
                        cg_lost = 'None'
                    try:
                        rank = str(profile_json['data']['competitive']['rank'])
                    except:
                        rank = 'None'
                    try:
                        cg_playtime = str(profile_json['data']['playtime']['competitive'])
                    except:
                        cg_playtime = 'None'
                    overwatch_profile = ('```Name: ' + name +
                                         '\nLevel: ' + level +
                                         '\nQuick Games:' +
                                         '\n    - Played: ' + qg_played +
                                         '\n    - Won: ' + qg_won +
                                         '\n    - Lost: ' + qg_lost +
                                         '\nCompetitive Games:' +
                                         '\n    - Played: ' + cg_played +
                                         '\n    - Won: ' + cg_won +
                                         '\n    - Lost: ' + cg_lost +
                                         '\n    - Rank: ' + rank +
                                         '\nPlaytime:' +
                                         '\n    - Quick: ' + qg_playtime +
                                         '\n    - Competitive: ' + cg_playtime + '```')
                    # print('CMD [' + cmd_name + '] > ' + initiator_data)
                    await self.client.send_file(message.channel, 'cache\ow\profile_' + message.author.id + '.png')
                    await self.client.send_message(message.channel, overwatch_profile)
                except KeyError:
                    try:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
                        print(profile_json['error'])
                        await self.client.send_message(message.channel, profile_json['error'])
                    except:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
                        await self.client.send_message(message.channel,
                                                       'Something went wrong.\nThe servers are most likely overloaded, please try again.')
                        # else:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
            else:
                await self.client.send_message(message.channel,
                                               'Invalid region: `' + ow_region.upper() + '`\nAccepted regions are `NA`, `US` and `EU`\nUsage: `' + pfx + cmd_overwatch + 'region battletag#ID')
<commit_msg>Mini-Fix<commit_after>from plugin import Plugin
from config import cmd_overwatch
import urllib.request
import wget
import os
import requests
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import json
from utils import create_logger

class Overwatch(Plugin):
    is_global = True
    log = create_logger(cmd_overwatch)

    async def on_message(self, message, pfx):

        # Overwatch API
        if message.content.startswith(pfx + cmd_overwatch + ' '):
            cmd_name = 'Overwatch'
            self.log.info('User %s [%s] on server %s [%s], used the ' + cmd_name + ' command on #%s channel',
                          message.author,
                          message.author.id, message.server.name, message.server.id, message.channel)
            await self.client.send_typing(message.channel)
            ow_input = (str(message.content[len(cmd_overwatch) + 1 + len(pfx):])).replace('#', '-')
            ow_region_x, ignore, ow_name = ow_input.partition(' ')
            ow_region = ow_region_x.replace('NA', 'US')
            if os.path.isfile('cache/ow/avatar_' + message.author.id + '.png'):
                os.remove('cache/ow/avatar_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/border_' + message.author.id + '.png'):
                os.remove('cache/ow/border_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/profile_' + message.author.id + '.png'):
                os.remove('cache/ow/profile_' + message.author.id + '.png')
            if os.path.isfile('cache/ow/rank_' + message.author.id + '.png'):
                os.remove('cache/ow/rank_' + message.author.id + '.png')
            if ow_region.upper() == 'NA' or 'US' or 'EU':
                try:
                    profile = (
                        'http://127.0.0.1:9000/pc/' + ow_region.lower() + '/' + ow_name + '/profile').replace(' ', '')
                    profile_json_source = urllib.request.urlopen(profile).read().decode('utf-8')
                    profile_json = json.loads(profile_json_source)
                    champ_get_url = (
                        'http://127.0.0.1:9000/pc/' + ow_region.lower() + '/' + ow_name + '/quick-play/heroes').replace(' ', '')
                    champ_get_src = urllib.request.urlopen(champ_get_url).read().decode('utf-8')
                    champ_get = json.loads(champ_get_src)
                    avatar_link = profile_json['data']['avatar']
                    border_link = profile_json['data']['levelFrame']
                    if str(champ_get[0]['name']) == 'Lúcio':
                        top_champ = 'Lucio'
                    else:
                        top_champ = str(champ_get[0]['name'])
                    avaloc = 'cache/ow/avatar_' + message.author.id + '.png'
                    borloc = 'cache/ow/border_' + message.author.id + '.png'
                    wget.download(avatar_link, out=avaloc)
                    # avatar_link_base = 'https://blzgdapipro-a.akamaihd.net/game/unlocks/'
                    # avatar_name = str(profile_json['data']['avatar'])
                    # os.rename(avatar_name[len(avatar_link_base):], '/cache/ow/avatar_' + message.author.id + '.png')
                    wget.download(border_link, out=borloc)
                    # border_link_base = 'https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/'
                    # border_name = str(profile_json['data']['levelFrame'])
                    # os.rename(border_name[len(border_link_base):], '/cache/ow/border_' + message.author.id + '.png')
                    base = Image.open('img/ow/base.png')
                    overlay = Image.open('img/ow/overlay.png')
                    foreground = Image.open('cache/ow/border_' + message.author.id + '.png')
                    foreground_res = foreground.resize((128, 128), Image.ANTIALIAS)
                    background = Image.open('cache/ow/avatar_' + message.author.id + '.png')
                    background_res = background.resize((72, 72), Image.ANTIALIAS)
                    try:
                        rank_link = profile_json['data']['competitive']['rank_img']
                        rankloc = 'cache/ow/rank_' + message.author.id + '.png'
                        wget.download(rank_link, out=rankloc)
                        rankimg = Image.open('cache/ow/rank_' + message.author.id + '.png')
                        rankimg_res = rankimg.resize((64, 64), Image.ANTIALIAS)
                    except:
                        pass
                    base.paste(background_res, (28, 28))
                    base.paste(overlay, (0, 0), overlay)
                    base.paste(foreground_res, (0, 0), foreground_res)
                    try:
                        base.paste(rankimg_res, (310, 32), rankimg_res)
                    except:
                        pass
                    font = ImageFont.truetype("big_noodle_titling_oblique.ttf", 32)
                    font2 = ImageFont.truetype("big_noodle_titling_oblique.ttf", 16)
                    imgdraw = ImageDraw.Draw(base)
                    imgdraw.text((130, 38), profile_json['data']['username'], (255, 255, 255), font=font)
                    imgdraw.text((130, 70), 'Most Played: ' + top_champ, (255, 255, 255), font=font2)
                    base.save('cache\ow\profile_' + message.author.id + '.png')
                    name = profile_json['data']['username']
                    level = str(profile_json['data']['level'])
                    qg_played = str(profile_json['data']['games']['quick']['played'])
                    qg_won = str(profile_json['data']['games']['quick']['wins'])
                    qg_lost = str(profile_json['data']['games']['quick']['lost'])
                    qg_playtime = str(profile_json['data']['playtime']['quick'])
                    try:
                        cg_played = str(profile_json['data']['games']['competitive']['played'])
                    except:
                        cg_played = 'None'
                    try:
                        cg_won = str(profile_json['data']['games']['competitive']['wins'])
                    except:
                        cg_won = 'None'
                    try:
                        cg_lost = str(profile_json['data']['games']['competitive']['lost'])
                    except:
                        cg_lost = 'None'
                    try:
                        rank = str(profile_json['data']['competitive']['rank'])
                    except:
                        rank = 'None'
                    try:
                        cg_playtime = str(profile_json['data']['playtime']['competitive'])
                    except:
                        cg_playtime = 'None'
                    overwatch_profile = ('```Name: ' + name +
                                         '\nLevel: ' + level +
                                         '\nQuick Games:' +
                                         '\n    - Played: ' + qg_played +
                                         '\n    - Won: ' + qg_won +
                                         '\n    - Lost: ' + qg_lost +
                                         '\nCompetitive Games:' +
                                         '\n    - Played: ' + cg_played +
                                         '\n    - Won: ' + cg_won +
                                         '\n    - Lost: ' + cg_lost +
                                         '\n    - Rank: ' + rank +
                                         '\nPlaytime:' +
                                         '\n    - Quick: ' + qg_playtime +
                                         '\n    - Competitive: ' + cg_playtime + '```')
                    # print('CMD [' + cmd_name + '] > ' + initiator_data)
                    await self.client.send_file(message.channel, 'cache\ow\profile_' + message.author.id + '.png')
                    await self.client.send_message(message.channel, overwatch_profile)
                except KeyError:
                    try:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
                        print(profile_json['error'])
                        await self.client.send_message(message.channel, profile_json['error'])
                    except:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
                        await self.client.send_message(message.channel,
                                                       'Something went wrong.\nThe servers are most likely overloaded, please try again.')
                        # else:
                        # print('CMD [' + cmd_name + '] > ' + initiator_data)
            else:
                await self.client.send_message(message.channel,
                                               'Invalid region: `' + ow_region.upper() + '`\nAccepted regions are `NA`, `US` and `EU`\nUsage: `' + pfx + cmd_overwatch + 'region battletag#ID')
<|endoftext|>