<commit_before>import discord
from discord.ext import commands
import time
import datetime
import socket

import os
import psutil

class Basic:
    def __init__(self, bot):
        self.bot = bot
        self.process = psutil.Process(os.getpid())

    @commands.command(aliases=['about'])
    async def info(self, ctx):
        """Returns bot's info."""
        local_time = str(datetime.datetime.now()).split('.')[0]
        total_guild_count = len(self.bot.guilds)
        total_user_count = len(list(self.bot.get_all_members()))
        total_unique_user_count = len(list(set(self.bot.get_all_members())))
        bot_info = await self.bot.application_info()
        owner = str(bot_info.owner)

        mem_bytes = self.process.memory_full_info().rss
        mem_mb = round(mem_bytes / 1024 / 1024, 2)
        cpu_usage = round(self.process.cpu_percent() / psutil.cpu_count(), 2)

        secs_since_boot = int(time.time()) - self.bot.start_time
        uptime = str(datetime.timedelta(seconds=secs_since_boot))

        em = discord.Embed()

        em.add_field(name="Git Hash", value=self.bot.get_git_revision_short_hash())
        em.add_field(name="Last git message", value=self.bot.get_git_commit_text())
        em.add_field(name="Hostname", value=socket.gethostname())
        em.add_field(name="Guild count", value=total_guild_count)
        em.add_field(name="Local Time", value=local_time)
        em.add_field(name="Unique users", value=total_unique_user_count)
        em.add_field(name="Owner", value=owner)
        em.add_field(name="RAM Usage", value=f"{mem_mb}MiB")
        em.add_field(name="CPU Percentage", value=f"{cpu_usage}%")
        em.add_field(name="Invite", value="https://bot.ave.zone/add")
        em.add_field(name="Uptime", value=uptime)

        em.set_author(name='AveBot v3', icon_url='https://s.ave.zone/c7d.png')
        await ctx.send(embed=em)

    @commands.command(aliases=['addavebot'])
    async def invite(self, ctx):
        """Gives a link that can be used to add AveBot."""
        inviteurl = discord.utils.oauth_url(self.bot.user.id)
        await ctx.send(f"You can use the following link to add AveBot to your server:\n<{inviteurl}>")

    @commands.command()
    async def ginvite(self, ctx, discordid: int):
        """Generates a discord invite link."""
        inviteurl = discord.utils.oauth_url(discordid)
        await ctx.send(f"<{inviteurl}>")

    @commands.command()
    async def servercount(self, ctx):
        """Returns the amount of servers AveBot is in."""
        total_guild_count = len(self.bot.guilds)
        total_user_count = len(list(self.bot.get_all_members()))
        total_unique_user_count = len(list(set(self.bot.get_all_members())))
        await ctx.send(f"AveBot is in {total_guild_count} servers with {total_user_count} total users ({total_unique_user_count} unique).")

    @commands.command()
    async def ping(self, ctx):
        """Shows ping values to discord."""
        before = time.monotonic()
        tmp = await ctx.send('Calculating ping...')
        after = time.monotonic()
        rtt_ms = (after - before) * 1000
        gw_ms = self.bot.latency * 1000

        message_text = f":ping_pong: rtt: {rtt_ms:.1f}ms, gw: {gw_ms:.1f}ms"
        self.bot.log.info(message_text)
        await tmp.edit(content=message_text)

    @commands.guild_only()
    @commands.command(aliases=['serverinfo'])
    async def sinfo(self, ctx):
        """Shows info about the current server."""
        current_guild = ctx.guild
        em = discord.Embed(title=f"Server info of {current_guild.name} ({current_guild.id})")

        region_replace = {"us-west": ":flag_us: US West", "us-east": ":flag_us: US East",
        "us-south": ":flag_us: US South", "us-central": ":flag_us: US Central",
        "eu-west": ":flag_eu: EU West", "eu-central": ":flag_eu: EU Central",
        "singapore": ":flag_si: Singapore", "london": ":flag_uk: London, UK",
        "sydney": ":flag_au: Sydney, AU", "amsterdam": ":flag_nl: Amsterdam, NL",
        "frankfurt": ":flag_de: Frankfurt, DE", "brazil": "<:lunadab:406845118105124864> Brazil",
        "hongkong": ":flag_hk: Hong Kong", "russia": ":flag_ru: Russia",
        "vip-us-east": ":flag_us: VIP US East", "vip-us-west": ":flag_us: VIP US West",
        "vip-amsterdam": ":flag_nl: VIP Amsterdam, NL"} # All this effort for :lunahahayes:

        region_text = str(current_guild.region)
        region_text = region_replace[region_text] if region_text in region_replace else region_text

        em.add_field(name="User Count", value=current_guild.member_count)
        em.add_field(name="Region", value=region_text)
        em.add_field(name="Owner", value=current_guild.owner)
        em.add_field(name="Verification Level", value=current_guild.verification_level)
        em.add_field(name="Created at", value=current_guild.created_at)

        em.set_thumbnail(url=current_guild.icon_url)
        await ctx.send(embed=em)

    @commands.command(aliases=['contact'])
    async def feedback(self, ctx, *, contact_text: str):
        """Contacts developers with a message."""
        em = discord.Embed(description=contact_text)

        author_name = f"{ctx.message.author} ({ctx.message.author.id}) "
        author_name += f"on \"{ctx.channel.name}\" at \"{ctx.guild.name}\"" if ctx.guild else "through DMs"

        em.set_author(name=author_name, icon_url=ctx.message.author.avatar_url)

        support_channel = self.bot.get_channel(int(self.bot.config['base']['support-channel']))
        await support_channel.send(embed=em)

        em = discord.Embed(title='Feedback sent!',
                           description='Your message has been delivered to the developers.')
        await ctx.send(embed=em)

    @commands.command(aliases=['userinfo', 'whoami', 'profile'])
    async def uinfo(self, ctx, *, user: discord.User = None):
        """Shows info about the user.

        info: returns info about the user who ran the command
        uinfo <mention/name>: returns info about the mentioned user"""

        if user is None:
            user = ctx.author

        if ctx.guild:
            maybe_member = ctx.guild.get_member(user.id)
            if maybe_member:
                user = maybe_member

        embed = discord.Embed(title=f"User Info of {str(user)}")

        if (ctx.message.author.avatar != ""):
            embed.set_thumbnail(url=ctx.message.author.avatar_url)
        embed.set_footer(text=f"UserID: {user.id}")

        embed.add_field(name="Joined Discord", value=str(user.created_at))
        if ctx.guild and maybe_member:
            embed.add_field(name="Joined Server", value=str(user.joined_at))
            embed.add_field(name="Status", value=str(user.status))
        if user.game:
            embed.add_field(name="Game", value=user.game.name)
        is_bot_display = ":white_check_mark:" if user.bot else ":x:"
        embed.add_field(name="Is bot", value=is_bot_display)

        await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Basic(bot))<commit_msg>info: visual changes<commit_after>import discord
from discord.ext import commands
import time
import datetime
import socket

import os
import psutil

class Basic:
    def __init__(self, bot):
        self.bot = bot
        self.process = psutil.Process(os.getpid())

    @commands.command(aliases=['about'])
    async def info(self, ctx):
        """Returns bot's info."""
        local_time = str(datetime.datetime.now()).split('.')[0]
        total_guild_count = len(self.bot.guilds)
        total_user_count = len(list(self.bot.get_all_members()))
        total_unique_user_count = len(list(set(self.bot.get_all_members())))
        bot_info = await self.bot.application_info()
        owner = str(bot_info.owner)

        mem_bytes = self.process.memory_full_info().rss
        mem_mb = round(mem_bytes / 1024 / 1024, 2)
        cpu_usage = round(self.process.cpu_percent() / psutil.cpu_count(), 2)

        secs_since_boot = int(time.time()) - self.bot.start_time
        uptime = str(datetime.timedelta(seconds=secs_since_boot))

        em = discord.Embed()

        em.add_field(name="Git Hash", value=self.bot.get_git_revision_short_hash())
        em.add_field(name="Last git message", value=self.bot.get_git_commit_text())
        em.add_field(name="Hostname", value=socket.gethostname())
        em.add_field(name="Guild count", value=total_guild_count)
        em.add_field(name="Unique users", value=total_unique_user_count)
        em.add_field(name="Local Time", value=local_time)
        em.add_field(name="RAM Usage", value=f"{mem_mb}MiB")
        em.add_field(name="CPU Percentage", value=f"{cpu_usage}%")
        em.add_field(name="Uptime", value=uptime)
        em.add_field(name="Owner", value=owner)
        em.add_field(name="Invite", value="https://bot.ave.zone/add")

        em.set_author(name='AveBot v3', icon_url='https://s.ave.zone/c7d.png')
        await ctx.send(embed=em)

    @commands.command(aliases=['addavebot'])
    async def invite(self, ctx):
        """Gives a link that can be used to add AveBot."""
        inviteurl = discord.utils.oauth_url(self.bot.user.id)
        await ctx.send(f"You can use the following link to add AveBot to your server:\n<{inviteurl}>")

    @commands.command()
    async def ginvite(self, ctx, discordid: int):
        """Generates a discord invite link."""
        inviteurl = discord.utils.oauth_url(discordid)
        await ctx.send(f"<{inviteurl}>")

    @commands.command()
    async def servercount(self, ctx):
        """Returns the amount of servers AveBot is in."""
        total_guild_count = len(self.bot.guilds)
        total_user_count = len(list(self.bot.get_all_members()))
        total_unique_user_count = len(list(set(self.bot.get_all_members())))
        await ctx.send(f"AveBot is in {total_guild_count} servers with {total_user_count} total users ({total_unique_user_count} unique).")

    @commands.command()
    async def ping(self, ctx):
        """Shows ping values to discord."""
        before = time.monotonic()
        tmp = await ctx.send('Calculating ping...')
        after = time.monotonic()
        rtt_ms = (after - before) * 1000
        gw_ms = self.bot.latency * 1000

        message_text = f":ping_pong: rtt: {rtt_ms:.1f}ms, gw: {gw_ms:.1f}ms"
        self.bot.log.info(message_text)
        await tmp.edit(content=message_text)

    @commands.guild_only()
    @commands.command(aliases=['serverinfo'])
    async def sinfo(self, ctx):
        """Shows info about the current server."""
        current_guild = ctx.guild
        em = discord.Embed(title=f"Server info of {current_guild.name} ({current_guild.id})")

        region_replace = {"us-west": ":flag_us: US West", "us-east": ":flag_us: US East",
        "us-south": ":flag_us: US South", "us-central": ":flag_us: US Central",
        "eu-west": ":flag_eu: EU West", "eu-central": ":flag_eu: EU Central",
        "singapore": ":flag_si: Singapore", "london": ":flag_uk: London, UK",
        "sydney": ":flag_au: Sydney, AU", "amsterdam": ":flag_nl: Amsterdam, NL",
        "frankfurt": ":flag_de: Frankfurt, DE", "brazil": "<:lunadab:406845118105124864> Brazil",
        "hongkong": ":flag_hk: Hong Kong", "russia": ":flag_ru: Russia",
        "vip-us-east": ":flag_us: VIP US East", "vip-us-west": ":flag_us: VIP US West",
        "vip-amsterdam": ":flag_nl: VIP Amsterdam, NL"} # All this effort for :lunahahayes:

        region_text = str(current_guild.region)
        region_text = region_replace[region_text] if region_text in region_replace else region_text

        em.add_field(name="User Count", value=current_guild.member_count)
        em.add_field(name="Region", value=region_text)
        em.add_field(name="Owner", value=current_guild.owner)
        em.add_field(name="Verification Level", value=current_guild.verification_level)
        em.add_field(name="Created at", value=current_guild.created_at)

        em.set_thumbnail(url=current_guild.icon_url)
        await ctx.send(embed=em)

    @commands.command(aliases=['contact'])
    async def feedback(self, ctx, *, contact_text: str):
        """Contacts developers with a message."""
        em = discord.Embed(description=contact_text)

        author_name = f"{ctx.message.author} ({ctx.message.author.id}) "
        author_name += f"on \"{ctx.channel.name}\" at \"{ctx.guild.name}\"" if ctx.guild else "through DMs"

        em.set_author(name=author_name, icon_url=ctx.message.author.avatar_url)

        support_channel = self.bot.get_channel(int(self.bot.config['base']['support-channel']))
        await support_channel.send(embed=em)

        em = discord.Embed(title='Feedback sent!',
                           description='Your message has been delivered to the developers.')
        await ctx.send(embed=em)

    @commands.command(aliases=['userinfo', 'whoami', 'profile'])
    async def uinfo(self, ctx, *, user: discord.User = None):
        """Shows info about the user.

        info: returns info about the user who ran the command
        uinfo <mention/name>: returns info about the mentioned user"""

        if user is None:
            user = ctx.author

        if ctx.guild:
            maybe_member = ctx.guild.get_member(user.id)
            if maybe_member:
                user = maybe_member

        embed = discord.Embed(title=f"User Info of {str(user)}")

        if (ctx.message.author.avatar != ""):
            embed.set_thumbnail(url=ctx.message.author.avatar_url)
        embed.set_footer(text=f"UserID: {user.id}")

        embed.add_field(name="Joined Discord", value=str(user.created_at))
        if ctx.guild and maybe_member:
            embed.add_field(name="Joined Server", value=str(user.joined_at))
            embed.add_field(name="Status", value=str(user.status))
        if user.game:
            embed.add_field(name="Game", value=user.game.name)
        is_bot_display = ":white_check_mark:" if user.bot else ":x:"
        embed.add_field(name="Is bot", value=is_bot_display)

        await ctx.send(embed=embed)

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


<commit_before>from distutils.core import setup

setup(
    name='django_replicated',
    version='1.1',
    description='Django DB router for stateful master-slave replication',
    packages=[
        'django_replicated',
    ],
)
<commit_msg>bump version<commit_after>from distutils.core import setup

setup(
    name='django_replicated',
    version='1.2',
    description='Django DB router for stateful master-slave replication',
    packages=[
        'django_replicated',
    ],
)
<|endoftext|>


<commit_before>import discord

from discord.ext import commands
from dateutil.parser import isoparse
from utils import aiohttp_wrap as aw

class Covid(commands.Cog):
    COLOR = discord.Color.red()
    URL = "https://api.covidtracking.com/v1"

    @commands.command(name="covid", aliases=["c19", "rona", "corona"])
    async def _covid(self, ctx, *, state: str=None):
        """Get current US covid statistics, optionally passing a 2-letter state code"""
        if state is not None:
            if len(state) != 2:
                await ctx.message.add_reaction("❌")
                return await ctx.send("Use 2-letter state identifiers", delete_after=10)

        if state is None:
            location = "the US"
            data = (await aw.aio_get_json(ctx.bot.aio_session, f"{self.URL}/us/current.json"))[0]
        else:
            location = state.upper()
            data = await aw.aio_get_json(ctx.bot.aio_session, f"{self.URL}/states/{state.lower()}/current.json")

        if "error" in data:
            if data["error"]:
                await ctx.message.add_reaction("❌")
                return await ctx.send("Something went wrong with the covid API :(", delete_after=10)

        em = discord.Embed()
        em.title = f"😷 Current Covid statistics in {location}"
        em.timestamp = isoparse(data["lastModified"])

        em.add_field(name="📈 New cases today", value=f"{data['positiveIncrease']:,}")
        em.add_field(name="☠ Deaths today", value=f"{data['deathIncrease']:,}")
        em.add_field(name="⚰ Total Deaths", value=f"{data['death']:,}")

        em.set_footer(text="Last updated")

        await ctx.send(embed=em)

def setup(bot):
    bot.add_cog(Covid(bot))
<commit_msg>👟🐛& add more datapoints to embed<commit_after>import discord

from discord.ext import commands
from dateutil.parser import isoparse
from utils import aiohttp_wrap as aw

class Covid(commands.Cog):
    COLOR = discord.Color.red()
    URL = "https://api.covidtracking.com/v1"

    @commands.command(name="covid", aliases=["c19", "rona", "corona"])
    async def _covid(self, ctx, *, state: str=None):
        """Get current US covid statistics, optionally passing a 2-letter state code"""
        if state is not None:
            if len(state) != 2:
                await ctx.message.add_reaction("❌")
                return await ctx.send("Use 2-letter state identifiers", delete_after=10)

        if state is None:
            location = "the US"
            data = (await aw.aio_get_json(ctx.bot.aio_session, f"{self.URL}/us/current.json"))[0]
        else:
            location = state.upper()
            data = await aw.aio_get_json(ctx.bot.aio_session, f"{self.URL}/states/{state.lower()}/current.json")

        if "error" in data:
            if data["error"]:
                await ctx.message.add_reaction("❌")
                return await ctx.send("Something went wrong with the covid API :(", delete_after=10)

        em = discord.Embed()
        em.title = f"😷 Current Covid statistics in {location}"
        em.timestamp = isoparse(data["lastModified"] if "lastModified" in data else data["dateModified"])

        em.add_field(name="📈 New cases today", value=f"{data['positiveIncrease']:,}")
        em.add_field(name="☠ Deaths today", value=f"{data['deathIncrease']:,}")
        em.add_field(name="⚰ Total Deaths", value=f"{data['death']:,}", inline=False)

        if "qualityGrade" in data:
            em.add_field(name="📝 Data quality", value=data["qualityGrade"] or "n/a")

        em.set_footer(text="Last updated")

        await ctx.send(embed=em)

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


<commit_before>import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-vote',
    version='1.0.2',
    packages=['vote'],
    include_package_data=True,
    license='BSD License',
    description='A simple Django app to conduct vote.',
    long_description=README,
    url='https://github.com/Beeblio/django-vote',
    author='shellfly',
    author_email='shell0fly@gmail.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<commit_msg>update dist info<commit_after>import os
from setuptools import setup

README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-vote',
    version='1.0.3',
    packages=['vote'],
    include_package_data=True,
    license='BSD License',
    description='A simple Django app to conduct vote.',
    long_description=README,
    url='https://github.com/Beeblio/django-vote',
    author='shellfly',
    author_email='shell0fly@gmail.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<|endoftext|>


<commit_before>import os.path
from setuptools import Command, find_packages, setup

HERE = os.path.abspath(os.path.dirname(__file__))

README_PATH = os.path.join(HERE, 'README.rst')
try:
    README = open(README_PATH).read()
except IOError:
    README = ''

setup(
    name='rollbar-agent',
    data_files=[('', ['rollbar-agent', 'rollbar-agent-init.sh', 'rollbar-agent.conf', 'LICENSE', 'requirements.txt'])],
    version='0.3.1',
    description='Rollbar server-side agent',
    long_description=README,
    author='Rollbar, Inc.',
    author_email='support@rollbar.com',
    url='http://github.com/rollbar/rollbar-agent',
    classifiers=[
        "Programming Language :: Python",
        "License :: OSI Approved :: MIT License",
        "Development Status :: 3 - Alpha",
        "Environment :: Web Environment",
        "Intended Audience :: Developers",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
        "Topic :: Software Development",
        "Topic :: Software Development :: Bug Tracking",
        "Topic :: Software Development :: Testing",
        "Topic :: Software Development :: Quality Assurance",
        ],
    install_requires=[
        'requests',
        ],
    )

<commit_msg>bump version to 0.3.2<commit_after>import os.path
from setuptools import Command, find_packages, setup

HERE = os.path.abspath(os.path.dirname(__file__))

README_PATH = os.path.join(HERE, 'README.rst')
try:
    README = open(README_PATH).read()
except IOError:
    README = ''

setup(
    name='rollbar-agent',
    data_files=[('', ['rollbar-agent', 'rollbar-agent-init.sh', 'rollbar-agent.conf', 'LICENSE', 'requirements.txt'])],
    version='0.3.2',
    description='Rollbar server-side agent',
    long_description=README,
    author='Rollbar, Inc.',
    author_email='support@rollbar.com',
    url='http://github.com/rollbar/rollbar-agent',
    classifiers=[
        "Programming Language :: Python",
        "License :: OSI Approved :: MIT License",
        "Development Status :: 3 - Alpha",
        "Environment :: Web Environment",
        "Intended Audience :: Developers",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
        "Topic :: Software Development",
        "Topic :: Software Development :: Bug Tracking",
        "Topic :: Software Development :: Testing",
        "Topic :: Software Development :: Quality Assurance",
        ],
    install_requires=[
        'requests',
        ],
    )

<|endoftext|>


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

import re
import os

try:
    from setuptools import setup
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup

def get_version(package):
    """
    Return package version as listed in `__version__` in `init.py`.
    """
    init_py = open(os.path.join(package, "__init__.py")).read()
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)

setup(
    name="drf-haystack",
    version=get_version("drf_haystack"),
    description="Makes Haystack play nice with Django REST Framework",
    long_description="Implements a ViewSet, FiltersBackends and Serializers in order to play nice with Haystack.",
    author="Rolf Håvard Blindheim, Eirik Krogstad",
    author_email="rolf.blindheim@inonit.no, eirik.krogstad@inonit.no",
    url="https://github.com/inonit/drf-haystack",
    download_url="https://github.com/inonit/drf-haystack.git",
    license="MIT License",
    packages=[
        "drf_haystack",
    ],
    include_package_data=True,
    install_requires=[
        "Django>=1.5.0",
        "djangorestframework>=2.4.4",
        "django-haystack>=2.3.1",
        "python-dateutil"
    ],
    tests_require=[
        "nose",
        "coverage",
        "unittest2",
        "elasticsearch>=1.4.0",
    ],
    zip_safe=False,
    test_suite="tests.runtests.start",
    classifiers=[
        "Operating System :: OS Independent",
        "Development Status :: 5 - Production/Stables",
        "Environment :: Web Environment",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ]
)
<commit_msg>Fixed Typo in Trove Classifier<commit_after># -*- coding: utf-8 -*-

import re
import os

try:
    from setuptools import setup
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup

def get_version(package):
    """
    Return package version as listed in `__version__` in `init.py`.
    """
    init_py = open(os.path.join(package, "__init__.py")).read()
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)

setup(
    name="drf-haystack",
    version=get_version("drf_haystack"),
    description="Makes Haystack play nice with Django REST Framework",
    long_description="Implements a ViewSet, FiltersBackends and Serializers in order to play nice with Haystack.",
    author="Rolf Håvard Blindheim, Eirik Krogstad",
    author_email="rolf.blindheim@inonit.no, eirik.krogstad@inonit.no",
    url="https://github.com/inonit/drf-haystack",
    download_url="https://github.com/inonit/drf-haystack.git",
    license="MIT License",
    packages=[
        "drf_haystack",
    ],
    include_package_data=True,
    install_requires=[
        "Django>=1.5.0",
        "djangorestframework>=2.4.4",
        "django-haystack>=2.3.1",
        "python-dateutil"
    ],
    tests_require=[
        "nose",
        "coverage",
        "unittest2",
        "elasticsearch>=1.4.0",
    ],
    zip_safe=False,
    test_suite="tests.runtests.start",
    classifiers=[
        "Operating System :: OS Independent",
        "Development Status :: 5 - Production/Stable",
        "Environment :: Web Environment",
        "Framework :: Django",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ]
)
<|endoftext|>


<commit_before># noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.common import user_agent

class Animemes:
    def __init__(self, bot):
        self.bot = bot
        self.config = json.load(open('config.json'))

    @commands.command()
    async def neko(self, ctx):
        """Shows a random neko picture"""
        async with self.bot.session.get('https://nekos.life/api/neko', headers=user_agent) as neko:
            if neko.status == 200:
                img = await neko.json()
                neko_em = discord.Embed(colour=0x690E8)
                neko_em.set_image(url=img['neko'])
                neko_em.set_footer(text='Powered by nekos.life - use ^lneko to get lewd version')
                await ctx.send(embed=neko_em)
            else:
                raise utils.errors.ServiceError(f'dude rip (http {neko.status})')

    @commands.command()
    async def lneko(self, ctx):
        """NSFW: Shows a random lewd neko pic
        Disable this command by putting "[lb:no_nsfw]" in your channel topic.
        """
        if ctx.channel.is_nsfw():
            if '[lb:no_nsfw]' in ctx.channel.topic:
                raise utils.errors.NSFWException()
            else:
                async with self.bot.session.get('https://nekos.life/api/lewd/neko', headers=user_agent) as lneko:
                    if lneko.status == 200:
                        img = await lneko.json()
                        # noinspection PyPep8Naming
                        lneko_em = discord.Embed(colour=0x690E8)
                        lneko_em.set_image(url=img['neko'])
                        await ctx.send(embed=lneko_em)
                        neko_em.set_footer(text='Powered by nekos.life - use ^neko to get non-nsfw version')
                    else:
                        raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
        else:
            raise utils.errors.NSFWException('you really think you can do this'
                                             'in a non nsfw channel? lol')

def setup(bot):
    bot.add_cog(Animemes(bot))
<commit_msg>cogs[nekos]: damn<commit_after># noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.common import user_agent

class Animemes:
    def __init__(self, bot):
        self.bot = bot
        self.config = json.load(open('config.json'))

    @commands.command()
    async def neko(self, ctx):
        """Shows a random neko picture"""
        async with self.bot.session.get('https://nekos.life/api/neko', headers=user_agent) as neko:
            if neko.status == 200:
                img = await neko.json()
                neko_em = discord.Embed(colour=0x690E8)
                neko_em.set_image(url=img['neko'])
                neko_em.set_footer(text='Powered by nekos.life - use ^lneko to get lewd version')
                await ctx.send(embed=neko_em)
            else:
                raise utils.errors.ServiceError(f'dude rip (http {neko.status})')

    @commands.command()
    async def lneko(self, ctx):
        """NSFW: Shows a random lewd neko pic
        Disable this command by putting "[lb:no_nsfw]" in your channel topic.
        """
        if ctx.channel.is_nsfw():
            if '[lb:no_nsfw]' in ctx.channel.topic:
                raise utils.errors.NSFWException()
            else:
                async with self.bot.session.get('https://nekos.life/api/lewd/neko', headers=user_agent) as lneko:
                    if lneko.status == 200:
                        img = await lneko.json()
                        # noinspection PyPep8Naming
                        lneko_em = discord.Embed(colour=0x690E8)
                        lneko_em.set_image(url=img['neko'])
                        await ctx.send(embed=lneko_em)
                        lneko_em.set_footer(text='Powered by nekos.life - use ^neko to get non-nsfw version')
                    else:
                        raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
        else:
            raise utils.errors.NSFWException('you really think you can do this'
                                             'in a non nsfw channel? lol')

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


<commit_before># -*- coding: utf-8 -*-
__author__ = "aganezov"

from setuptools import setup

from gos import version as gos_version

setup(
    name="gos",
    version=gos_version,
    packages=["gos", "tests"],
    install_requires=list(map(lambda entry: entry.strip(), open("requirements.txt", "rt").readlines())),
    author="Sergey Aganezov",
    author_email="aganezov@gwu.edu",
    description="Gene order based scaffolding tool for multiple genomes",
    license="LGPLv3",
    keywords=["breakpoint graph", "data structures", "python", "scaffolding", "gene order"],
    url="https://github.com/sergey-aganezov-jr/gos",
    classifiers=[
        "Development Status :: 1 - Planning",
        "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ]
)<commit_msg>setup.py file update with new description and links<commit_after># -*- coding: utf-8 -*-
__author__ = "aganezov"

from setuptools import setup

from gos import version as gos_version

setup(
    name="gos",
    version="0.0.0",
    packages=["gos", "tests"],
    install_requires=list(map(lambda entry: entry.strip(), open("requirements.txt", "rt").readlines())),
    author="Sergey Aganezov",
    author_email="aganezov@gwu.edu",
    description="Generically organizable supervisor to create multi-level executable pipelines",
    license="LGPLv3",
    keywords=["breakpoint graph", "data structures", "python", "scaffolding", "gene order"],
    url="https://github.com/aganezov/gos",
    classifiers=[
        "Development Status :: 1 - Planning",
        "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5'
    ]
)<|endoftext|>


<commit_before># noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors

class Animemes:
    def __init__(self, bot):
        self.bot = bot
        self.config = json.load(open('config.json'))
        self.header = {
            'User-Agent': 'lolbot (discord.py/aiohttp)'
        }

    @commands.command()
    async def neko(self, ctx):
        """Shows a random neko picture"""
        async with self.bot.session.get('https://nekos.life/api/neko', headers=self.header) as neko:
            if neko.status == 200:
                img = await neko.json()
                neko_em = discord.Embed(colour=0x690E8)
                neko_em.set_image(url=img['neko'])
                await ctx.send(embed=neko_em)
            else:
                raise utils.errors.ServiceError(f'dude rip (http {neko.status})')

    @commands.command()
    async def lneko(self, ctx):
        """Shows a random lewd neko pic"""
        if ctx.channel.is_nsfw():
            async with self.bot.session.get('https://nekos.life/api/lewd/neko', headers=self.header) as lneko:
                if lneko.status == 200:
                    img = await lneko.json()
                    # noinspection PyPep8Naming
                    lneko_em = discord.Embed(colour=0x690E8)
                    lneko_em.set_image(url=img['neko'])
                    await ctx.send(embed=lneko_em)
                else:
                    raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
        else:
            raise utils.errors.NSFWException('you really think you can do this'
                                             'in a non nsfw channel? lol')

def setup(bot):
    bot.add_cog(Animemes(bot))
<commit_msg>cogs[nekos]: use common user agent<commit_after># noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.common import user_agent

class Animemes:
    def __init__(self, bot):
        self.bot = bot
        self.config = json.load(open('config.json'))

    @commands.command()
    async def neko(self, ctx):
        """Shows a random neko picture"""
        async with self.bot.session.get('https://nekos.life/api/neko', headers=user_agent) as neko:
            if neko.status == 200:
                img = await neko.json()
                neko_em = discord.Embed(colour=0x690E8)
                neko_em.set_image(url=img['neko'])
                await ctx.send(embed=neko_em)
            else:
                raise utils.errors.ServiceError(f'dude rip (http {neko.status})')

    @commands.command()
    async def lneko(self, ctx):
        """Shows a random lewd neko pic"""
        if ctx.channel.is_nsfw():
            async with self.bot.session.get('https://nekos.life/api/lewd/neko', headers=user_agent) as lneko:
                if lneko.status == 200:
                    img = await lneko.json()
                    # noinspection PyPep8Naming
                    lneko_em = discord.Embed(colour=0x690E8)
                    lneko_em.set_image(url=img['neko'])
                    await ctx.send(embed=lneko_em)
                else:
                    raise utils.errors.ServiceError(f'dude rip (http {lneko.status})')
        else:
            raise utils.errors.NSFWException('you really think you can do this'
                                             'in a non nsfw channel? lol')

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


<commit_before>from setuptools import setup, find_packages  # pylint: disable=no-name-in-module,import-error

def dependencies(file):
    with open(file) as f:
        return f.read().splitlines()

with open("README.md", encoding='utf-8') as infile:
    long_description = infile.read()

setup(
    name='halo',
    packages=find_packages(exclude=('tests', 'examples')),
    version='0.0.23',
    license='MIT',
    description='Beautiful terminal spinners in Python',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Manraj Singh',
    author_email='manrajsinghgrover@gmail.com',
    url='https://github.com/manrajgrover/halo',
    keywords=[
        "console",
        "loading",
        "indicator",
        "progress",
        "cli",
        "spinner",
        "spinners",
        "terminal",
        "term",
        "busy",
        "wait",
        "idle"
    ],
    install_requires=dependencies('requirements.txt'),
    tests_require=dependencies('requirements-dev.txt'),
    include_package_data=True,
    extras_require={
        'ipython': [
            'IPython==5.7.0',
            'ipywidgets==7.1.0',
        ]
    }
)
<commit_msg>Use io.open to support Python 2<commit_after>import io
from setuptools import setup, find_packages  # pylint: disable=no-name-in-module,import-error

def dependencies(file):
    with open(file) as f:
        return f.read().splitlines()

with io.open("README.md", encoding='utf-8') as infile:
    long_description = infile.read()

setup(
    name='halo',
    packages=find_packages(exclude=('tests', 'examples')),
    version='0.0.23',
    license='MIT',
    description='Beautiful terminal spinners in Python',
    long_description=long_description,
    long_description_content_type="text/markdown",
    author='Manraj Singh',
    author_email='manrajsinghgrover@gmail.com',
    url='https://github.com/manrajgrover/halo',
    keywords=[
        "console",
        "loading",
        "indicator",
        "progress",
        "cli",
        "spinner",
        "spinners",
        "terminal",
        "term",
        "busy",
        "wait",
        "idle"
    ],
    install_requires=dependencies('requirements.txt'),
    tests_require=dependencies('requirements-dev.txt'),
    include_package_data=True,
    extras_require={
        'ipython': [
            'IPython==5.7.0',
            'ipywidgets==7.1.0',
        ]
    }
)
<|endoftext|>


<commit_before>"""
Owner stuff

Originally made by luna for Jose, the best bot
"""
import os
import traceback
import asyncio
import logging
# noinspection PyPackageRequirements
import discord

# noinspection PyPackageRequirements
from discord.ext import commands

async def run_cmd(cmd: str) -> str:
    """Runs a subprocess and returns the output."""
    process = await asyncio.create_subprocess_shell(
        cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    results = await process.communicate()
    return "".join(x.decode("utf-8") for x in results)

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

    @commands.command(hidden=True)
    @commands.is_owner()
    async def game(self, ctx, *, game: str):
        """Change playing status"""
        haha = ctx.bot.config['prefix']
        try:
            await self.bot.change_presence(
                game=discord.Game(name=f'{game} | {haha}help | v1.1', type=1, url='https://twitch.tv/monstercat'))
        except Exception:
            await ctx.send(f'```\n{traceback.format_exc()}\n```')
        else:
            await ctx.send(':white_check_mark: Successfully changed game')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def shutdown(self, ctx):
        """Shuts down the bot"""
        await self.bot.session.close()
        await self.bot.logout()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def reboot(self, ctx):
        """Reboots the bot.
        Can only be used with PM2"""
        restart_land = discord.Embed(title='Restarting', description='Please wait...')
        restart_msg = await ctx.send(embed=restart_land)
        pm2_id = os.environ.get('pm_id')
        if pm2_id:
            await restart_msg.edit(content='Logging out and restarting. Bye!')
            await self.bot.session.close()
            await self.bot.logout
            await run_cmd(f'pm2 restart {pm2_id}')
        else:
            await restart_message.edit(content=':warning: pm2 not detected, invoking `shutdown` command')
            await ctx.invoke(self.bot.get_command('shutdown'))

    @commands.command(hidden=True)
    @commands.is_owner()
    async def load(self, ctx, extension_name: str):
        """Loads a cog"""
        try:
            self.bot.load_extension('cogs.' + extension_name)
        except ModuleNotFoundError:
            await ctx.send(f':x: Cog `{extension_name}` not found.')
            return
        except Exception:
            await ctx.send(f'```py\n{traceback.format_exc()}\n```')
            return
        logging.info(f'owner[load]: cog {extension_name} loaded')
        await ctx.send(f':ok_hand: `{extension_name}` loaded.')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def unload(self, ctx, extension_name: str):
        """Unloads a cog"""
        self.bot.unload_extension('cogs.' + extension_name)
        logging.info(f'owner[unload]: cog {extension_name} unloaded')
        await ctx.send(f':ok_hand: `{extension_name}` unloaded.')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def reload(self, ctx, extension_name: str):
        """Reloads a cog"""
        try:
            self.bot.unload_extension('cogs.' + extension_name)
            self.bot.load_extension('cogs.' + extension_name)
        except ModuleNotFoundError:
            await ctx.send(f':x: Cog `{extension_name}` not found.')
            return
        except Exception:
            await ctx.send(f'```{traceback.format_exc()}```')
            return
        logging.info(f'owner[reload]: cog {extension_name} reloaded')
        await ctx.send(f':ok_hand: Reloaded `{extension_name}`')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def shell(self, ctx, *, command: str):
        """Run stuff"""
        with ctx.typing():
            p = await asyncio.create_subprocess_shell(command,
                                                      stderr=asyncio.subprocess.PIPE,
                                                      stdout=asyncio.subprocess.PIPE,
                                                      )

            out, err = map(lambda s: s.decode('utf-8'), await p.communicate())

        result = f'{out}{err}'
        await ctx.send(f"`{command}`: ```{result}```\n")

    @commands.command(hidden=True)
    @commands.is_owner()
    async def update(self, ctx):
        """Lazy much? Whatever..."""
        await ctx.invoke(self.bot.get_command('shell'), command='git pull')

def setup(bot):
    bot.add_cog(Owner(bot))
<commit_msg>cogs[owner]: batch loading cogs<commit_after>"""
Owner stuff

Originally made by luna for Jose, the best bot
"""
import os
import traceback
import asyncio
import logging
# noinspection PyPackageRequirements
import discord

# noinspection PyPackageRequirements
from discord.ext import commands

async def run_cmd(cmd: str) -> str:
    """Runs a subprocess and returns the output."""
    process = await asyncio.create_subprocess_shell(
        cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    results = await process.communicate()
    return "".join(x.decode("utf-8") for x in results)

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

    @commands.command(hidden=True)
    @commands.is_owner()
    async def game(self, ctx, *, game: str):
        """Change playing status"""
        haha = ctx.bot.config['prefix']
        try:
            await self.bot.change_presence(
                game=discord.Game(name=f'{game} | {haha}help | v1.1', type=1, url='https://twitch.tv/monstercat'))
        except Exception:
            await ctx.send(f'```\n{traceback.format_exc()}\n```')
        else:
            await ctx.send(':white_check_mark: Successfully changed game')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def shutdown(self, ctx):
        """Shuts down the bot"""
        await self.bot.session.close()
        await self.bot.logout()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def reboot(self, ctx):
        """Reboots the bot.
        Can only be used with PM2"""
        restart_land = discord.Embed(title='Restarting', description='Please wait...')
        restart_msg = await ctx.send(embed=restart_land)
        pm2_id = os.environ.get('pm_id')
        if pm2_id:
            await restart_msg.edit(content='Logging out and restarting. Bye!')
            await self.bot.session.close()
            await self.bot.logout
            await run_cmd(f'pm2 restart {pm2_id}')
        else:
            await restart_message.edit(content=':warning: pm2 not detected, invoking `shutdown` command')
            await ctx.invoke(self.bot.get_command('shutdown'))

    @commands.command(hidden=True)
    @commands.is_owner()
    async def load(self, ctx, *exts: str):
        """Loads a cog"""
        for ext in exts:
            try:
                self.bot.load_extension('cogs.' + extension_name)
            except ModuleNotFoundError:
                await ctx.send(f':x: Cog `{extension_name}` not found.')
                return
            except Exception:
                await ctx.send(f'```py\n{traceback.format_exc()}\n```')
                return
            logging.info(f'owner[load]: cog {extension_name} loaded')
            await ctx.send(f':ok_hand: `{extension_name}` loaded.')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def unload(self, ctx, *exts: str):
        """Unloads a cog"""
        for ext in exts:
            self.bot.unload_extension('cogs.' + extension_name)
            logging.info(f'owner[unload]: cog {extension_name} unloaded')
        await ctx.send(f':ok_hand: `{extension_name}` unloaded.')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def reload(self, ctx, *exts: str):
        """Reloads a cog"""
        try:
            self.bot.unload_extension('cogs.' + extension_name)
            self.bot.load_extension('cogs.' + extension_name)
        except ModuleNotFoundError:
            await ctx.send(f':x: Cog `{extension_name}` not found.')
            return
        except Exception:
            await ctx.send(f'```{traceback.format_exc()}```')
            return
        logging.info(f'owner[reload]: cog {extension_name} reloaded')
        await ctx.send(f':ok_hand: Reloaded `{extension_name}`')

    @commands.command(hidden=True)
    @commands.is_owner()
    async def shell(self, ctx, *, command: str):
        """Run stuff"""
        with ctx.typing():
            p = await asyncio.create_subprocess_shell(command,
                                                      stderr=asyncio.subprocess.PIPE,
                                                      stdout=asyncio.subprocess.PIPE,
                                                      )

            out, err = map(lambda s: s.decode('utf-8'), await p.communicate())

        result = f'{out}{err}'
        await ctx.send(f"`{command}`: ```{result}```\n")

    @commands.command(hidden=True)
    @commands.is_owner()
    async def update(self, ctx):
        """Lazy much? Whatever..."""
        await ctx.invoke(self.bot.get_command('shell'), command='git pull')

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


<commit_before>from os import environ
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager
import flask.ext.restless

# Initialize Flask app and database:
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = "Not really a secret."
app.config['ENVIRONMENT'] = "LOCAL"
app.config['DEFAULT_OWNER_NAME'] = "Default owner name"
app.config['DEFAULT_OWNER_REASON'] = "Default owner reason"
app.config['DEFAULT_OWNER_EMAIL'] = "Default owner email"

try:
	app.config.from_object('local_config')
except:
	try:
		app.config['SECRET_KEY'] = environ['SECRET_KEY']
		app.config['ENVIRONMENT'] = environ['ENVIRONMENT']
		app.config['APPLICATION_URL'] = environ['APPLICATION_URL']
		app.config['SCRIBD_API_KEY'] = environ['SCRIBD_API_KEY']
		app.config['SCRIBD_API_SECRET'] = environ['SCRIBD_API_SECRET']
		app.config['DEFAULT_OWNER_NAME'] = environ['DEFAULT_OWNER_NAME']
		app.config['DEFAULT_OWNER_EMAIL'] = environ['DEFAULT_OWNER_EMAIL']
		app.config['DEFAULT_OWNER_REASON'] = environ['DEFAULT_OWNER_REASON']
		app.config['MAIL_USERNAME'] = environ['MAIL_USERNAME']
		app.config['MAIL_PASSWORD'] = environ['MAIL_PASSWORD']
		app.config['ADMIN_PASSWORD'] = environ['ADMIN_PASSWORD']
		app.config['DEFAULT_MAIL_SENDER'] = environ['DEFAULT_MAIL_SENDER']
		app.config['HOST_URL'] = environ['HOST_URL']
		app.config['SQLALCHEMY_DATABASE_URI'] = environ['SQLALCHEMY_DATABASE_URI']
	except:
		print "Config variables were not set"

db = SQLAlchemy(app)
from public_records_portal import models
from models import *

# Create API
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Request, methods=['GET', 'POST', 'PUT', 'DELETE'], results_per_page=None)
manager.create_api(Owner, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Note, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Record, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Note, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(QA, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Subscriber, methods=['GET', 'POST', 'PUT', 'DELETE'])<commit_msg>Fixes #34, updating API for Owner to not be paginated<commit_after>from os import environ
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restless import APIManager
import flask.ext.restless

# Initialize Flask app and database:
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = "Not really a secret."
app.config['ENVIRONMENT'] = "LOCAL"
app.config['DEFAULT_OWNER_NAME'] = "Default owner name"
app.config['DEFAULT_OWNER_REASON'] = "Default owner reason"
app.config['DEFAULT_OWNER_EMAIL'] = "Default owner email"

try:
	app.config.from_object('local_config')
except:
	try:
		app.config['SECRET_KEY'] = environ['SECRET_KEY']
		app.config['ENVIRONMENT'] = environ['ENVIRONMENT']
		app.config['APPLICATION_URL'] = environ['APPLICATION_URL']
		app.config['SCRIBD_API_KEY'] = environ['SCRIBD_API_KEY']
		app.config['SCRIBD_API_SECRET'] = environ['SCRIBD_API_SECRET']
		app.config['DEFAULT_OWNER_NAME'] = environ['DEFAULT_OWNER_NAME']
		app.config['DEFAULT_OWNER_EMAIL'] = environ['DEFAULT_OWNER_EMAIL']
		app.config['DEFAULT_OWNER_REASON'] = environ['DEFAULT_OWNER_REASON']
		app.config['MAIL_USERNAME'] = environ['MAIL_USERNAME']
		app.config['MAIL_PASSWORD'] = environ['MAIL_PASSWORD']
		app.config['ADMIN_PASSWORD'] = environ['ADMIN_PASSWORD']
		app.config['DEFAULT_MAIL_SENDER'] = environ['DEFAULT_MAIL_SENDER']
		app.config['HOST_URL'] = environ['HOST_URL']
		app.config['SQLALCHEMY_DATABASE_URI'] = environ['SQLALCHEMY_DATABASE_URI']
	except:
		print "Config variables were not set"

db = SQLAlchemy(app)
from public_records_portal import models
from models import *

# Create API
manager = APIManager(app, flask_sqlalchemy_db=db)
manager.create_api(Request, methods=['GET', 'POST', 'PUT', 'DELETE'], results_per_page=None)
manager.create_api(Owner, methods=['GET', 'POST', 'PUT', 'DELETE'], results_per_page = None)
manager.create_api(Note, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Record, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Note, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(QA, methods=['GET', 'POST', 'PUT', 'DELETE'])
manager.create_api(Subscriber, methods=['GET', 'POST', 'PUT', 'DELETE'])<|endoftext|>


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

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from setuptools import find_packages, setup

setup(
    name='TwistedChecker',
    description='A Twisted coding standard compliance checker.',
    version='0.2.0',
    author='Twisted Matrix Laboratories',
    author_email='twisted-python@twistedmatrix.com',
    url='https://launchpad.net/twistedchecker',
    packages=find_packages(),
    package_data={
        "twistedchecker": ["configuration/pylintrc"]
        },
    scripts=[
        'bin/twistedchecker'
        ],
    license='MIT',
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Topic :: Software Development :: Quality Assurance"
        ],
    keywords=[
        "twisted", "checker", "compliance", "pep8"
        ],
    install_requires=[
        "pylint == 0.26.0",
        "pep8"
        ],
    long_description=file('README.rst').read()
    )
<commit_msg>Update setup.py to point at Github. (closes #78)<commit_after>#!/usr/bin/env python

# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from setuptools import find_packages, setup

setup(
    name='TwistedChecker',
    description='A Twisted coding standard compliance checker.',
    version='0.2.0',
    author='Twisted Matrix Laboratories',
    author_email='twisted-python@twistedmatrix.com',
    url='https://github.com/twisted/twistedchecker',
    packages=find_packages(),
    package_data={
        "twistedchecker": ["configuration/pylintrc"]
        },
    scripts=[
        'bin/twistedchecker'
        ],
    license='MIT',
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Topic :: Software Development :: Quality Assurance"
        ],
    keywords=[
        "twisted", "checker", "compliance", "pep8"
        ],
    install_requires=[
        "pylint == 0.26.0",
        "pep8"
        ],
    long_description=file('README.rst').read()
    )
<|endoftext|>


<commit_before>import os
import ast
from setuptools import setup

PACKAGE_NAME = 'pyx'

def load_description(fname):
    here = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(here, fname)) as f:
        return f.read().strip()

def get_version(fname):
    with open(fname) as f:
        source = f.read()
    module = ast.parse(source)
    for e in module.body:
        if isinstance(e, ast.Assign) and \
                len(e.targets) == 1 and \
                e.targets[0].id == '__version__' and \
                isinstance(e.value, ast.Str):
            return e.value.s
    raise RuntimeError('__version__ not found')

setup(
    name='pyxserver',
    packages=[PACKAGE_NAME],
    version=get_version('{}/version.py'.format(PACKAGE_NAME)),
    description='Yet another async web server',
    long_description=load_description('README.rst'),
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.4',
    ],
    keywords=['http', 'web', 'server'],
    author='Kay Zheng',
    author_email='l04m33@gmail.com',
    url='https://github.com/l04m33/pyx',
    license='http://l04m33.mit-license.org/',
    zip_safe=False,
    install_requires=[],
    extras_require={
        'dev': ['nose', 'coverage']
    },
    entry_points='''
    [console_scripts]
    {0} = {0}.cmd:main
    '''.format(PACKAGE_NAME),
)
<commit_msg>Include tests package<commit_after>import os
import ast
from setuptools import setup

PACKAGE_NAME = 'pyx'

def load_description(fname):
    here = os.path.dirname(os.path.abspath(__file__))
    with open(os.path.join(here, fname)) as f:
        return f.read().strip()

def get_version(fname):
    with open(fname) as f:
        source = f.read()
    module = ast.parse(source)
    for e in module.body:
        if isinstance(e, ast.Assign) and \
                len(e.targets) == 1 and \
                e.targets[0].id == '__version__' and \
                isinstance(e.value, ast.Str):
            return e.value.s
    raise RuntimeError('__version__ not found')

setup(
    name='pyxserver',
    packages=['pyx', 'pyx.tests'],
    version=get_version('{}/version.py'.format(PACKAGE_NAME)),
    description='Yet another async web server',
    long_description=load_description('README.rst'),
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.4',
    ],
    keywords=['http', 'web', 'server'],
    author='Kay Zheng',
    author_email='l04m33@gmail.com',
    url='https://github.com/l04m33/pyx',
    license='http://l04m33.mit-license.org/',
    zip_safe=False,
    install_requires=[],
    extras_require={
        'dev': ['nose', 'coverage']
    },
    entry_points='''
    [console_scripts]
    {0} = {0}.cmd:main
    '''.format(PACKAGE_NAME),
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.

try:
    from setuptools import setup, find_packages
except ImportError:
    try:
        from distribute_setup import use_setuptools
        use_setuptools()
        from setuptools import setup, find_packages
    except ImportError:
        raise RuntimeError("python setuptools is required to build gcecloudstack")

VERSION = '0.0.1'

import os

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read().strip()

setup(name="gcecloudstack",
      version=VERSION,
      description="Web Server exposing a GCE interface to Apache CloudStack",
      author="",
      author_email="",
      long_description="Google Compute Engine Interface to the Apache CloudStack API",
      platforms=("Any",),
      license="LICENSE.txt",
      package_data={'': ['LICENSE.txt','server.crt','server.key']},
      packages = ["gcecloudstack", "gcecloudstack.controllers",
                  "gcecloudstack.services", "pyoauth2"],
      install_requires=[
          "flask",
          "requests==0.14",
          "pycrypto==2.6",
          "pyopenssl",
	  "Flask-SQLAlchemy",
      ],
      zip_safe=False,
      entry_points="""
    [console_scripts]
    gcecloudstack = gcecloudstack.appserver:main
    """,
      )
<commit_msg>Adjust seutp.py to include the models<commit_after>#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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.

try:
    from setuptools import setup, find_packages
except ImportError:
    try:
        from distribute_setup import use_setuptools
        use_setuptools()
        from setuptools import setup, find_packages
    except ImportError:
        raise RuntimeError("python setuptools is required to build gcecloudstack")

VERSION = '0.0.1'

import os

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read().strip()

setup(name="gcecloudstack",
      version=VERSION,
      description="Web Server exposing a GCE interface to Apache CloudStack",
      author="",
      author_email="",
      long_description="Google Compute Engine Interface to the Apache CloudStack API",
      platforms=("Any",),
      license="LICENSE.txt",
      package_data={'': ['LICENSE.txt','server.crt','server.key']},
      packages = ["gcecloudstack", "gcecloudstack.controllers","gcecloudstack.models",
                  "gcecloudstack.services", "pyoauth2"],
      install_requires=[
          "flask",
          "requests==0.14",
          "pycrypto==2.6",
          "pyopenssl",
	  "Flask-SQLAlchemy",
      ],
      zip_safe=False,
      entry_points="""
    [console_scripts]
    gcecloudstack = gcecloudstack.appserver:main
    """,
      )
<|endoftext|>


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

import numpy
import random
from itertools import permutations

class graph:
  '''A graph data structure.

  The data structure consists of a dictionary for which each element is a
  node.  Each node stores a dictionary of all other nodes to which the node
  is connected along with the length of the edge.
  '''

  def __init__(self, name=None):
    '''Initialize the graph.

    Parameters:
      name: any type
        The name of the node.  This should usually be a short string or an
        integer.
    '''
    if name is None:
      self.G = {}
    elif type(name) is dict:
      for elem in name:
        if type(name[elem]) is not dict:
          raise ValueError('graph.__init__(): cast to graph failed!')
      self.G = {}
      for elem in name:
        self.G[elem] = name[elem]
    else:
      self.G = {name : {}}

  def __getitem__(self, i):
    '''Return the edges connected to a specific node.'''
    if i not in self.G:
      raise ValueError('node not in graph!')
    return self.G[i]

  def copy(self):
    '''Return a deep copy of the graph.'''
    H = {}
    for elem in self.G:
      H[elem] = self.G[elem]
    return graph(H)

  def add_node(self, name, edges=None):
    '''Add a node to the graph.

    Parameters:
      name: any type
        The name of the node.  This should usually be a short string or an
        integer.

      edges: dict, optional
        The nodes this new node connects to.  The key for each element of
        this dictionary is the name of an adjacent node and the associated
        value is the length of the corresponding edge.
        '''

    #
    # First perform some checks on the received data types.
    #

    # Make sure that the node is not already in the graph
    if name in self.G:
      raise ValueError('graph.add_node(): node already in graph!')

    if edges is None:
      self.G[name] = {}

    else:
      # Make sure that the edges are a dictionary
      if type(edges) is not dict:
        raise TypeError('graph.add_node(): edges must be a dictionary!')
      for elem in edges:
        # Make sure the length is some kind of number
        if not isinstance(edges[elem], (int, long, float)):
          raise TypeError('graph.add_node(): ' + str(elem) +
          ': edge length is not a number!')
        # Check that the edges are to nodes already in the graph
        if elem not in self.G:
          raise ValueError('graph.add_node(): ' + str(elem) +
          ': edge connects to nonexistant node!')

      # First add the node
      self.G[name] = edges

      # Now update all the adjacent nodes
      for adj_node in edges:
        self.G[adj_node][name] = edges[adj_node]

  def add_edge(self, x, y, length):
    '''Add an edge between nodes x and y with given length.  If an edge
    already connects x and y, this function changes the length.

    Parameters:
      x: node

      y: node

      length: int, float, or long
    '''

    # First check that the nodes are in the graph.
    if x not in self.G:
      raise ValueError('graph.add_node(): ' + str(x) + ' not in graph!')
    if y not in self.G:
      raise ValueError('graph.add_node(): ' + str(y) + ' not in graph!')
    # Check that the length is a number
    if type(length) not in [int, float, long]:
      raise ValueError('graph.add_node(): length must be a number!')

    self.G[x][y] = length
    self.G[y][x] = length

  def neighbors(self, x):
    '''Returns all nodes with an edge connecting them to x.

    Parameters:
      x: node
        A node in the graph.

    Returns:
      list
        A list of all nodes connected to the given node.
    '''
    if x not in self.G:
      raise ValueError('graph.neighbors():' + str(x) + ' not in graph!')

    return self.G[x].keys()

  def delete_node(self, x):
    '''Delete a node from the graph.

    Parameters:
      x: node
        The node to be deleted
    '''

    if x not in self.G:
      raise ValueError('delete_node(): node not in graph!')

    # Delete the edges connecting the node
    for node in self.neighbors(x):
      del self.G[node][x]

    # Delete the node itself
    del self.G[x]

  def get_edge(self, x, y):
    '''Returns the value of the edge connecting x and y.

    Parameters:
      x: node
        A node in the graph

      y: node
        Another node in the graph

    Returns:
      number
        The length of the edge connecting x and y
    '''
    # First check that there exists an edge connecting x and y.
    if y not in self.G[x]:
      raise ValueError('graph.get_edge(): no edge connecting the nodes!')

    return self.G[x][y]

  def count_nodes(self):
    '''Return the number of nodes in the graph.'''
    return len(self.G)

  def nodes(self):
    '''Return the nodes in the graph.'''
    return self.G.keys()

def shortest_path(G, A, B):
  '''Caculate the shortest path from A to B in a graph G by brute force.

  Parameters:
    G: graph
      The graph on which to find the shortest route

    A: node
      Starting node

    B: node
      Ending node

  Returns:
    shortest_path_length: number
      The length of the shortest path

    shortest_path_nodes: tuple
      A tuple consisting of the nodes along the shortest path.
  '''

  shortest_path_length = numpy.inf
  shortest_path_nodes = []
  for adj_node in G[A]:
    path_length = G[A][adj_node]

    H = G.copy()
    H.delete_node(A)
    sub_path_length, sub_path_nodes = shortest_path(H, adj_node, B)
    path_length += sub_path_length
    path_nodes = sub_path_nodes.insert(0, A)

    if path_length < shortest_path:
      shortest_path_length = path_length
      shortest_path_nodes = path_nodes

  return (shortest_path_length, shortest_path_nodes)

def salesman_brute(G):
  '''Calculate the shortest tour that visits every node of the graph, G, and
  returns to the starting node.

  Parameters:
    G: graph
      The graph on which to find the shortest tour

  Returns:
    shortest_tour_length: number
      The length of the shortest tour

    shortest_tour_nodes: tuple
      A tuple consisting of the nodes along the shortest tour
  '''

  # Randomly pick a node.
  start_node = random.choice(G.nodes())

  min_length = numpy.inf

#  for path in permutations(G.nodes())

if __name__ == '__main__':
  # Set up a default graph

  G = graph()
  G.add_node('A')
  G.add_node('B')
  G.add_node('C')
  G.add_node('D')
  G.add_node('E')
  G.add_node('F')

  G.add_edge('A', 'B', 10)
  G.add_edge('A', 'C', 20)
  G.add_edge('A', 'E', 50)
  G.add_edge('B', 'D', 24)
  G.add_edge('B', 'C', 15)
  G.add_edge('B', 'E', 30)
  G.add_edge('C', 'E', 6)
  G.add_edge('C', 'F', 12)
  G.add_edge('D', 'E', 15)
  G.add_edge('D', 'F', 40)
  G.add_edge('E', 'F', 18)

  PATH = shortest_path(G, 'A', 'D')
  print PATH[0]
  print PATH[1]
<commit_msg>Changed variables in functions to lower case<commit_after>#! /usr/bin/env python

import numpy
import random
from itertools import permutations

class graph:
  '''A graph data structure.

  The data structure consists of a dictionary for which each element is a
  node.  Each node stores a dictionary of all other nodes to which the node
  is connected along with the length of the edge.
  '''

  def __init__(self, name=None):
    '''Initialize the graph.

    Parameters:
      name: any type
        The name of the node.  This should usually be a short string or an
        integer.
    '''
    if name is None:
      self.g = {}
    elif type(name) is dict:
      for elem in name:
        if type(name[elem]) is not dict:
          raise ValueError('graph.__init__(): cast to graph failed!')
      self.g = {}
      for elem in name:
        self.g[elem] = name[elem]
    else:
      self.g = {name : {}}

  def __getitem__(self, i):
    '''Return the edges connected to a specific node.'''
    if i not in self.g:
      raise ValueError('node not in graph!')
    return self.g[i]

  def copy(self):
    '''Return a deep copy of the graph.'''
    h = {}
    for elem in self.g:
      h[elem] = self.g[elem]
    return graph(h)

  def add_node(self, name, edges=None):
    '''Add a node to the graph.

    Parameters:
      name: any type
        The name of the node.  This should usually be a short string or an
        integer.

      edges: dict, optional
        The nodes this new node connects to.  The key for each element of
        this dictionary is the name of an adjacent node and the associated
        value is the length of the corresponding edge.
        '''

    #
    # First perform some checks on the received data types.
    #

    # Make sure that the node is not already in the graph
    if name in self.g:
      raise ValueError('graph.add_node(): node already in graph!')

    if edges is None:
      self.g[name] = {}

    else:
      # Make sure that the edges are a dictionary
      if type(edges) is not dict:
        raise TypeError('graph.add_node(): edges must be a dictionary!')
      for elem in edges:
        # Make sure the length is some kind of number
        if not isinstance(edges[elem], (int, long, float)):
          raise TypeError('graph.add_node(): ' + str(elem) +
          ': edge length is not a number!')
        # Check that the edges are to nodes already in the graph
        if elem not in self.g:
          raise ValueError('graph.add_node(): ' + str(elem) +
          ': edge connects to nonexistant node!')

      # First add the node
      self.g[name] = edges

      # Now update all the adjacent nodes
      for adj_node in edges:
        self.g[adj_node][name] = edges[adj_node]

  def add_edge(self, x, y, length):
    '''Add an edge between nodes x and y with given length.  If an edge
    already connects x and y, this function changes the length.

    Parameters:
      x: node

      y: node

      length: int, float, or long
    '''

    # First check that the nodes are in the graph.
    if x not in self.g:
      raise ValueError('graph.add_node(): ' + str(x) + ' not in graph!')
    if y not in self.g:
      raise ValueError('graph.add_node(): ' + str(y) + ' not in graph!')
    # Check that the length is a number
    if type(length) not in [int, float, long]:
      raise ValueError('graph.add_node(): length must be a number!')

    self.g[x][y] = length
    self.g[y][x] = length

  def neighbors(self, x):
    '''Returns all nodes with an edge connecting them to x.

    Parameters:
      x: node
        A node in the graph.

    Returns:
      list
        A list of all nodes connected to the given node.
    '''
    if x not in self.g:
      raise ValueError('graph.neighbors():' + str(x) + ' not in graph!')

    return self.g[x].keys()

  def delete_node(self, x):
    '''Delete a node from the graph.

    Parameters:
      x: node
        The node to be deleted
    '''

    if x not in self.g:
      raise ValueError('delete_node(): node not in graph!')

    # Delete the edges connecting the node
    for node in self.neighbors(x):
      del self.g[node][x]

    # Delete the node itself
    del self.g[x]

  def get_edge(self, x, y):
    '''Returns the value of the edge connecting x and y.

    Parameters:
      x: node
        A node in the graph

      y: node
        Another node in the graph

    Returns:
      number
        The length of the edge connecting x and y
    '''
    # First check that there exists an edge connecting x and y.
    if y not in self.g[x]:
      raise ValueError('graph.get_edge(): no edge connecting the nodes!')

    return self.g[x][y]

  def count_nodes(self):
    '''Return the number of nodes in the graph.'''
    return len(self.g)

  def nodes(self):
    '''Return the nodes in the graph.'''
    return self.g.keys()

def shortest_path(g, a, b):
  '''Caculate the shortest path from a to b in a graph g by brute force.

  Parameters:
    g: graph
      The graph on which to find the shortest route

    a: node
      Starting node

    b: node
      Ending node

  Returns:
    shortest_path_length: number
      The length of the shortest path

    shortest_path_nodes: tuple
      A tuple consisting of the nodes along the shortest path.
  '''

  shortest_path_length = numpy.inf
  shortest_path_nodes = []
  for adj_node in g[a]:
    path_length = g[a][adj_node]

    h = g.copy()
    h.delete_node(a)
    sub_path_length, sub_path_nodes = shortest_path(h, adj_node, b)
    path_length += sub_path_length
    path_nodes = sub_path_nodes.insert(0, a)

    if path_length < shortest_path:
      shortest_path_length = path_length
      shortest_path_nodes = path_nodes

  return (shortest_path_length, shortest_path_nodes)

def salesman_brute(g):
  '''Calculate the shortest tour that visits every node of the graph, G, and
  returns to the starting node.

  Parameters:
    g: graph
      The graph on which to find the shortest tour

  Returns:
    shortest_tour_length: number
      The length of the shortest tour

    shortest_tour_nodes: tuple
      A tuple consisting of the nodes along the shortest tour
  '''

  # Randomly pick a node.
  start_node = random.choice(g.nodes())

  min_length = numpy.inf

#  for path in permutations(G.nodes())

if __name__ == '__main__':
  # Set up a default graph

  G = graph()
  G.add_node('A')
  G.add_node('B')
  G.add_node('C')
  G.add_node('D')
  G.add_node('E')
  G.add_node('F')

  G.add_edge('A', 'B', 10)
  G.add_edge('A', 'C', 20)
  G.add_edge('A', 'E', 50)
  G.add_edge('B', 'D', 24)
  G.add_edge('B', 'C', 15)
  G.add_edge('B', 'E', 30)
  G.add_edge('C', 'E', 6)
  G.add_edge('C', 'F', 12)
  G.add_edge('D', 'E', 15)
  G.add_edge('D', 'F', 40)
  G.add_edge('E', 'F', 18)

  PATH = shortest_path(G, 'A', 'D')
  print PATH[0]
  print PATH[1]
<|endoftext|>


<commit_before>from setuptools import setup, find_packages
import os

version = '0.1'
shortdesc = "UML metamodel implementation based on nodes"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'LICENSE.rst')).read()

setup(name='node',
      version=version,
      description=shortdesc,
      long_description=longdesc,
      classifiers=[
            'Development Status :: 3 - Alpha',
            'License :: OSI Approved :: GNU General Public License (GPL)',
            'Operating System :: OS Independent',
            'Programming Language :: Python',
      ], # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      keywords='',
      author='BlueDynamics Alliance',
      author_email='dev@bluedynamics.com',
      url='http://github.com/bluedynamics/node.ext.uml',
      license='BSD',
      packages=find_packages('src'),
      package_dir = {'': 'src'},
      namespace_packages=['node', 'node.ext.uml'],
      include_package_data=True,
      zip_safe=True,
      install_requires=[
          'setuptools',
          'zodict',
          'zope.interface',
      ],
      extras_require={
          'test': [
              'interlude',
          ]
      },
      entry_points="""
      [console_scripts]
      """,
      )
<commit_msg>namespace bugfixes<commit_after>from setuptools import setup, find_packages
import os

version = '0.1'
shortdesc = "UML metamodel implementation based on nodes"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'LICENSE.rst')).read()

setup(name='node.ext.uml',
      version=version,
      description=shortdesc,
      long_description=longdesc,
      classifiers=[
            'Development Status :: 3 - Alpha',
            'License :: OSI Approved :: GNU General Public License (GPL)',
            'Operating System :: OS Independent',
            'Programming Language :: Python',
      ], # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      keywords='',
      author='BlueDynamics Alliance',
      author_email='dev@bluedynamics.com',
      url='http://github.com/bluedynamics/node.ext.uml',
      license='BSD',
      packages=find_packages('src'),
      package_dir = {'': 'src'},
      namespace_packages=['node', 'node.ext'],
      include_package_data=True,
      zip_safe=True,
      install_requires=[
          'setuptools',
          'zodict',
          'zope.interface',
      ],
      extras_require={
          'test': [
              'interlude',
              'zope.configuration',
          ]
      },
      entry_points="""
      [console_scripts]
      """,
      )
<|endoftext|>


<commit_before>import asyncio
import base64
import builtins
import inspect
import os
import random
import time
from io import BytesIO, StringIO
from traceback import format_exception

import discord
import psutil
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
from PIL import Image

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

    @commands.command()
    async def ping(self, ctx):
        """Displays latency"""
        before = time.monotonic()
        msg = await ctx.send("Pinging... \N{TABLE TENNIS PADDLE AND BALL}")
        after = time.monotonic()
        ping = round((after - before) * 1000, 2)
        await msg.edit(content=f"\N{TABLE TENNIS PADDLE AND BALL} Pong! **{ping}**ms")

    @commands.command(hidden=True, disabled=True)
    async def setavatar(self, ctx):
        pics = os.listdir("Bot Pics")
        fmt = "Enter pic number to set:\n"
        for i, pic in enumerate(pics):
            fmt += f"[{i+1}] - {pic}\n"
        img_msg = await ctx.send(fmt)
        check = lambda m: m.author == ctx.author and m.channel == ctx.channel # noqa
        try:
            msg = await self.bot.wait_for("message", check=check, timeout=35)
        except asyncio.TimeoutError:
            await img_msg.delete()
            return await ctx.send("Timeout. Please try again later.")
        img_num = int(msg.content) - 1
        if img_num > len(pics):
            await img_msg.delete()
            return await ctx.send("This image doesnt exist!")
        img_name = pics[img_num]

        with open(img_name, "rb") as f:
            await ctx.bot.user.edit(avatar=f.read())
        await ctx.send("Changed image to " + img_name)

    @commands.command(hidden=True)
    @commands.is_owner()
    async def eval(self, ctx, *, code):

        out = StringIO()

        def print(*args, **kwargs):
            f = kwargs.pop('file', False) or out
            builtins.print(*args, **kwargs, file=f)

        env = {
            "ctx": ctx,
            "message": ctx.message,
            "channel": ctx.channel,
            "guild": ctx.guild,
            "author": ctx.author,
            "bot": ctx.bot,
            "print": print,
            "history": await ctx.history().flatten()
        }
        env.update(globals())

        code = code.strip("`")
        code = code.replace("py\n", "")
        fmt = "async def e():\n"
        fmt += "\n".join(["    " + ln for ln in code.split("\n")])

        try:
            result = eval(code, env)
            stdout = out.getvalue()
            if inspect.isawaitable(result):
                result = await result
            return await ctx.send(f"```py\n{stdout}\n{result}```")
        except:  # noqa
            try:
                exec(fmt, env)
                result = await env["e"]()
            except Exception as e:
                result = ''.join(format_exception(None, e, e.__traceback__, chain=False))
        stdout = out.getvalue()
        if stdout is not "" or result is not None:
            await ctx.send(f"```py\n{stdout}\n{result}```")

    @commands.command(aliased=["join", "inv"])
    async def invite(self, ctx):
        """Sends an invite link for the bot"""
        await ctx.send("https://discordapp.com/oauth2/authorize/?permissions=64&scope=bot&client_id=236176083861372928")

    class ByteString(commands.Converter):
        async def convert(self, ctx, arg):
            return bytes(arg, 'utf-8')

    @commands.command()
    async def img64(self, ctx, *, b64: ByteString):
        """Converts base64 to an image"""
        f = BytesIO(base64.decodebytes(b64))
        await ctx.send(file=discord.File(f, "img.png"))

    def square_color(self, hexa):
        with Image.new("RGBA", (200, 200), f"#{hexa}") as img:
            img.save('color.png')

    @commands.command()
    async def color(self, ctx, hexa):
        """Post a pic of a given hex value."""
        async with ctx.typing():
            self.bot.loop.run_in_executor(None, self.square_color, hexa)
            await asyncio.sleep(1)
        embed = discord.Embed(title=f"Color for hex `#{hexa.upper()}`:") \
            .set_image(url="attachment://color.png")
        await ctx.send(file=discord.File('color.png'), embed=embed)

    @commands.command()
    async def about(self, ctx):
        """Shows bot information"""
        owner = self.bot.get_user(self.bot.owner_id)
        total = len(list(self.bot.get_all_members()))
        unique = len(self.bot.users)
        online = len({m.id for m in self.bot.get_all_members() if m.status is discord.Status.online})
        process = psutil.Process()
        memory = process.memory_full_info().uss / 1024**2
        cpu = process.cpu_percent() / psutil.cpu_count()
        embed = (discord.Embed(title=f"Bot Statistics", color=discord.Color.blurple())
                 .add_field(name="Members",
                            value=f"{total} total\n{unique} unique\n{online} online")
                 .add_field(name="Servers", value=len(self.bot.guilds))
                 .add_field(name="Hardware", value=f"CPU - {cpu:.2f}%\nRAM - {memory:.2f}MB")
                 .set_author(name=str(owner), icon_url=owner.avatar_url))
        await ctx.send(embed=embed)

    @commands.command(aliases=['c', 'pick'])
    async def choose(self, ctx, *, options):
        """Chooses out of options.
        Syntax: s!choose option 1 | option 2 | option 3
        """
        options = options.split("|") if "|" in options else options.split()
        await ctx.send(random.choice(options))

    def generate_message(self, messages):
        words = messages.split(' ')
        index = 1
        chain = {}
        for word in words[index:]:
            key = words[index - 1]
            if key in chain:
                chain[key].append(word)
            else:
                chain[key] = [word]
            index += 1

        word1 = random.choice(list(chain.keys()))
        message = word1.capitalize()
        count = 45
        while len(message.split(' ')) < count:
            word2 = random.choice(chain[word1])
            word1 = word2
            message += ' ' + word2

        if not message.endswith('.'):
            message += "."

        return message

    @commands.command(aliases=["makechain", "channelchain", "makemessage"])
    @cooldown(1, 120, BucketType.channel)
    async def scramble(self, ctx, channel: discord.TextChannel = None):
        """Generates a message based on the last 1000 messages in a specified channel
        (or the current one if none was given).
        """
        channel = channel or ctx.channel
        if channel.is_nsfw() and not ctx.channel.is_nsfw():
            return await ctx.send("Cannot post nsfw content in non-nsfw channels.")
        async with ctx.typing():
            msgs = [m.clean_content async for m in channel.history(limit=1000)]
            msg = await self.bot.loop.run_in_executor(None, self.generate_message, " ".join(msgs))
        if len(msg) >= 2000:
            await ctx.send("Result was too large! Posting a part of it.")
            msg = msg[:2000]
        await ctx.send(msg)

    @scramble.error
    async def handle_cooldown(self, ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send("Command is on cooldown!")

def setup(bot):
    bot.add_cog(Utilities(bot))
<commit_msg>remove cooldown for scramble<commit_after>import asyncio
import base64
import builtins
import inspect
import os
import random
import time
from io import BytesIO, StringIO
from traceback import format_exception

import discord
import psutil
from discord.ext import commands
from discord.ext.commands import cooldown, BucketType
from PIL import Image

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

    @commands.command()
    async def ping(self, ctx):
        """Displays latency"""
        before = time.monotonic()
        msg = await ctx.send("Pinging... \N{TABLE TENNIS PADDLE AND BALL}")
        after = time.monotonic()
        ping = round((after - before) * 1000, 2)
        await msg.edit(content=f"\N{TABLE TENNIS PADDLE AND BALL} Pong! **{ping}**ms")

    @commands.command(hidden=True, disabled=True)
    async def setavatar(self, ctx):
        pics = os.listdir("Bot Pics")
        fmt = "Enter pic number to set:\n"
        for i, pic in enumerate(pics):
            fmt += f"[{i+1}] - {pic}\n"
        img_msg = await ctx.send(fmt)
        check = lambda m: m.author == ctx.author and m.channel == ctx.channel # noqa
        try:
            msg = await self.bot.wait_for("message", check=check, timeout=35)
        except asyncio.TimeoutError:
            await img_msg.delete()
            return await ctx.send("Timeout. Please try again later.")
        img_num = int(msg.content) - 1
        if img_num > len(pics):
            await img_msg.delete()
            return await ctx.send("This image doesnt exist!")
        img_name = pics[img_num]

        with open(img_name, "rb") as f:
            await ctx.bot.user.edit(avatar=f.read())
        await ctx.send("Changed image to " + img_name)

    @commands.command(hidden=True)
    @commands.is_owner()
    async def eval(self, ctx, *, code):

        out = StringIO()

        def print(*args, **kwargs):
            f = kwargs.pop('file', False) or out
            builtins.print(*args, **kwargs, file=f)

        env = {
            "ctx": ctx,
            "message": ctx.message,
            "channel": ctx.channel,
            "guild": ctx.guild,
            "author": ctx.author,
            "bot": ctx.bot,
            "print": print,
            "history": await ctx.history().flatten()
        }
        env.update(globals())

        code = code.strip("`")
        code = code.replace("py\n", "")
        fmt = "async def e():\n"
        fmt += "\n".join(["    " + ln for ln in code.split("\n")])

        try:
            result = eval(code, env)
            stdout = out.getvalue()
            if inspect.isawaitable(result):
                result = await result
            return await ctx.send(f"```py\n{stdout}\n{result}```")
        except:  # noqa
            try:
                exec(fmt, env)
                result = await env["e"]()
            except Exception as e:
                result = ''.join(format_exception(None, e, e.__traceback__, chain=False))
        stdout = out.getvalue()
        if stdout is not "" or result is not None:
            await ctx.send(f"```py\n{stdout}\n{result}```")

    @commands.command(aliased=["join", "inv"])
    async def invite(self, ctx):
        """Sends an invite link for the bot"""
        await ctx.send("https://discordapp.com/oauth2/authorize/?permissions=64&scope=bot&client_id=236176083861372928")

    class ByteString(commands.Converter):
        async def convert(self, ctx, arg):
            return bytes(arg, 'utf-8')

    @commands.command()
    async def img64(self, ctx, *, b64: ByteString):
        """Converts base64 to an image"""
        f = BytesIO(base64.decodebytes(b64))
        await ctx.send(file=discord.File(f, "img.png"))

    def square_color(self, hexa):
        with Image.new("RGBA", (200, 200), f"#{hexa}") as img:
            img.save('color.png')

    @commands.command()
    async def color(self, ctx, hexa):
        """Post a pic of a given hex value."""
        async with ctx.typing():
            self.bot.loop.run_in_executor(None, self.square_color, hexa)
            await asyncio.sleep(1)
        embed = discord.Embed(title=f"Color for hex `#{hexa.upper()}`:") \
            .set_image(url="attachment://color.png")
        await ctx.send(file=discord.File('color.png'), embed=embed)

    @commands.command()
    async def about(self, ctx):
        """Shows bot information"""
        owner = self.bot.get_user(self.bot.owner_id)
        total = len(list(self.bot.get_all_members()))
        unique = len(self.bot.users)
        online = len({m.id for m in self.bot.get_all_members() if m.status is discord.Status.online})
        process = psutil.Process()
        memory = process.memory_full_info().uss / 1024**2
        cpu = process.cpu_percent() / psutil.cpu_count()
        embed = (discord.Embed(title=f"Bot Statistics", color=discord.Color.blurple())
                 .add_field(name="Members",
                            value=f"{total} total\n{unique} unique\n{online} online")
                 .add_field(name="Servers", value=len(self.bot.guilds))
                 .add_field(name="Hardware", value=f"CPU - {cpu:.2f}%\nRAM - {memory:.2f}MB")
                 .set_author(name=str(owner), icon_url=owner.avatar_url))
        await ctx.send(embed=embed)

    @commands.command(aliases=['c', 'pick'])
    async def choose(self, ctx, *, options):
        """Chooses out of options.
        Syntax: s!choose option 1 | option 2 | option 3
        """
        options = options.split("|") if "|" in options else options.split()
        await ctx.send(random.choice(options))

    def generate_message(self, messages):
        words = messages.split(' ')
        index = 1
        chain = {}
        for word in words[index:]:
            key = words[index - 1]
            if key in chain:
                chain[key].append(word)
            else:
                chain[key] = [word]
            index += 1

        word1 = random.choice(list(chain.keys()))
        message = word1.capitalize()
        count = 45
        while len(message.split(' ')) < count:
            word2 = random.choice(chain[word1])
            word1 = word2
            message += ' ' + word2

        if not message.endswith('.'):
            message += "."

        return message

    @commands.command(aliases=["makechain", "channelchain", "makemessage"])
    async def scramble(self, ctx, channel: discord.TextChannel = None):
        """Generates a message based on the last 1000 messages in a specified channel
        (or the current one if none was given).
        """
        channel = channel or ctx.channel
        if channel.is_nsfw() and not ctx.channel.is_nsfw():
            return await ctx.send("Cannot post nsfw content in non-nsfw channels.")
        async with ctx.typing():
            msgs = [m.clean_content async for m in channel.history(limit=1000)]
            msg = await self.bot.loop.run_in_executor(None, self.generate_message, " ".join(msgs))
        if len(msg) >= 2000:
            await ctx.send("Result was too large! Posting a part of it.")
            msg = msg[:2000]
        await ctx.send(msg)

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


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

from setuptools import setup, find_packages

about = {}
with open("skylines/__about__.py") as fp:
    exec(fp.read(), about)

setup(
    name=about['__title__'],
    version=about['__version__'],
    description=about['__summary__'],
    author=about['__author__'],
    author_email=about['__email__'],
    url=about['__uri__'],
    packages=find_packages(),
    install_requires=[
        'flask==0.10.1',
        'werkzeug==0.9.4',
        'Flask-Babel==0.9',
        'Flask-Assets==0.8',
        'Flask-Login==0.2.9',
        'Flask-Cache==0.12',
        'Flask-Migrate==1.1.0',
        'Flask-Script==0.6.7',
        'Flask-SQLAlchemy==1.0',
        'Flask-WTF==0.9.3',
        'SQLAlchemy==0.9.3',
        'alembic==0.6.3',
        'psycopg2==2.5.2',
        'GeoAlchemy2==0.2.3',
        'Shapely==1.3.0',
        'crc16==0.1.1',
        'Markdown==2.4',
        'pytz',
        'webassets==0.8',
        'cssmin==0.1.4',
        'twisted==13.1',
        'closure==20140110',
        'WebHelpers==1.3',
        'celery_with_redis==3.0',
        'xcsoar==0.2',
        'Pygments==1.6',
        'aerofiles==0.1.1',
    ],
    include_package_data=True,
    package_data={
        'skylines': [
            'i18n/*/LC_MESSAGES/*.mo',
            'templates/*/*',
            'assets/static/*/*'
        ]
    },
    zip_safe=False
)
<commit_msg>setup.py: Updated Twisted dependency to v13.2.0<commit_after>#!/usr/bin/env python

from setuptools import setup, find_packages

about = {}
with open("skylines/__about__.py") as fp:
    exec(fp.read(), about)

setup(
    name=about['__title__'],
    version=about['__version__'],
    description=about['__summary__'],
    author=about['__author__'],
    author_email=about['__email__'],
    url=about['__uri__'],
    packages=find_packages(),
    install_requires=[
        'flask==0.10.1',
        'werkzeug==0.9.4',
        'Flask-Babel==0.9',
        'Flask-Assets==0.8',
        'Flask-Login==0.2.9',
        'Flask-Cache==0.12',
        'Flask-Migrate==1.1.0',
        'Flask-Script==0.6.7',
        'Flask-SQLAlchemy==1.0',
        'Flask-WTF==0.9.3',
        'SQLAlchemy==0.9.3',
        'alembic==0.6.3',
        'psycopg2==2.5.2',
        'GeoAlchemy2==0.2.3',
        'Shapely==1.3.0',
        'crc16==0.1.1',
        'Markdown==2.4',
        'pytz',
        'webassets==0.8',
        'cssmin==0.1.4',
        'Twisted==13.2.0',
        'closure==20140110',
        'WebHelpers==1.3',
        'celery_with_redis==3.0',
        'xcsoar==0.2',
        'Pygments==1.6',
        'aerofiles==0.1.1',
    ],
    include_package_data=True,
    package_data={
        'skylines': [
            'i18n/*/LC_MESSAGES/*.mo',
            'templates/*/*',
            'assets/static/*/*'
        ]
    },
    zip_safe=False
)
<|endoftext|>