<commit_before># -*- encoding: utf-8 -*-
#
# Copyright © 2017 Red Hat, 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.

import logging
import operator

import six.moves

from pastamaker import pr

LOG = logging.getLogger(__name__)

def is_branch_protected_as_expected(repo, branch):
    # NOTE(sileht): Can't get which permission I need to do this
    return True

    headers, data = repo._requester.requestJsonAndCheck(
        "GET",
        repo.url + "/branches/" + branch + "/protection",
        headers={'Accept': 'application/vnd.github.loki-preview+json'}
    )

    del data["url"]
    del data["required_pull_request_reviews"]["url"]
    del data["required_status_checks"]["url"]
    del data["required_status_checks"]["contexts_url"]
    del data["enforce_admins"]["url"]

    expected = {
        'required_pull_request_reviews': {'dismiss_stale_reviews': True},
        'required_status_checks': {'strict': True, 'contexts':
                                   ['continuous-integration/travis-ci']},
        'enforce_admins': {'enabled': True},
    }
    return data == expected

class PastaMakerEngine(object):
    def __init__(self, g, user, repo):
        self._g = g
        self._u = user
        self._r = repo

    def _get_logprefix(self, branch="<unknown>"):
        return (self._u.login + "/" + self._r.name +
                "/pull/?@" + branch + " (?, ?)")

    def log_formated_event(self, event_type, incoming_pull, data):
        if event_type == "pull_request":
            p_info = incoming_pull.pretty()
            extra = "action: %s" % data["action"]

        elif event_type == "pull_request_review":
            p_info = incoming_pull.pretty()
            extra = "action: %s, review-state: %s" % (data["action"],
                                                      data["review"]["state"])

        elif event_type == "status":
            if incoming_pull:
                p_info = incoming_pull.pretty()
            else:
                p_info = self._get_logprefix()
            extra = "ci-status: %s, sha: %s" % (data["state"], data["sha"])

        elif event_type == "refresh":
            p_info = self._get_logprefix(data["branch"])
            extra = ""
        else:
            if incoming_pull:
                p_info = incoming_pull.pretty()
            else:
                p_info = self._get_logprefix()
            extra = " ignored"

        LOG.info("%s - got event '%s' - %s", p_info, event_type, extra)

    def handle(self, event_type, data):
        # Everything start here

        incoming_pull = pr.from_event(self._r, data)
        if not incoming_pull and event_type == "status":
            issues = list(self._g.search_issues("is:pr is:open %s" %
                                                data["sha"]))
            if len(issues) >= 1:
                incoming_pull = self._r.get_pull(issues[0].number)

        self.log_formated_event(event_type, incoming_pull, data)

        if event_type == "refresh":
            queues = self.get_pull_requests_queue(data["branch"])
            if queues:
                self.proceed_queues(queues)
            return

        if not incoming_pull:
            LOG.error("No pull request found in the event, ignoring")
            return

        if event_type == "state" and data["state"] == "pending":
            # Don't compute the queue for nothing
            return

        queues = self.get_pull_requests_queue(incoming_pull.base.ref)

        if not queues:
            LOG.info("Nothing queued, skipping the event")
            return

        # Something change on our top PR
        if incoming_pull.number == queues[0].number:
            self.proceed_queues(queues)

        if event_type == "pull_request" and data["action"] == "closed":
            # A PR have been closed, process the queues
            self.proceed_queues(queues)

    ###########################
    # State machine goes here #
    ###########################

    def proceed_queues(self, queues):
        """Do the next action for this pull request

        'p' is the top priority pull request to merge
        """

        p = queues[0]

        LOG.info("%s, processing...", p.pretty())

        # NOTE(sileht): This also refresh the PR, following code expects the
        # mergeable_state is up2date

        if p.approved:
            # Everything looks good
            if p.mergeable_state == "clean":
                if p.pastamaker_merge():
                    LOG.info("%s merged", p.pretty())
                    # Wait for the closed event
                    return

            # Have CI ok, at least 1 approval, but branch need to be updated
            elif p.mergeable_state == "behind":
                if p.ci_status == "success":
                    # rebase it and wait the next pull_request event
                    # (synchronize)
                    if p.update_branch():
                        LOG.info("%s branch updated", p.pretty())
                        return

            elif p.mergeable_state == "blocked":
                # We need to check why it's blocked
                if p.ci_status == "pending":
                    # Let's wait the next status event
                    LOG.info("%s wating for CI completion", p.pretty())
                    return
                # For other reason, we need to select another PR

            elif p.mergeable_state in ["unstable", "dirty", "ok"]:
                LOG.info("%s, unmergable", p.pretty())

            else:
                LOG.warning("%s, FIXME unhandled mergeable_state",
                            p.pretty())

        if len(queues) >= 2:
            self.proceed_queues(queues[1:])

    def dump_pulls_state(self, pulls):
        for p in pulls:
            LOG.info("%s, %s, %s, base-sha: %s, head-sha: %s)",
                     p.pretty(), p.ci_status,
                     p.created_at, p.base.sha, p.head.sha)

    def get_pull_requests_queue(self, branch):
        LOG.info("%s, looking for pull requests mergeable",
                 self._get_logprefix(branch))

        sort_key = operator.attrgetter('pastamaker_priority', 'created_at')

        pulls = self._r.get_pulls(sort="created", direction="asc", base=branch)
        pulls = six.moves.map(lambda p: p.pastamaker_update(), pulls)
        pulls = list(filter(lambda p: p.pastamaker_priority >= 0,
                            sorted(pulls, key=sort_key, reverse=True)))
        if pulls:
            self.dump_pulls_state(pulls)
        LOG.info("%s, %s pull request(s) mergeable" %
                 (self._get_logprefix(branch), len(pulls)))
        return pulls
<commit_msg>For status event search in closed PR too<commit_after># -*- encoding: utf-8 -*-
#
# Copyright © 2017 Red Hat, 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.

import logging
import operator

import six.moves

from pastamaker import pr

LOG = logging.getLogger(__name__)

def is_branch_protected_as_expected(repo, branch):
    # NOTE(sileht): Can't get which permission I need to do this
    return True

    headers, data = repo._requester.requestJsonAndCheck(
        "GET",
        repo.url + "/branches/" + branch + "/protection",
        headers={'Accept': 'application/vnd.github.loki-preview+json'}
    )

    del data["url"]
    del data["required_pull_request_reviews"]["url"]
    del data["required_status_checks"]["url"]
    del data["required_status_checks"]["contexts_url"]
    del data["enforce_admins"]["url"]

    expected = {
        'required_pull_request_reviews': {'dismiss_stale_reviews': True},
        'required_status_checks': {'strict': True, 'contexts':
                                   ['continuous-integration/travis-ci']},
        'enforce_admins': {'enabled': True},
    }
    return data == expected

class PastaMakerEngine(object):
    def __init__(self, g, user, repo):
        self._g = g
        self._u = user
        self._r = repo

    def _get_logprefix(self, branch="<unknown>"):
        return (self._u.login + "/" + self._r.name +
                "/pull/?@" + branch + " (?, ?)")

    def log_formated_event(self, event_type, incoming_pull, data):
        if event_type == "pull_request":
            p_info = incoming_pull.pretty()
            extra = "action: %s" % data["action"]

        elif event_type == "pull_request_review":
            p_info = incoming_pull.pretty()
            extra = "action: %s, review-state: %s" % (data["action"],
                                                      data["review"]["state"])

        elif event_type == "status":
            if incoming_pull:
                p_info = incoming_pull.pretty()
            else:
                p_info = self._get_logprefix()
            extra = "ci-status: %s, sha: %s" % (data["state"], data["sha"])

        elif event_type == "refresh":
            p_info = self._get_logprefix(data["branch"])
            extra = ""
        else:
            if incoming_pull:
                p_info = incoming_pull.pretty()
            else:
                p_info = self._get_logprefix()
            extra = " ignored"

        LOG.info("%s - got event '%s' - %s", p_info, event_type, extra)

    def handle(self, event_type, data):
        # Everything start here

        incoming_pull = pr.from_event(self._r, data)
        if not incoming_pull and event_type == "status":
            issues = list(self._g.search_issues("is:pr %s" % data["sha"]))
            if len(issues) >= 1:
                incoming_pull = self._r.get_pull(issues[0].number)

        self.log_formated_event(event_type, incoming_pull, data)

        if event_type == "refresh":
            queues = self.get_pull_requests_queue(data["branch"])
            if queues:
                self.proceed_queues(queues)
            return

        if not incoming_pull:
            LOG.error("No pull request found in the event, ignoring")
            return

        if event_type == "state" and data["state"] == "pending":
            # Don't compute the queue for nothing
            return

        queues = self.get_pull_requests_queue(incoming_pull.base.ref)

        if not queues:
            LOG.info("Nothing queued, skipping the event")
            return

        # Something change on our top PR
        if incoming_pull.number == queues[0].number:
            self.proceed_queues(queues)

        if event_type == "pull_request" and data["action"] == "closed":
            # A PR have been closed, process the queues
            self.proceed_queues(queues)

    ###########################
    # State machine goes here #
    ###########################

    def proceed_queues(self, queues):
        """Do the next action for this pull request

        'p' is the top priority pull request to merge
        """

        p = queues[0]

        LOG.info("%s, processing...", p.pretty())

        # NOTE(sileht): This also refresh the PR, following code expects the
        # mergeable_state is up2date

        if p.approved:
            # Everything looks good
            if p.mergeable_state == "clean":
                if p.pastamaker_merge():
                    LOG.info("%s merged", p.pretty())
                    # Wait for the closed event
                    return

            # Have CI ok, at least 1 approval, but branch need to be updated
            elif p.mergeable_state == "behind":
                if p.ci_status == "success":
                    # rebase it and wait the next pull_request event
                    # (synchronize)
                    if p.update_branch():
                        LOG.info("%s branch updated", p.pretty())
                        return

            elif p.mergeable_state == "blocked":
                # We need to check why it's blocked
                if p.ci_status == "pending":
                    # Let's wait the next status event
                    LOG.info("%s wating for CI completion", p.pretty())
                    return
                # For other reason, we need to select another PR

            elif p.mergeable_state in ["unstable", "dirty", "ok"]:
                LOG.info("%s, unmergable", p.pretty())

            else:
                LOG.warning("%s, FIXME unhandled mergeable_state",
                            p.pretty())

        if len(queues) >= 2:
            self.proceed_queues(queues[1:])

    def dump_pulls_state(self, pulls):
        for p in pulls:
            LOG.info("%s, %s, %s, base-sha: %s, head-sha: %s)",
                     p.pretty(), p.ci_status,
                     p.created_at, p.base.sha, p.head.sha)

    def get_pull_requests_queue(self, branch):
        LOG.info("%s, looking for pull requests mergeable",
                 self._get_logprefix(branch))

        sort_key = operator.attrgetter('pastamaker_priority', 'created_at')

        pulls = self._r.get_pulls(sort="created", direction="asc", base=branch)
        pulls = six.moves.map(lambda p: p.pastamaker_update(), pulls)
        pulls = list(filter(lambda p: p.pastamaker_priority >= 0,
                            sorted(pulls, key=sort_key, reverse=True)))
        if pulls:
            self.dump_pulls_state(pulls)
        LOG.info("%s, %s pull request(s) mergeable" %
                 (self._get_logprefix(branch), len(pulls)))
        return pulls
<|endoftext|>


<commit_before>#!/usr/bin/env python2
# coding=utf-8

"""
gradient pattern.

    generates a test pattern:
    gradient
    same output as gradient but with hopefully different calculation logic

    logic:
        start at _calculate_step
        - calculate (new) current position. (position means time)
        for every stop-pair
            for every pixel

    history:
        see git commits

    todo:
        ~ all fine :-)
"""

# https://docs.python.org/2.7/howto/pyporting.html#division
from __future__ import division

import array
import colorsys

import pattern

##########################################
# globals

##########################################
# functions

##########################################
# classes

class Gradient2(pattern.Pattern):
    """Gradient2 Pattern Class."""

    def __init__(self, config, config_global):
        """Init pattern."""
        self.config_defaults = {
            "cycle_duration": 10,
            "position_current": 0,
            "type": "channel",
            "stops": [
                {
                    "position": 0,
                    "red": 1,
                    "green": 1,
                    "blue": 1,
                },
                {
                    "position": 0.3,
                    "red": 1,
                    "green": 0,
                    "blue": 0,
                },
                {
                    "position": 0.7,
                    "red": 0,
                    "green": 1,
                    "blue": 0,
                },
                {
                    "position": 1,
                    "red": 0,
                    "green": 0,
                    "blue": 1,
                },
            ],
        }
        # python3 syntax
        # super().__init__()
        # python2 syntax
        # super(Pattern, self).__init__()
        # explicit call
        pattern.Pattern.__init__(self, config, config_global)

    def _interpolate_channels(self, pixel_position, stop_start, stop_end):
        """Interpolate with channels."""
        # print("interpolate_channels")
        result = {}
        # check for exact match
        if pixel_position == stop_start["position"]:
            result = stop_start.copy()
        else:
            # interpolate all colors
            for color_name in self.color_channels:
                result[color_name] = pattern.map(
                    pixel_position,
                    stop_start["position"],
                    stop_end["position"],
                    stop_start[color_name],
                    stop_end[color_name],
                )
            result["position"] = pixel_position

        return result

    def _calculate_pixels_for_position(self, position_current):
        """Calculate pixels for all positions."""
        pixel_count = self.pixel_count
        pixel_index_max = self.pixel_count - 1

        stops_list = self.stops_list
        stops_count = len(stops_list)
        position_stepwidth_per_pixel = self.position_stepwidth_per_pixel

        print("\n"*2)
        print("_calculate_pixels_for_position()")
        print("position_current {: <.9f}".format(position_current))

        print("pixel_count     {: <}".format(pixel_count))
        print("pixel_index_max {: <}".format(pixel_index_max))

        color_channels = self.color_channels

        pixel_data = []
        pixel_data.append(0)
        pixel_data *= pixel_count

        # for every section in the stops_list
        for stop_index, stop_start in enumerate(stops_list):
            if stop_index < (stops_count-1):
                stop_end = stops_list[stop_index+1]
            else:
                stop_end = stops_list[0]

            print("stop_index {}".format(stop_index))
            print("stop_start {}".format(stop_start))
            print("stop_end   {}".format(stop_end))

            # calculate first and last pixel position for this section
            pixel_position_start = stop_start['position'] + position_current
            # pixel_position_start = stop_start['position']
            # print("pixel_position_start {: <.3f}".format(
            #     pixel_position_start
            # ))
            # # check for wrap around
            # if pixel_position_start > 1.0:
            #     pixel_position_start -= 1.0

            print("pixel_position_start {: <.3f}".format(
                pixel_position_start
            ))

            pixel_position_end = stop_end['position'] + position_current
            # pixel_position_end = stop_end['position']
            # print("pixel_position_end   {: <.3f}".format(pixel_position_end))
            # # check for wrap around
            # if pixel_position_end > 1.0:
            #     pixel_position_end -= 1.0

            print("pixel_position_end   {: <.3f}".format(pixel_position_end))

            # calculate pixel index from position:
            pixel_index_start = int(
                pixel_position_start * pixel_index_max
            )
            print("pixel_index_start    {}".format(pixel_index_start))

            pixel_index_end = int(
                pixel_position_end * pixel_index_max
            )
            # print("pixel_index_end      {}".format(pixel_index_end))
            # # handle wrap around in value
            # if pixel_index_end < pixel_index_max:
            #     pixel_index_end -= pixel_index_max
            print("pixel_index_end      {}".format(pixel_index_end))
            # handle wrap around for xrange
            if pixel_index_end < pixel_index_start:
                pixel_index_end += pixel_index_max

            print("pixel_index_end      {}".format(pixel_index_end))

            # check if there are pixels in this section
            if (pixel_index_end - pixel_index_start) > 0:
                # for every pixel in this section do
                # pixel_position = pixel_position_start
                for pixel_index_raw in xrange(
                    pixel_index_start, pixel_index_end + 1
                ):
                    # handle wrap around for xrange
                    pixel_index = pixel_index_raw
                    if pixel_index > pixel_index_max:
                        pixel_index = pixel_index - pixel_count

                    # calculate position in section
                    pixel_position_raw = 0
                    pixel_position = 0
                    # pixel_position_raw = (
                    #     (pixel_index_start + pixel_index) *
                    #     position_stepwidth_per_pixel
                    # ) - position_current
                    # # check for wrap around
                    # pixel_position = pixel_position_raw
                    # if pixel_position_raw > 1.0:
                    #     pixel_position = pixel_position_raw - 1.0
                    pixel_position = pattern.map(
                        pixel_index_raw,
                        pixel_index_start,
                        pixel_index_end,
                        stop_start["position"],
                        stop_end["position"]
                    )

                    print(
                        "ir: {:< 4} "
                        "i: {:< 4} "
                        # "pr: {:< 7.6f} "
                        "p: {:< 7.6f}"
                        .format(
                            pixel_index_raw,
                            pixel_index,
                            # pixel_position_raw,
                            pixel_position
                            )
                    )

                    # now we have
                    # pixel_index
                    # pixel_position
                    # stop_start
                    # stop_end
                    # so we can interpolate
                    pixel_data[pixel_index] = self.interpolation_function(
                        pixel_position,
                        stop_start,
                        stop_end
                    )

        return pixel_data

    def _set_data_output(self, data_output, pixel_data):
        color_channels = self.color_channels
        color_channels_count = len(color_channels)
        print("output:")
        for pixel_index, pixel_values in enumerate(pixel_data):
            channel_index = (pixel_index * color_channels_count)
            print(
                "i: {:< 4} "
                "p: {:< 7.6f}  "
                "r: {:< 7.6f}  "
                "g: {:< 7.6f}  "
                "b: {:< 7.6f}  "
                "ci: {:< 4} "
                .format(
                    pixel_index,
                    pixel_values['position'],
                    pixel_values['red'],
                    pixel_values['green'],
                    pixel_values['blue'],
                    channel_index
                )
            )
            for color_index, color_name in enumerate(color_channels):
                color_value = pixel_values[color_name]
                # convert 0..1 to 0..65535 range
                value_16bit = int(65535 * color_value)
                # convert 16bit to 8 bit
                # check bounds
                if not (0 <= value_16bit < 65535):
                    value_16bit = min(max(value_16bit, 0), 65535)
                value_HighByte = value_16bit >> 8
                data_output[channel_index + color_index] = value_HighByte

    def _calculate_step(self):
        """Calculate single step."""
        # pattern.Pattern._calculate_step(self)
        # available attributes:
        # global things (readonly)
        # self.channel_count
        # self.pixel_count
        # self.repeate_count
        # self.repeate_snake
        # self.color_channels
        # self.update_interval
        # self.mode_16bit
        # self.values['off']
        # self.values['low']
        # self.values['high']
        # self.config_global[]

        self.update_globals()

        # pattern specific updates:
        interpolation_type = self.config['type']
        self.interpolation_function = self._interpolate_channels
        # if interpolation_type.startswith("hsv"):
        #     self.interpolation_function = self._interpolate_hsv
        # elif interpolation_type.startswith("channels"):
        #     self.interpolation_function = self._interpolate_channels
        # else:
        #     self.interpolation_function = self._interpolate_channels

        # prepare temp array
        data_output = array.array('B')
        data_output.append(0)
        # multiply so we have a array with total_channel_count zeros in it:
        # this is much faster than a for loop!
        data_output *= self.total_channel_count

        # in milliseconds
        cycle_duration = self.config["cycle_duration"] * 1000

        # calculate stepsize
        # step_count = cycle_duration / update_interval
        # cycle_duration = 1.0
        # update_interval = position_stepsize
        position_stepsize = 1.0 * self.update_interval / cycle_duration

        stops_list = self.config["stops"]
        self.stops_list = stops_list
        stops_count = len(stops_list)
        position_min = stops_list[0]["position"]
        position_max = stops_list[stops_count-1]["position"]
        position_amount = position_max - position_min
        self.position_stepwidth_per_pixel = position_amount / self.pixel_count

        # print("stops_count", stops_count)
        # print("position_min", position_min)
        # print("position_max", position_max)
        # print("position_amount", position_amount)
        # print("position_stepwidth_per_pixel", position_stepwidth_per_pixel)

        ##########################################
        # fill array with meaningfull data according to the pattern :-)

        # calculate new position
        position_current = self.config["position_current"]
        position_current = position_current + position_stepsize
        # check for upper bound
        if position_current >= 1:
            position_current -= 1
        # write position_current back:
        self.config["position_current"] = position_current
        # print("position_current", position_current)
        # print("****")

        # generate values for every pixel
        pixel_data = self._calculate_pixels_for_position(
            position_current
        )

        self._set_data_output(data_output, pixel_data)

        return data_output

##########################################
if __name__ == '__main__':

    print(42*'*')
    print('Python Version: ' + sys.version)
    print(42*'*')
    print(__doc__)
    print(42*'*')
    print("This Module has no stand alone functionality.")
    print(42*'*')

    ##########################################
<commit_msg>gradient2 commented debug output<commit_after>#!/usr/bin/env python2
# coding=utf-8

"""
gradient pattern.

    generates a test pattern:
    gradient
    same output as gradient but with hopefully different calculation logic

    logic:
        start at _calculate_step
        - calculate (new) current position. (position means time)
        for every stop-pair
            for every pixel

    history:
        see git commits

    todo:
        ~ all fine :-)
"""

# https://docs.python.org/2.7/howto/pyporting.html#division
from __future__ import division

import array
import colorsys

import pattern

##########################################
# globals

##########################################
# functions

##########################################
# classes

class Gradient2(pattern.Pattern):
    """Gradient2 Pattern Class."""

    def __init__(self, config, config_global):
        """Init pattern."""
        self.config_defaults = {
            "cycle_duration": 10,
            "position_current": 0,
            "type": "channel",
            "stops": [
                {
                    "position": 0,
                    "red": 1,
                    "green": 1,
                    "blue": 1,
                },
                {
                    "position": 0.3,
                    "red": 1,
                    "green": 0,
                    "blue": 0,
                },
                {
                    "position": 0.7,
                    "red": 0,
                    "green": 1,
                    "blue": 0,
                },
                {
                    "position": 1,
                    "red": 0,
                    "green": 0,
                    "blue": 1,
                },
            ],
        }
        # python3 syntax
        # super().__init__()
        # python2 syntax
        # super(Pattern, self).__init__()
        # explicit call
        pattern.Pattern.__init__(self, config, config_global)

    def _interpolate_channels(self, pixel_position, stop_start, stop_end):
        """Interpolate with channels."""
        # print("interpolate_channels")
        result = {}
        # check for exact match
        if pixel_position == stop_start["position"]:
            result = stop_start.copy()
        else:
            # interpolate all colors
            for color_name in self.color_channels:
                result[color_name] = pattern.map(
                    pixel_position,
                    stop_start["position"],
                    stop_end["position"],
                    stop_start[color_name],
                    stop_end[color_name],
                )
            result["position"] = pixel_position

        return result

    def _calculate_pixels_for_position(self, position_current):
        """Calculate pixels for all positions."""
        pixel_count = self.pixel_count
        pixel_index_max = self.pixel_count - 1

        stops_list = self.stops_list
        stops_count = len(stops_list)
        position_stepwidth_per_pixel = self.position_stepwidth_per_pixel

        # print("\n"*2)
        # print("_calculate_pixels_for_position()")
        # print("position_current {: <.9f}".format(position_current))
        #
        # print("pixel_count     {: <}".format(pixel_count))
        # print("pixel_index_max {: <}".format(pixel_index_max))

        color_channels = self.color_channels

        pixel_data = []
        pixel_data.append(0)
        pixel_data *= pixel_count

        # for every section in the stops_list
        for stop_index, stop_start in enumerate(stops_list):
            if stop_index < (stops_count-1):
                stop_end = stops_list[stop_index+1]
            else:
                stop_end = stops_list[0]

            # print("stop_index {}".format(stop_index))
            # print("stop_start {}".format(stop_start))
            # print("stop_end   {}".format(stop_end))

            # calculate first and last pixel position for this section
            pixel_position_start = stop_start['position'] + position_current
            # pixel_position_start = stop_start['position']
            # print("pixel_position_start {: <.3f}".format(
            #     pixel_position_start
            # ))
            # # check for wrap around
            # if pixel_position_start > 1.0:
            #     pixel_position_start -= 1.0

            # print("pixel_position_start {: <.3f}".format(
            #     pixel_position_start
            # ))

            pixel_position_end = stop_end['position'] + position_current
            # pixel_position_end = stop_end['position']
            # print("pixel_position_end   {: <.3f}".format(pixel_position_end))
            # # check for wrap around
            # if pixel_position_end > 1.0:
            #     pixel_position_end -= 1.0

            # print("pixel_position_end   {: <.3f}".format(pixel_position_end))

            # calculate pixel index from position:
            pixel_index_start = int(
                pixel_position_start * pixel_index_max
            )
            # print("pixel_index_start    {}".format(pixel_index_start))

            pixel_index_end = int(
                pixel_position_end * pixel_index_max
            )
            # print("pixel_index_end      {}".format(pixel_index_end))
            # # handle wrap around in value
            # if pixel_index_end < pixel_index_max:
            #     pixel_index_end -= pixel_index_max
            # print("pixel_index_end      {}".format(pixel_index_end))
            # handle wrap around for xrange
            if pixel_index_end < pixel_index_start:
                pixel_index_end += pixel_index_max

            # print("pixel_index_end      {}".format(pixel_index_end))

            # check if there are pixels in this section
            if (pixel_index_end - pixel_index_start) > 0:
                # for every pixel in this section do
                # pixel_position = pixel_position_start
                for pixel_index_raw in xrange(
                    pixel_index_start, pixel_index_end + 1
                ):
                    # handle wrap around for xrange
                    pixel_index = pixel_index_raw
                    if pixel_index > pixel_index_max:
                        pixel_index = pixel_index - pixel_count

                    # calculate position in section
                    pixel_position_raw = 0
                    pixel_position = 0
                    # pixel_position_raw = (
                    #     (pixel_index_start + pixel_index) *
                    #     position_stepwidth_per_pixel
                    # ) - position_current
                    # # check for wrap around
                    # pixel_position = pixel_position_raw
                    # if pixel_position_raw > 1.0:
                    #     pixel_position = pixel_position_raw - 1.0
                    pixel_position = pattern.map(
                        pixel_index_raw,
                        pixel_index_start,
                        pixel_index_end,
                        stop_start["position"],
                        stop_end["position"]
                    )

                    # print(
                    #     "ir: {:< 4} "
                    #     "i: {:< 4} "
                    #     # "pr: {:< 7.6f} "
                    #     "p: {:< 7.6f}"
                    #     .format(
                    #         pixel_index_raw,
                    #         pixel_index,
                    #         # pixel_position_raw,
                    #         pixel_position
                    #         )
                    # )

                    # now we have
                    # pixel_index
                    # pixel_position
                    # stop_start
                    # stop_end
                    # so we can interpolate
                    pixel_data[pixel_index] = self.interpolation_function(
                        pixel_position,
                        stop_start,
                        stop_end
                    )

        return pixel_data

    def _set_data_output(self, data_output, pixel_data):
        color_channels = self.color_channels
        color_channels_count = len(color_channels)
        # print("output:")
        for pixel_index, pixel_values in enumerate(pixel_data):
            channel_index = (pixel_index * color_channels_count)
            # print(
            #     "i: {:< 4} "
            #     "p: {:< 7.6f}  "
            #     "r: {:< 7.6f}  "
            #     "g: {:< 7.6f}  "
            #     "b: {:< 7.6f}  "
            #     "ci: {:< 4} "
            #     .format(
            #         pixel_index,
            #         pixel_values['position'],
            #         pixel_values['red'],
            #         pixel_values['green'],
            #         pixel_values['blue'],
            #         channel_index
            #     )
            # )
            for color_index, color_name in enumerate(color_channels):
                color_value = pixel_values[color_name]
                # convert 0..1 to 0..65535 range
                value_16bit = int(65535 * color_value)
                # convert 16bit to 8 bit
                # check bounds
                if not (0 <= value_16bit < 65535):
                    value_16bit = min(max(value_16bit, 0), 65535)
                value_HighByte = value_16bit >> 8
                data_output[channel_index + color_index] = value_HighByte

    def _calculate_step(self):
        """Calculate single step."""
        # pattern.Pattern._calculate_step(self)
        # available attributes:
        # global things (readonly)
        # self.channel_count
        # self.pixel_count
        # self.repeate_count
        # self.repeate_snake
        # self.color_channels
        # self.update_interval
        # self.mode_16bit
        # self.values['off']
        # self.values['low']
        # self.values['high']
        # self.config_global[]

        self.update_globals()

        # pattern specific updates:
        interpolation_type = self.config['type']
        self.interpolation_function = self._interpolate_channels
        # if interpolation_type.startswith("hsv"):
        #     self.interpolation_function = self._interpolate_hsv
        # elif interpolation_type.startswith("channels"):
        #     self.interpolation_function = self._interpolate_channels
        # else:
        #     self.interpolation_function = self._interpolate_channels

        # prepare temp array
        data_output = array.array('B')
        data_output.append(0)
        # multiply so we have a array with total_channel_count zeros in it:
        # this is much faster than a for loop!
        data_output *= self.total_channel_count

        # in milliseconds
        cycle_duration = self.config["cycle_duration"] * 1000

        # calculate stepsize
        # step_count = cycle_duration / update_interval
        # cycle_duration = 1.0
        # update_interval = position_stepsize
        position_stepsize = 1.0 * self.update_interval / cycle_duration

        stops_list = self.config["stops"]
        self.stops_list = stops_list
        stops_count = len(stops_list)
        position_min = stops_list[0]["position"]
        position_max = stops_list[stops_count-1]["position"]
        position_amount = position_max - position_min
        self.position_stepwidth_per_pixel = position_amount / self.pixel_count

        # print("stops_count", stops_count)
        # print("position_min", position_min)
        # print("position_max", position_max)
        # print("position_amount", position_amount)
        # print("position_stepwidth_per_pixel", position_stepwidth_per_pixel)

        ##########################################
        # fill array with meaningfull data according to the pattern :-)

        # calculate new position
        position_current = self.config["position_current"]
        position_current = position_current + position_stepsize
        # check for upper bound
        if position_current >= 1:
            position_current -= 1
        # write position_current back:
        self.config["position_current"] = position_current
        # print("position_current", position_current)
        # print("****")

        # generate values for every pixel
        pixel_data = self._calculate_pixels_for_position(
            position_current
        )

        self._set_data_output(data_output, pixel_data)

        return data_output

##########################################
if __name__ == '__main__':

    print(42*'*')
    print('Python Version: ' + sys.version)
    print(42*'*')
    print(__doc__)
    print(42*'*')
    print("This Module has no stand alone functionality.")
    print(42*'*')

    ##########################################
<|endoftext|>


<commit_before>import os
import re
import sys

import markdown2
import pygments
import pygments.formatters
import pygments.lexers

import pdoc.doc
import pdoc.render

# From language reference, but adds '.' to allow fully qualified names.
pyident = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]+$")
indent = re.compile("^\s*")

def decode(s):
    if sys.version_info[0] < 3 and isinstance(s, str):
        return s.decode("utf-8", "ignore")
    return s

def ident(s):
    return '%s' % s

def sourceid(dobj):
    return "source-%s" % dobj.refname

def clean_source_lines(lines):
    """
  Cleans the source code so that pygments can render it well.

  Returns one string with all of the source code.
  """
    base_indent = len(indent.match(lines[0]).group(0))
    base_indent = 0
    for line in lines:
        if len(line.strip()) > 0:
            base_indent = len(indent.match(lines[0]).group(0))
            break
    lines = [line[base_indent:] for line in lines]

    if sys.version_info[0] < 3:
        pylex = pygments.lexers.PythonLexer()
    else:
        pylex = pygments.lexers.Python3Lexer()

    htmlform = pygments.formatters.HtmlFormatter(cssclass="codehilite")
    return pygments.highlight("".join(lines), pylex, htmlform)

def linkify(parent, match, link_prefix):
    matched = match.group(0)
    ident = matched[1:-1]
    name, url = lookup(parent, ident, link_prefix)
    if name is None:
        return matched
    return "[`%s`](%s)" % (name, url)

def mark(s, module_list=None, linky=True):
    if linky:
        s, _ = re.subn("\b\n\b", " ", s)
    # if not module_list:
    #     s, _ = re.subn("`[^`]+`", linkify, s)

    extensions = ["fenced-code-blocks"]
    s = markdown2.markdown(s.strip(), extras=extensions)
    return s

def glimpse(s, length=100):
    if len(s) < length:
        return s
    return s[0:length] + "..."

def module_url(parent, m, link_prefix):
    """
        Returns a URL for `m`, which must be an instance of `Module`.
        Also, `m` must be a submodule of the module being documented.

        Namely, '.' import separators are replaced with '/' URL
        separators. Also, packages are translated as directories
        containing `index.html` corresponding to the `__init__` module,
        while modules are translated as regular HTML files with an
        `.m.html` suffix. (Given default values of
        `pdoc.html_module_suffix` and `pdoc.html_package_name`.)
    """
    if parent.name == m.name:
        return ""

    base = m.name.replace(".", "/")
    if len(link_prefix) == 0:
        base = os.path.relpath(base, parent.name.replace(".", "/"))
    url = base[len("../") :] if base.startswith("../") else "" if base == ".." else base
    if m.submodules:
        index = pdoc.render.html_package_name
        url = url + "/" + index if url else index
    else:
        url += pdoc.render.html_module_suffix
    return link_prefix + url

def external_url(refname):
    """
        Attempts to guess an absolute URL for the external identifier
        given.

        Note that this just returns the refname with an ".ext" suffix.
        It will be up to whatever is interpreting the URLs to map it
        to an appropriate documentation page.
    """
    return "/%s.ext" % refname

def is_external_linkable(name):
    return pyident.match(name) and "." in name

def lookup(module, refname, link_prefix):
    """
        Given a fully qualified identifier name, return its refname
        with respect to the current module and a value for a `href`
        attribute. If `refname` is not in the public interface of
        this module or its submodules, then `None` is returned for
        both return values. (Unless this module has enabled external
        linking.)

        In particular, this takes into account sub-modules and external
        identifiers. If `refname` is in the public API of the current
        module, then a local anchor link is given. If `refname` is in the
        public API of a sub-module, then a link to a different page with
        the appropriate anchor is given. Otherwise, `refname` is
        considered external and no link is used.
    """
    d = module.find_ident(refname)
    if isinstance(d, pdoc.doc.External):
        if is_external_linkable(refname):
            return d.refname, external_url(d.refname)
        else:
            return None, None
    if isinstance(d, pdoc.doc.Module):
        return d.refname, module_url(module, d, link_prefix)
    if module.is_public(d.refname):
        return d.name, "#%s" % d.refname
    return d.refname, "%s#%s" % (module_url(module, d.module, link_prefix), d.refname)

def link(parent, refname, link_prefix):
    """
        A convenience wrapper around `href` to produce the full
        `a` tag if `refname` is found. Otherwise, plain text of
        `refname` is returned.
    """
    name, url = lookup(parent, refname, link_prefix)
    if name is None:
        return refname
    return '%s' % (url, name)
<commit_msg>Fix invalid escape sequence \s in html_helpers.py<commit_after>import os
import re
import sys

import markdown2
import pygments
import pygments.formatters
import pygments.lexers

import pdoc.doc
import pdoc.render

# From language reference, but adds '.' to allow fully qualified names.
pyident = re.compile("^[a-zA-Z_][a-zA-Z0-9_.]+$")
indent = re.compile(r"^\s*")

def decode(s):
    if sys.version_info[0] < 3 and isinstance(s, str):
        return s.decode("utf-8", "ignore")
    return s

def ident(s):
    return '%s' % s

def sourceid(dobj):
    return "source-%s" % dobj.refname

def clean_source_lines(lines):
    """
  Cleans the source code so that pygments can render it well.

  Returns one string with all of the source code.
  """
    base_indent = len(indent.match(lines[0]).group(0))
    base_indent = 0
    for line in lines:
        if len(line.strip()) > 0:
            base_indent = len(indent.match(lines[0]).group(0))
            break
    lines = [line[base_indent:] for line in lines]

    if sys.version_info[0] < 3:
        pylex = pygments.lexers.PythonLexer()
    else:
        pylex = pygments.lexers.Python3Lexer()

    htmlform = pygments.formatters.HtmlFormatter(cssclass="codehilite")
    return pygments.highlight("".join(lines), pylex, htmlform)

def linkify(parent, match, link_prefix):
    matched = match.group(0)
    ident = matched[1:-1]
    name, url = lookup(parent, ident, link_prefix)
    if name is None:
        return matched
    return "[`%s`](%s)" % (name, url)

def mark(s, module_list=None, linky=True):
    if linky:
        s, _ = re.subn("\b\n\b", " ", s)
    # if not module_list:
    #     s, _ = re.subn("`[^`]+`", linkify, s)

    extensions = ["fenced-code-blocks"]
    s = markdown2.markdown(s.strip(), extras=extensions)
    return s

def glimpse(s, length=100):
    if len(s) < length:
        return s
    return s[0:length] + "..."

def module_url(parent, m, link_prefix):
    """
        Returns a URL for `m`, which must be an instance of `Module`.
        Also, `m` must be a submodule of the module being documented.

        Namely, '.' import separators are replaced with '/' URL
        separators. Also, packages are translated as directories
        containing `index.html` corresponding to the `__init__` module,
        while modules are translated as regular HTML files with an
        `.m.html` suffix. (Given default values of
        `pdoc.html_module_suffix` and `pdoc.html_package_name`.)
    """
    if parent.name == m.name:
        return ""

    base = m.name.replace(".", "/")
    if len(link_prefix) == 0:
        base = os.path.relpath(base, parent.name.replace(".", "/"))
    url = base[len("../") :] if base.startswith("../") else "" if base == ".." else base
    if m.submodules:
        index = pdoc.render.html_package_name
        url = url + "/" + index if url else index
    else:
        url += pdoc.render.html_module_suffix
    return link_prefix + url

def external_url(refname):
    """
        Attempts to guess an absolute URL for the external identifier
        given.

        Note that this just returns the refname with an ".ext" suffix.
        It will be up to whatever is interpreting the URLs to map it
        to an appropriate documentation page.
    """
    return "/%s.ext" % refname

def is_external_linkable(name):
    return pyident.match(name) and "." in name

def lookup(module, refname, link_prefix):
    """
        Given a fully qualified identifier name, return its refname
        with respect to the current module and a value for a `href`
        attribute. If `refname` is not in the public interface of
        this module or its submodules, then `None` is returned for
        both return values. (Unless this module has enabled external
        linking.)

        In particular, this takes into account sub-modules and external
        identifiers. If `refname` is in the public API of the current
        module, then a local anchor link is given. If `refname` is in the
        public API of a sub-module, then a link to a different page with
        the appropriate anchor is given. Otherwise, `refname` is
        considered external and no link is used.
    """
    d = module.find_ident(refname)
    if isinstance(d, pdoc.doc.External):
        if is_external_linkable(refname):
            return d.refname, external_url(d.refname)
        else:
            return None, None
    if isinstance(d, pdoc.doc.Module):
        return d.refname, module_url(module, d, link_prefix)
    if module.is_public(d.refname):
        return d.name, "#%s" % d.refname
    return d.refname, "%s#%s" % (module_url(module, d.module, link_prefix), d.refname)

def link(parent, refname, link_prefix):
    """
        A convenience wrapper around `href` to produce the full
        `a` tag if `refname` is found. Otherwise, plain text of
        `refname` is returned.
    """
    name, url = lookup(parent, refname, link_prefix)
    if name is None:
        return refname
    return '%s' % (url, name)
<|endoftext|>


<commit_before>from typing import Generator, Tuple

import numpy as np
import pandas as pd
import streamlit as st

@st.cache
def sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n: float
) -> Tuple[float, float, float]:
    """The SIR model, one time step."""
    s_n = (-beta * s * i) + s
    i_n = (beta * s * i - gamma * i) + i
    r_n = gamma * i + r
    if s_n < 0.0:
        s_n = 0.0
    if i_n < 0.0:
        i_n = 0.0
    if r_n < 0.0:
        r_n = 0.0

    scale = n / (s_n + i_n + r_n)
    return s_n * scale, i_n * scale, r_n * scale

def gen_sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> Generator:
    """Simulate SIR model forward in time yielding tuples."""
    s, i, r, beta_decay = (float(v) for v in (s, i, r, beta_decay))
    n = s + i + r
    for _ in range(n_days + 1):
        yield s, i, r
        s, i, r = sir(s, i, r, beta, gamma, n)
        # okay even if beta_decay is 0.0
        beta = beta * (1.0 - beta_decay)

@st.cache
def sim_sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Simulate the SIR model forward in time."""
    s, i, r, beta_decay = (float(v) for v in (s, i, r, beta_decay))
    n = s + i + r
    s_v, i_v, r_v = [s], [i], [r]
    for day in range(n_days):
        s, i, r = sir(s, i, r, beta, gamma, n)
        # okay even if beta_decay is 0.0
        beta = beta * (1.0 - beta_decay)
        s_v.append(s)
        i_v.append(i)
        r_v.append(r)

    return (
        np.array(s_v),
        np.array(i_v),
        np.array(r_v),
    )

@st.cache
def sim_sir_df(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> pd.DataFrame:
    """Simulate the SIR model forward in time."""
    return pd.DataFrame(
        data=gen_sir(s, i, r, beta, gamma, n_days, beta_decay),
        columns=("S", "I", "R"),
    )

@st.cache
def get_hospitalizations2(
    infected: np.ndarray, rates: Tuple[float, ...], market_share: float = 1.0
) -> Tuple[np.ndarray, ...]:
    """Get hopitalizations adjusted by rate and market_share."""
    return (*(infected * rate * market_share for rate in rates),)

@st.cache
def get_hospitalizations(
    infected: np.ndarray, rates: Tuple[float, float, float], market_share: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Get hopitalizations adjusted by rate and market_share."""
    hosp_rate, icu_rate, vent_rate = rates

    hosp = infected * hosp_rate * market_share
    icu = infected * icu_rate * market_share
    vent = infected * vent_rate * market_share
    return hosp, icu, vent
<commit_msg>Move (1.0 - beta_decay) static calculation out of inner loop<commit_after>from typing import Generator, Tuple

import numpy as np
import pandas as pd
import streamlit as st

@st.cache
def sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n: float
) -> Tuple[float, float, float]:
    """The SIR model, one time step."""
    s_n = (-beta * s * i) + s
    i_n = (beta * s * i - gamma * i) + i
    r_n = gamma * i + r
    if s_n < 0.0:
        s_n = 0.0
    if i_n < 0.0:
        i_n = 0.0
    if r_n < 0.0:
        r_n = 0.0

    scale = n / (s_n + i_n + r_n)
    return s_n * scale, i_n * scale, r_n * scale

def gen_sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> Generator[Tuple[float, float, float], None, None]:
    """Simulate SIR model forward in time yielding tuples."""
    s, i, r = (float(v) for v in (s, i, r))
    n = s + i + r
    f = 1.0 - beta_decay  # okay even if beta_decay is 0.0
    for _ in range(n_days + 1):
        yield s, i, r
        s, i, r = sir(s, i, r, beta, gamma, n)
        beta *= f

@st.cache
def sim_sir(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Simulate the SIR model forward in time."""
    s, i, r = (float(v) for v in (s, i, r))
    n = s + i + r
    f = 1.0 - beta_decay  # okay even if beta_decay is 0.0
    s_v, i_v, r_v = [s], [i], [r]
    for day in range(n_days):
        s, i, r = sir(s, i, r, beta, gamma, n)
        beta *= f
        s_v.append(s)
        i_v.append(i)
        r_v.append(r)

    return (
        np.array(s_v),
        np.array(i_v),
        np.array(r_v),
    )

@st.cache
def sim_sir_df(
    s: float, i: float, r: float,
    beta: float, gamma: float, n_days: int, beta_decay: float = 0.0
) -> pd.DataFrame:
    """Simulate the SIR model forward in time."""
    return pd.DataFrame(
        data=gen_sir(s, i, r, beta, gamma, n_days, beta_decay),
        columns=("S", "I", "R"),
    )

@st.cache
def get_hospitalizations2(
    infected: np.ndarray, rates: Tuple[float, ...], market_share: float = 1.0
) -> Tuple[np.ndarray, ...]:
    """Get hopitalizations adjusted by rate and market_share."""
    return (*(infected * rate * market_share for rate in rates),)

@st.cache
def get_hospitalizations(
    infected: np.ndarray, rates: Tuple[float, float, float], market_share: float
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Get hopitalizations adjusted by rate and market_share."""
    hosp_rate, icu_rate, vent_rate = rates

    hosp = infected * hosp_rate * market_share
    icu = infected * icu_rate * market_share
    vent = infected * vent_rate * market_share
    return hosp, icu, vent
<|endoftext|>


<commit_before>import discord

from cogs.utils import checks
from discord.ext import commands

class Config:
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def countservers(self):
        """
        Checks how many servers the bot is on"""
        msg = "The bot is in **"
        msg += str(len(self.bot.servers))
        msg += "** servers."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def shout(self, server_id, *, message):
        """
        Shouts a message to the main channel of a certain server"""
        msg = "```asciidoc\n"
        msg += "Announcement :: Information\n"
        msg += message
        msg += "\n```"
        for server in self.bot.servers:
            if server.id == server_id:
                try:
                    await self.bot.send_message(server, msg)
                    await self.bot.say("'" + message + "'" + " has been send to " + server.name + ".")
                except discord.errors.Forbidden:
                    await self.bot.say("I'm not allowed to do that.")

    @commands.command()
    @checks.is_owner()
    async def listservers(self):
        """
        Checks what servers the bot is on"""
        servers = self.bot.servers
        await self.bot.say("```asciidoc\nThe bot is in the following {} server(s):\n```".format(str(len(self.bot.servers))))
        msg = "```asciidoc\n"
        #msg += "\n"

        messages = []
        count = 0
        for server in servers:
            messages[count] = "```asciidoc\n"
            if len(server.members)<10:
                messages[count] += "{:<1} :: 000{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<100:
                messages[count] += "{:<1} :: 00{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<1000:
                messages[count] += "{:<1} :: 0{} users :: {}".format(server.id, len(server.members), server.name)
            else:
                messages[count] += "{:<1} :: {} users :: {}".format(server.id, len(server.members), server.name)
            messages[count] += "\n"
            if len(messages[count])>1500:
                count = count+1
        for message in messages:
            if len(message) > 30:
                await self.bot.say(message + "\n```")

    @commands.command(pass_context = True)
    @checks.is_owner()
    async def discrim(self, ctx, discriminator):
        """
        Find users with this discriminator"""
        msg = "Users with discriminator " + discriminator
        msg += ": \n"
        for r in self.bot.get_all_members():
            if r.discriminator == discriminator:
                if r.name in msg:
                    pass
                else:
                    msg += "```\n"
                    msg += r.name
                    msg += "\n```"
        await self.bot.say(msg)

    @commands.command()
    async def countusers(self):
        """
        Checks how many users the bot is connected to"""
        msg = "The bot is connected to **"
        msg += str(len(set(self.bot.get_all_members())))
        msg += "** users."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def notify(self, *, content):
        """Notifies every server"""
        if content == "shutdown":
            msg = "```asciidoc\n"
            msg += "Announcement :: Shutdown\n"
            msg += "riceBot shutting down... Will be up again soon!"
            msg += "\n```"
        elif content == "info":
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "Thank you for inviting riceBot!\n"
            msg += "For basic information on the bot, a list of commands, or to contact the owner, use: \n"
            msg += "= rice.rice =\n"
            msg += "= rice.help =\n"
            msg += "= rice.contact =\n"
            msg += "To add the bot to your own server, open this:: https://discordsites.com/ricebot/\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "riceBot ~ managed by FwiedWice"
            msg += "\n```"
        else:
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += content
            msg += "\n```"
        for server in self.bot.servers:
            try:
                await self.bot.send_message(server, msg)
            except discord.errors.Forbidden:
                pass
        await self.bot.say("Message succesfully sent")

    @commands.command()
    @checks.is_owner()

    async def speak(self, *, content):

        """Says something"""
        await self.bot.say(content)

def setup(bot):
    bot.add_cog(Config(bot))
<commit_msg>fixed character limit<commit_after>import discord

from cogs.utils import checks
from discord.ext import commands

class Config:
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def countservers(self):
        """
        Checks how many servers the bot is on"""
        msg = "The bot is in **"
        msg += str(len(self.bot.servers))
        msg += "** servers."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def shout(self, server_id, *, message):
        """
        Shouts a message to the main channel of a certain server"""
        msg = "```asciidoc\n"
        msg += "Announcement :: Information\n"
        msg += message
        msg += "\n```"
        for server in self.bot.servers:
            if server.id == server_id:
                try:
                    await self.bot.send_message(server, msg)
                    await self.bot.say("'" + message + "'" + " has been send to " + server.name + ".")
                except discord.errors.Forbidden:
                    await self.bot.say("I'm not allowed to do that.")

    @commands.command()
    @checks.is_owner()
    async def listservers(self):
        """
        Checks what servers the bot is on"""
        servers = self.bot.servers
        await self.bot.say("```asciidoc\nThe bot is in the following {} server(s):\n```".format(str(len(self.bot.servers))))
        msg = "```asciidoc\n"
        msg2 = "```asciidoc\n"
        msg3 = "```asciidoc\n"
        msg4 = "```asciidoc\n"
        #msg += "\n"

        messages = [msg, msg2, msg3, msg4]
        count = 0
        for server in servers:
            if len(server.members)<10:
                messages[count] += "{:<1} :: 000{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<100:
                messages[count] += "{:<1} :: 00{} users :: {}".format(server.id, len(server.members), server.name)
            elif len(server.members)<1000:
                messages[count] += "{:<1} :: 0{} users :: {}".format(server.id, len(server.members), server.name)
            else:
                messages[count] += "{:<1} :: {} users :: {}".format(server.id, len(server.members), server.name)
            messages[count] += "\n"
            if len(messages[count])>1500:
                count = count+1

        for message in messages:
            if len(message) > 30:
                await self.bot.say(message + "\n```")

    @commands.command(pass_context = True)
    @checks.is_owner()
    async def discrim(self, ctx, discriminator):
        """
        Find users with this discriminator"""
        msg = "Users with discriminator " + discriminator
        msg += ": \n"
        for r in self.bot.get_all_members():
            if r.discriminator == discriminator:
                if r.name in msg:
                    pass
                else:
                    msg += "```\n"
                    msg += r.name
                    msg += "\n```"
        await self.bot.say(msg)

    @commands.command()
    async def countusers(self):
        """
        Checks how many users the bot is connected to"""
        msg = "The bot is connected to **"
        msg += str(len(set(self.bot.get_all_members())))
        msg += "** users."
        await self.bot.say(msg)

    @commands.command()
    @checks.is_owner()
    async def notify(self, *, content):
        """Notifies every server"""
        if content == "shutdown":
            msg = "```asciidoc\n"
            msg += "Announcement :: Shutdown\n"
            msg += "riceBot shutting down... Will be up again soon!"
            msg += "\n```"
        elif content == "info":
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "Thank you for inviting riceBot!\n"
            msg += "For basic information on the bot, a list of commands, or to contact the owner, use: \n"
            msg += "= rice.rice =\n"
            msg += "= rice.help =\n"
            msg += "= rice.contact =\n"
            msg += "To add the bot to your own server, open this:: https://discordsites.com/ricebot/\n"
            msg += "= -=-=-=-=-=-=-=-=-=-=-=- =\n"
            msg += "riceBot ~ managed by FwiedWice"
            msg += "\n```"
        else:
            msg = "```asciidoc\n"
            msg += "Announcement :: Information\n"
            msg += content
            msg += "\n```"
        for server in self.bot.servers:
            try:
                await self.bot.send_message(server, msg)
            except discord.errors.Forbidden:
                pass
        await self.bot.say("Message succesfully sent")

    @commands.command()
    @checks.is_owner()

    async def speak(self, *, content):

        """Says something"""
        await self.bot.say(content)

def setup(bot):
    bot.add_cog(Config(bot))
<|endoftext|>


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

import sys
import argparse
import os
import subprocess
import json
import hashlib
import requests
from coverage import parse_gcov

def gitcmd( *arguments ):
  gitcmd = 'git'
  if sys.platform.startswith('win'):
    gitcmd = 'git.exe'
  return subprocess.check_output( ['git'] + list( arguments ) )

def gitlog( format ):
  return gitcmd( '--no-pager', 'log', '-1', '--pretty=format:%s' % format )

def gitinfo():
  return {
    'branch' : gitcmd( 'rev-parse', '--abbrev-ref', 'HEAD' ).rstrip(),
    'remotes' : [ { 'name': remote.split()[0], 'url': remote.split()[1] } for remote in gitcmd( 'remote', '-v' ).split( '\n' ) if '(fetch)' in remote ],
    'head' : {
      'id' : gitlog( '%H' ),
      'message' : gitlog( '%s' ),
      'author_name' : gitlog( '%aN' ),
      'author_email' : gitlog( '%ae' ),
      'committer_name' : gitlog( '%cN' ),
      'committer_email' : gitlog( '%ce' )
    }
  }

def read_prefs( filename ):
  if not os.path.isfile( filename ):
    return
  file = open( filename, 'r' )
  prefs = json.load( file )
  file.close()
  return prefs

def merge_reports( basereport, addreport ):
  baselen = len(basereport)
  addlen = len(addreport)
  for line in range( 0, addlen ):
    if line >= baselen:
      basereport.append( addreport[line] )
    elif basereport[line] == None:
      basereport[line] = addreport[line]
    elif basereport[line] == 0 and addreport[line] != None:
      basereport[line] = addreport[line]
    elif addreport[line] != None:
      basereport[line] += addreport[line]
  return basereport

def post_report(prefs, coverage):
  info = gitinfo()
  response = requests.post('https://codecov.io/upload/v2?token=' + prefs['token'] + '&commit=' + info['head']['id'] + '&branch=' + info['branch'] + '&job=' + prefs['job'], data = json.dumps(coverage))
  try:
    result = response.json()
  except ValueError:
    result = { 'error': 'Failure to submit data. '
               'Response [%(status)s]: %(text)s' % {
               'status': response.status_code,
               'text': response.text } }
  return result

argparser = argparse.ArgumentParser( description = 'Ninja build generator' )
argparser.add_argument( '-o', '--objectdir', required = True,
                     help = 'Object directory' )
argparser.add_argument( '-s', '--sourcedir', required = True,
                     help = 'Source directory' )
argparser.add_argument( '-m,', '--merge', action = 'append',
                     help = 'Merge in previous report',
                     default = [] )
argparser.add_argument( '-p', '--post', action='store_true',
                     help = 'Post results to codecov.io',
                     default = False )
options = argparser.parse_args()

infiles = {}
for file in os.listdir( options.objectdir ):
  basefile = os.path.splitext(file)[0]
  if file.endswith(".gcda"):
    if not basefile in infiles:
      infiles[basefile] = ( False, False )
    infiles[basefile] = ( True, infiles[basefile][1] )
  elif file.endswith(".gcno"):
    if not basefile in infiles:
      infiles[basefile] = ( False, False )
    infiles[basefile] = ( infiles[basefile][0], True )

sourcefiles = {}
for file in os.listdir( options.sourcedir ):
  if file.endswith(".c") or file.endswith(".m"):
    sourcefiles[file] = []

for key, pair in infiles.iteritems():
  if pair[0] and pair[1]:
    if sys.platform == "darwin":
      subprocess.check_output( [ "gcov", "-gcda=" + os.path.join( options.objectdir, key + ".gcda" ), "-gcno=" + os.path.join( options.objectdir, key + ".gcno" ), "source" ] )
    else:
      subprocess.check_output( [ "gcov", "-o", options.objectdir, "-s", options.sourcedir, key + ".o" ] )
    for file in os.listdir('.'):
      if file.endswith(".gcov"):
        sourcefile = os.path.splitext(file)[0]
        if sourcefile in sourcefiles:
          results = parse_gcov( file )
          sourcefiles[sourcefile] = merge_reports( sourcefiles[sourcefile], results )
        os.remove( file )

for reportfile in options.merge:
  with open( reportfile, 'r' ) as infile:
    report = json.load( infile )
    infile.close()
    sourcelist = report['source_files']
    for sourcefile in sourcelist:
      filename = os.path.basename( sourcefile['name'] )
      if not filename in sourcefiles:
        sourcefiles[filename] = []
      results = sourcefile['coverage']
      sourcefiles[filename] = merge_reports( sourcefiles[filename], results )

coverage = {}
for sourcefile, report in sourcefiles.iteritems():
  if len(report) > 0:
    coverage[os.path.join( options.sourcedir, sourcefile )] = [None] + report

prefs = read_prefs( 'codecov.json' )

codecov = {}
codecov['coverage'] = coverage

if options.post:
  result = post_report(prefs, codecov)
  print result
else:
  with open( 'codecovreport.json', 'w' ) as outfile:
    json.dump( codecov, outfile )
<commit_msg>change code coverage to use llvm<commit_after>#!/usr/bin/env python

import sys
import argparse
import os
import subprocess
import json
import hashlib
import requests
from coverage import parse_gcov

def gitcmd( *arguments ):
  gitcmd = 'git'
  if sys.platform.startswith('win'):
    gitcmd = 'git.exe'
  return subprocess.check_output( ['git'] + list( arguments ) )

def gitlog( format ):
  return gitcmd( '--no-pager', 'log', '-1', '--pretty=format:%s' % format )

def gitinfo():
  return {
    'branch' : gitcmd( 'rev-parse', '--abbrev-ref', 'HEAD' ).rstrip(),
    'remotes' : [ { 'name': remote.split()[0], 'url': remote.split()[1] } for remote in gitcmd( 'remote', '-v' ).split( '\n' ) if '(fetch)' in remote ],
    'head' : {
      'id' : gitlog( '%H' ),
      'message' : gitlog( '%s' ),
      'author_name' : gitlog( '%aN' ),
      'author_email' : gitlog( '%ae' ),
      'committer_name' : gitlog( '%cN' ),
      'committer_email' : gitlog( '%ce' )
    }
  }

def read_prefs( filename ):
  if not os.path.isfile( filename ):
    return
  file = open( filename, 'r' )
  prefs = json.load( file )
  file.close()
  return prefs

def merge_reports( basereport, addreport ):
  baselen = len(basereport)
  addlen = len(addreport)
  for line in range( 0, addlen ):
    if line >= baselen:
      basereport.append( addreport[line] )
    elif basereport[line] == None:
      basereport[line] = addreport[line]
    elif basereport[line] == 0 and addreport[line] != None:
      basereport[line] = addreport[line]
    elif addreport[line] != None:
      basereport[line] += addreport[line]
  return basereport

def post_report(prefs, coverage):
  info = gitinfo()
  response = requests.post('https://codecov.io/upload/v2?token=' + prefs['token'] + '&commit=' + info['head']['id'] + '&branch=' + info['branch'] + '&job=' + prefs['job'], data = json.dumps(coverage))
  try:
    result = response.json()
  except ValueError:
    result = { 'error': 'Failure to submit data. '
               'Response [%(status)s]: %(text)s' % {
               'status': response.status_code,
               'text': response.text } }
  return result

argparser = argparse.ArgumentParser( description = 'Ninja build generator' )
argparser.add_argument( '-o', '--objectdir', required = True,
                     help = 'Object directory' )
argparser.add_argument( '-s', '--sourcedir', required = True,
                     help = 'Source directory' )
argparser.add_argument( '-m,', '--merge', action = 'append',
                     help = 'Merge in previous report',
                     default = [] )
argparser.add_argument( '-p', '--post', action='store_true',
                     help = 'Post results to codecov.io',
                     default = False )
options = argparser.parse_args()

infiles = {}
for file in os.listdir( options.objectdir ):
  basefile = os.path.splitext(file)[0]
  if file.endswith(".gcda"):
    if not basefile in infiles:
      infiles[basefile] = ( False, False )
    infiles[basefile] = ( True, infiles[basefile][1] )
  elif file.endswith(".gcno"):
    if not basefile in infiles:
      infiles[basefile] = ( False, False )
    infiles[basefile] = ( infiles[basefile][0], True )

sourcefiles = {}
for file in os.listdir( options.sourcedir ):
  if file.endswith(".c") or file.endswith(".m"):
    sourcefiles[file] = []

for key, pair in infiles.iteritems():
  if pair[0] and pair[1]:
    if sys.platform == "darwin":
      subprocess.check_output( [ "gcov", "-gcda=" + os.path.join( options.objectdir, key + ".gcda" ), "-gcno=" + os.path.join( options.objectdir, key + ".gcno" ), "source" ] )
    else:
      sourcefile = os.path.basename(key).rsplit('-', 1)[0]
      subprocess.check_output(["llvm-cov", "gcov", "-o", os.path.join(options.objectdir, key + ".o"), os.path.join(options.sourcedir, sourcefile + ".c")])
      #subprocess.check_output( [ "gcov", "-o", options.objectdir, "-s", options.sourcedir, key + ".o" ] )
    for file in os.listdir('.'):
      if file.endswith(".gcov"):
        sourcefile = os.path.splitext(file)[0]
        if sourcefile in sourcefiles:
          results = parse_gcov( file )
          sourcefiles[sourcefile] = merge_reports( sourcefiles[sourcefile], results )
        os.remove( file )

for reportfile in options.merge:
  with open( reportfile, 'r' ) as infile:
    report = json.load( infile )
    infile.close()
    sourcelist = report['source_files']
    for sourcefile in sourcelist:
      filename = os.path.basename( sourcefile['name'] )
      if not filename in sourcefiles:
        sourcefiles[filename] = []
      results = sourcefile['coverage']
      sourcefiles[filename] = merge_reports( sourcefiles[filename], results )

coverage = {}
for sourcefile, report in sourcefiles.iteritems():
  if len(report) > 0:
    coverage[os.path.join( options.sourcedir, sourcefile )] = [None] + report

prefs = read_prefs( 'codecov.json' )

codecov = {}
codecov['coverage'] = coverage

if options.post:
  result = post_report(prefs, codecov)
  print result
else:
  with open( 'codecovreport.json', 'w' ) as outfile:
    json.dump( codecov, outfile )
<|endoftext|>


<commit_before>import os
import sys
sys.path.insert(0, os.path.abspath('..'))

import kernel_tuner.cuda as cuda
import kernel_tuner.opencl as opencl
import kernel_tuner.interface as kernel_tuner

from nose import SkipTest
from nose.tools import nottest

@nottest
def skip_if_no_cuda_device():
    try:
        from pycuda.autoinit import context
    except ImportError:
        raise SkipTest("PyCuda not installed")

@nottest
def skip_if_no_opencl():
    try:
        import pyopencl
    except ImportError as e:
        raise SkipTest("PyOpenCL not installed")

<commit_msg>small fix to cuda tests<commit_after>import os
import sys
sys.path.insert(0, os.path.abspath('..'))

import kernel_tuner.cuda as cuda
import kernel_tuner.opencl as opencl
import kernel_tuner.interface as kernel_tuner

from nose import SkipTest
from nose.tools import nottest

@nottest
def skip_if_no_cuda_device():
    try:
        from pycuda.autoinit import context
    except (ImportError, Exception) as e:
        raise SkipTest("PyCuda not installed")

@nottest
def skip_if_no_opencl():
    try:
        import pyopencl
    except ImportError as e:
        raise SkipTest("PyOpenCL not installed")

<|endoftext|>