<commit_before>__author__ = 'georgeoblapenko'

from rest_framework import serializers<commit_msg>some basic serializers done<commit_after>__author__ = 'georgeoblapenko'

from rest_framework import serializers
from abandoned.models import Author, Reason, Tag, Project

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'name', 'link',)

class ReasonSerializer(serializers.ModelSerializer):
    class Meta:
        model = Reason
        fields = ('id', 'reason',)

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('id', 'tag',)

class ProjectSerializer(serializers.ModelSerializer):
    author = serializers.RelatedField()
    reason = serializers.RelatedField()
    tags = serializers.RelatedField(many=True)

    class Meta:
        model = Project
        fields = ('id', 'name', 'link', 'author', 'description', 'reason', 'tags', 'upvotes', 'downvotes', 'date_added')<|endoftext|>


<commit_before>"""
The MIT License (MIT)

Copyright (c) 2018 tilda

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
# noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.utils.plainreq import get_req
from cogs.utils.endpoints import nekos

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 neko"""
        async with get_req(ctx.bot.session, nekos['sfw']) 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='source: nekos.life')
                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 get_req(ctx.bot.session, nekos['nsfw']) 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='source: nekos.life')
                    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]: fix 2<commit_after>"""
The MIT License (MIT)

Copyright (c) 2018 tilda

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
# noinspection PyPackageRequirements
import discord
import json
# noinspection PyPackageRequirements
from discord.ext import commands
# noinspection PyPackageRequirements
import utils.errors
from cogs.utils.plainreq import get_req
from cogs.utils.endpoints import nekos

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 neko"""
        async with get_req(ctx.bot.session, nekos['sfw']) 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='source: nekos.life')
                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 get_req(ctx.bot.session, nekos['nsfw']) 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'])
                        lneko_em.set_footer(text='source: nekos.life')
                        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>#!/usr/bin/python
# -*- coding:utf-8 -*-
# Powered By KK Studio

import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.netutil
import tornado.process
import tornado.locale
import platform
import db
from tornado.log import gen_log
from handler.page import Page404Handler
from config.settings import *
from handler import route
#from ui_modules import UIModules # Don't support Jinja2
from Template import TemplateLoader # For Jinja2

class App(tornado.web.Application):

    def __init__(self,handlers,conf,log):
        self.__version__ = conf['version']
        self.log = log
        settings = conf['app_settings']
        settings['default_handler_class'] = Page404Handler  # 404
        # Don't Support for Jinja2
        #settings['ui_modules'] = UIModules
        #tornado.web.Application.__init__(self, handlers, **settings)
        # Support for Jinja2
        tpl_loader = TemplateLoader(settings['template_path'], False)
        tornado.web.Application.__init__(self, handlers, template_loader=tpl_loader.Loader(), **settings)
        #每10秒执行一次
        #tornado.ioloop.PeriodicCallback(self.test, 1 * 10 * 1000).start()
        # Init Database
        self.db = db.DB(**conf['db'])
        #Init Redis
        R = db.Redis(**conf['redis'])
        self.redis = R.Connect()
        # Load Locale
        self.__load_locale(settings['default_lang'])

    #def test(self):
    #    self.log.info('Test')

    # Load Locale
    def __load_locale(self,default_lang):
        tornado.locale.load_translations('locale')
        tornado.locale.set_default_locale(default_lang)

class DNStack():

    def __init__(self,processes=4):
        self.__version__ = '1.0.0'
        self.host = config['host']
        self.port = config['port']
        self.urls = route
        self.config = config
        self.config['version'] = self.__version__
        self.log = gen_log
        if platform.system() == "Linux":  #根据操作系统类型来确定是否启用多线程
            self.processes = processes # 当processes>1时，PeriodicCallback定时任务会响相应的执行多次
        else:
            self.processes = 1
        self.log.info('DNStack %s' % self.__version__)  # 启动时打印版本号
        self.log.info('Listen Port: %s' % self.port)

    # 单进程模式
    def run(self):
        app = App(self.urls, self.config, self.log)
        app.listen(self.port)
        tornado.ioloop.IOLoop.current().start()

    # 多线程模式
    def run_multi(self):
        http_sockets = tornado.netutil.bind_sockets(self.port, self.host)
        tornado.process.fork_processes(num_processes=self.processes)
        http_server = tornado.httpserver.HTTPServer(request_callback=App(self.urls,self.config,self.log), xheaders=True)
        http_server.add_sockets(http_sockets)
        tornado.ioloop.IOLoop.instance().start()
<commit_msg>Improve DB Init<commit_after>#!/usr/bin/python
# -*- coding:utf-8 -*-
# Powered By KK Studio

import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.netutil
import tornado.process
import tornado.locale
import platform
import db
from tornado.log import gen_log
from handler.page import Page404Handler
from config.settings import *
from handler import route
#from ui_modules import UIModules # Don't support Jinja2
from Template import TemplateLoader # For Jinja2

class App(tornado.web.Application):

    def __init__(self,handlers,conf,log):
        self.__version__ = conf['version']
        self.log = log
        settings = conf['app_settings']
        settings['default_handler_class'] = Page404Handler  # 404
        # Don't Support for Jinja2
        #settings['ui_modules'] = UIModules
        #tornado.web.Application.__init__(self, handlers, **settings)
        # Support for Jinja2
        tpl_loader = TemplateLoader(settings['template_path'], False)
        tornado.web.Application.__init__(self, handlers, template_loader=tpl_loader.Loader(), **settings)
        #每10秒执行一次
        #tornado.ioloop.PeriodicCallback(self.test, 1 * 10 * 1000).start()
        # Init Database
        _db = db.DB(**conf['db'])
        self.db = _db.session
        #Init Redis
        R = db.Redis(**conf['redis'])
        self.redis = R.Connect()
        # Load Locale
        self.__load_locale(settings['default_lang'])

    #def test(self):
    #    self.log.info('Test')

    # Load Locale
    def __load_locale(self,default_lang):
        tornado.locale.load_translations('locale')
        tornado.locale.set_default_locale(default_lang)

class DNStack():

    def __init__(self,processes=4):
        self.__version__ = '1.0.0'
        self.host = config['host']
        self.port = config['port']
        self.urls = route
        self.config = config
        self.config['version'] = self.__version__
        self.log = gen_log
        if platform.system() == "Linux":  #根据操作系统类型来确定是否启用多线程
            self.processes = processes # 当processes>1时，PeriodicCallback定时任务会响相应的执行多次
        else:
            self.processes = 1
        self.log.info('DNStack %s' % self.__version__)  # 启动时打印版本号
        self.log.info('Listen Port: %s' % self.port)

    # 单进程模式
    def run(self):
        app = App(self.urls, self.config, self.log)
        app.listen(self.port)
        tornado.ioloop.IOLoop.current().start()

    # 多线程模式
    def run_multi(self):
        http_sockets = tornado.netutil.bind_sockets(self.port, self.host)
        tornado.process.fork_processes(num_processes=self.processes)
        http_server = tornado.httpserver.HTTPServer(request_callback=App(self.urls,self.config,self.log), xheaders=True)
        http_server.add_sockets(http_sockets)
        tornado.ioloop.IOLoop.instance().start()
<|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, *exts: str):
        """Loads a cog"""
        for ext in exts:
            try:
                self.bot.load_extension('cogs.' + ext)
            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.' + ext)
            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.' + ext)
            self.bot.load_extension('cogs.' + ext)
        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]: half-done work ftw<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.' + ext)
            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.' + ext)
            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"""
        for ext in exts:
            try:
                self.bot.unload_extension('cogs.' + ext)
                self.bot.load_extension('cogs.' + ext)
            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 .utils import config, checks, formats
import discord
from discord.ext import commands
import discord.utils
import random, json, asyncio
from urllib.parse import unquote

class Radio:
    """The radio-bot related commands."""

    def __init__(self, bot):
        self.bot = bot
        if not discord.opus.is_loaded():
            discord.opus.load_opus('/usr/local/lib/libopus.so') #FreeBSD path

        self.player = None
        self.stopped = True
        self.break_loop = asyncio.Event()
        #self.break_loop.clear()
        self.q = asyncio.Queue()
        self.play_next_song = asyncio.Event()
        self.current_song = None
        self.songs_dir = 'radio/'
        self.songs = []
        self.playlists = {}
        self.update_song_list()

    @property
    def is_playing(self):
        return self.player is not None and self.player.is_playing() and not self.stopped

    def toggle_next_song(self):
        if not self.stopped:
            self.bot.loop.call_soon_threadsafe(self.play_next_song.set)

    def update_song_list(self):
        self.songs = self.bot.yadisk.list_files(self.songs_dir)
        self.update_playlists()

    def update_playlists(self):
        pl_files = self.bot.yadisk.list_files(self.songs_dir + 'playlists/')
        for pl in pl_files:
            pl_url = self.bot.yadisk.direct_link(self.songs_dir + 'playlists/' + pl)
            pl_data = self.bot.yadisk._get(pl_url).json()['songs']
            self.playlists[pl] = []
            for song in pl_data:
                if song in self.songs:
                    self.playlists[pl].append(song)

    @commands.command(pass_context=True)
    async def join(self, ctx, *, channel_name : str):
        """Зайти на указанный голосовой канал."""
        if self.bot.is_voice_connected():
            await ctx.invoke(self.leave)

        check = lambda c: c.name == channel_name and c.type == discord.ChannelType.voice
        channel = discord.utils.find(check, ctx.message.server.channels)
        if channel is None:
            await self.bot.say('Нет такого голосового канала.')
        await self.bot.join_voice_channel(channel)

    @commands.command(pass_context=True)
    async def leave(self, ctx):
        """Покинуть текущий голосовой канал."""
        await ctx.invoke(self.stop)
        await self.bot.voice.disconnect()

    @commands.command()
    async def pause(self):
        """Приостановить воспроизведение."""
        if self.player is not None:
            self.player.pause()

    @commands.command()
    async def resume(self):
        """Продолжить воспроизведение."""
        if self.player is not None and not self.is_playing:
            self.player.resume()

    @commands.command()
    async def skip(self):
        """Перейти к следующей песне в очереди."""
        if self.player is not None and self.is_playing:
            self.player.stop()
            self.toggle_next_song()

    @commands.command()
    async def stop(self):
        """Остановить воспроизведение."""
        if self.is_playing:
            self.break_loop.set()
            self.play_next_song.set()
            self.stopped = True
            self.player.stop()

    @commands.command(pass_context=True)
    async def play(self, ctx):
        """Начать воспроизведение песен из очереди."""
        if self.player is not None and not self.stopped:
            if not self.is_playing:
                await ctx.invoke(self.resume)
                return
            else:
                await self.bot.say('Уже играю песенку.')
                return

        while True:
            if not self.bot.is_voice_connected():
                author_channel = ctx.message.author.voice_channel
                if author_channel is not None:
                    print('Joining {}.'.format(author_channel.name))
                    await ctx.invoke(self.join, channel_name=author_channel.name)
                else:
                    await self.bot.say('Не выбран голосовой канал.')
                    return

            if self.q.empty():
                await self.q.put(random.choice(self.songs))
            self.play_next_song.clear()
            self.current = await self.q.get()
            self.player = self.bot.voice.create_ffmpeg_player(
                self.bot.yadisk.direct_link(self.songs_dir + self.current),
                after=self.toggle_next_song)
                #options="-loglevel debug -report",
                #headers = dict(self.bot.pycopy.session.headers)
            self.stopped = False
            self.player.start()
            song_name = unquote(self.current.split('/')[-1])
            await self.bot.change_status(discord.Game(name=song_name))

            await self.play_next_song.wait()
            if self.break_loop.is_set():
                self.break_loop.clear()
                return
        await self.bot.say('Leaving play loop')

    @commands.command(aliases=['c'])
    async def current(self):
        """Что там играет?"""
        if self.is_playing:
            song_name = unquote(self.current.split('/')[-1])
            await self.bot.say(song_name)

    @commands.command()
    async def update(self):
        """Обновить список песен."""
        self.update_song_list()
        await self.bot.say("Найдено {} песенок".format(len(self.songs)))

    @commands.command()
    async def list(self):
        """Вывести список всех доступных песен."""
        song_list = ""
        id = 1
        for song in self.songs:
            song_list += "{}. {}\n".format(id, song)
            id += 1
            if len(song_list) > 1800:
                await self.bot.say(song_list)
                song_list = ''
        await self.bot.say(song_list)

    @commands.command(aliases=['ss'])
    async def searchsong(self, search_word : str):
        """Искать песню по названию."""
        search_result = ""
        id = 1
        found = False
        for song in self.songs:
            if search_word.lower() in song.lower():
                found = True
                search_result += "{}. {}\n".format(id, song)
                if len(search_result) > 1800:
                    await self.bot.say(search_result)
                    search_result = ''
            id += 1
        if not found:
            search_result = "Нет такой песни."
        await self.bot.say(search_result)

    @commands.command()
    async def add(self, value : str):
        """Добавить в конец очереди песню или плейлист."""
        if value.strip().isdigit():
            await self.q.put(self.songs[int(value.strip())-1])
            await self.bot.say("{} добавлена в конец очереди".format(self.songs[int(value.strip())-1]))
        elif value in self.playlists:
            for song in self.playlists[value]:
                await self.q.put(song)
            await self.bot.say("Плейлист добавлен в конец очереди.")
        else:
            await self.bot.say("Нет такой песенки.")

    @commands.group(pass_context=True, aliases=['pl'])
    async def playlist(self, ctx):
        """Показать плейлисты."""
        if ctx.invoked_subcommand is None and len(self.playlists) > 0:
            to_print = ""
            id = 1
            for playlist in self.playlists:
                to_print += "{}. {}\n".format(id, playlist.strip('.json')[0])
                id += 1
                if len(to_print) > 1800:
                    await self.bot.say(to_print)
                    to_print = ''
            await self.bot.say(to_print)

    @playlist.command(pass_context=True, name='add')
    async def pl_add(self, ctx, *args):
        """Добавить песенки в плейлист.

        !playlist add {song} {song} ... {playlist}
        """
        to_add = []
        for arg in args:
            if arg.strip().isdigit():
                if int(arg) in range(1, len(self.songs) + 1):
                    song_name = self.songs[int(arg)-1]
                    to_add.append(song_name)
            elif arg in self.playlists:
                self.playlists[arg] += to_add
                pl_json = {'name': arg, 'songs': self.playlists[arg]}
                self.bot.yadisk.upload(self.songs_dir + 'playlists/' + arg + '.json', json.dumps(pl_json))
                await self.bot.say('Плейлист {} обновлён.'.format(arg))
                to_add = []

    @playlist.command(name = 'new')
    async def pl_new(self, name : str):
        """Создать новый плейлист.
        (Имя не должно содержать пробелов. Имя не может быть числом.)
        """
        name = name.strip().split(' ')[0]
        self.playlists[name] = []
        await self.bot.say('Плейлист {} создан.'.format(name))

    @playlist.command(name = 'show')
    async def pl_show(self, name : str):
        """Показать плейлист."""
        name = name.strip().split(' ')[0]
        if name in self.playlists:
            song_list = ""
            for song in self.playlists[name]:
                try:
                    id = self.songs.index(song) + 1
                except:
                    await self.bot.say('Плейлист {} повреждён.'.format(name))
                song_list += "{}. {}\n".format(id, song)
                if len(song_list) > 1800:
                    await self.bot.say(song_list)
                    song_list = ''
            await self.bot.say(song_list)
        else:
            await self.bot.say('Нет такого плейлиста.')

def setup(bot):
    bot.add_cog(Radio(bot))
<commit_msg>Update radio.py<commit_after>from .utils import config, checks, formats
import discord
from discord.ext import commands
import discord.utils
import random, json, asyncio
from urllib.parse import unquote

class Radio:
    """The radio-bot related commands."""

    def __init__(self, bot):
        self.bot = bot
        if not discord.opus.is_loaded():
            discord.opus.load_opus('/usr/local/lib/libopus.so') #FreeBSD path

        self.player = None
        self.stopped = True
        self.break_loop = asyncio.Event()
        #self.break_loop.clear()
        self.q = asyncio.Queue()
        self.play_next_song = asyncio.Event()
        self.current_song = None
        self.songs_dir = 'radio/'
        self.songs = []
        self.playlists = {}
        self.update_song_list()

    @property
    def is_playing(self):
        return self.player is not None and self.player.is_playing() and not self.stopped

    def toggle_next_song(self):
        if not self.stopped:
            self.bot.loop.call_soon_threadsafe(self.play_next_song.set)

    def update_song_list(self):
        self.songs = self.bot.yadisk.list_files(self.songs_dir)
        self.update_playlists()

    def update_playlists(self):
        pl_files = self.bot.yadisk.list_files(self.songs_dir + 'playlists/')
        for pl in pl_files:
            pl_url = self.bot.yadisk.direct_link(self.songs_dir + 'playlists/' + pl)
            pl_data = self.bot.yadisk._get(pl_url).json()['songs']
            self.playlists[pl] = []
            for song in pl_data:
                if song in self.songs:
                    self.playlists[pl].append(song)

    @commands.command(pass_context=True)
    async def join(self, ctx, *, channel_name : str):
        """Зайти на указанный голосовой канал."""
        if self.bot.is_voice_connected():
            await ctx.invoke(self.leave)

        check = lambda c: c.name == channel_name and c.type == discord.ChannelType.voice
        channel = discord.utils.find(check, ctx.message.server.channels)
        if channel is None:
            await self.bot.say('Нет такого голосового канала.')
        await self.bot.join_voice_channel(channel)

    @commands.command(pass_context=True)
    async def leave(self, ctx):
        """Покинуть текущий голосовой канал."""
        await ctx.invoke(self.stop)
        await self.bot.voice.disconnect()

    @commands.command()
    async def pause(self):
        """Приостановить воспроизведение."""
        if self.player is not None:
            self.player.pause()

    @commands.command()
    async def resume(self):
        """Продолжить воспроизведение."""
        if self.player is not None and not self.is_playing:
            self.player.resume()

    @commands.command()
    async def skip(self):
        """Перейти к следующей песне в очереди."""
        if self.player is not None and self.is_playing:
            self.player.stop()
            self.toggle_next_song()

    @commands.command()
    async def stop(self):
        """Остановить воспроизведение."""
        if self.is_playing:
            self.break_loop.set()
            self.play_next_song.set()
            self.stopped = True
            self.player.stop()

    @commands.command(pass_context=True)
    async def play(self, ctx):
        """Начать воспроизведение песен из очереди."""
        if self.player is not None and not self.stopped:
            if not self.is_playing:
                await ctx.invoke(self.resume)
                return
            else:
                await self.bot.say('Уже играю песенку.')
                return

        while True:
            if not self.bot.is_voice_connected():
                author_channel = ctx.message.author.voice_channel
                if author_channel is not None:
                    print('Joining {}.'.format(author_channel.name))
                    await ctx.invoke(self.join, channel_name=author_channel.name)
                else:
                    await self.bot.say('Не выбран голосовой канал.')
                    return

            if self.q.empty():
                await self.q.put(random.choice(self.songs))
            self.play_next_song.clear()
            self.current = await self.q.get()
            self.player = self.bot.voice.create_ffmpeg_player(
                self.bot.yadisk.direct_link(self.songs_dir + self.current),
                after=self.toggle_next_song)
                #options="-loglevel debug -report",
                #headers = dict(self.bot.pycopy.session.headers)
            self.stopped = False
            self.player.start()
            song_name = unquote(self.current.split('/')[-1])
            await self.bot.change_status(discord.Game(name=song_name))

            await self.play_next_song.wait()
            if self.break_loop.is_set():
                self.break_loop.clear()
                return
        await self.bot.say('Leaving play loop')

    @commands.command(aliases=['c'])
    async def current(self):
        """Что там играет?"""
        if self.is_playing:
            song_name = unquote(self.current.split('/')[-1])
            await self.bot.say(song_name)

    @commands.command()
    async def update(self):
        """Обновить список песен."""
        self.update_song_list()
        await self.bot.say("Найдено {} песенок".format(len(self.songs)))

    @commands.command()
    async def list(self):
        """Вывести список всех доступных песен."""
        song_list = ""
        id = 1
        for song in self.songs:
            song_list += "{}. {}\n".format(id, song)
            id += 1
            if len(song_list) > 1800:
                await self.bot.say(song_list)
                song_list = ''
        await self.bot.say(song_list)

    @commands.command(aliases=['ss'])
    async def searchsong(self, search_word : str):
        """Искать песню по названию."""
        search_result = ""
        id = 1
        found = False
        for song in self.songs:
            if search_word.lower() in song.lower():
                found = True
                search_result += "{}. {}\n".format(id, song)
                if len(search_result) > 1800:
                    await self.bot.say(search_result)
                    search_result = ''
            id += 1
        if not found:
            search_result = "Нет такой песни."
        await self.bot.say(search_result)

    @commands.command()
    async def add(self, value : str):
        """Добавить в конец очереди песню или плейлист."""
        if value.strip().isdigit():
            await self.q.put(self.songs[int(value.strip())-1])
            await self.bot.say("{} добавлена в конец очереди".format(self.songs[int(value.strip())-1]))
        elif value in self.playlists:
            for song in self.playlists[value]:
                await self.q.put(song)
            await self.bot.say("Плейлист добавлен в конец очереди.")
        else:
            await self.bot.say("Нет такой песенки.")

    @commands.group(pass_context=True, aliases=['pl'])
    async def playlist(self, ctx):
        """Показать плейлисты."""
        if ctx.invoked_subcommand is None and len(self.playlists) > 0:
            to_print = ""
            id = 1
            for playlist in self.playlists:
                to_print += "{}. {}\n".format(id, playlist.split('.json')[0])
                id += 1
                if len(to_print) > 1800:
                    await self.bot.say(to_print)
                    to_print = ''
            await self.bot.say(to_print)

    @playlist.command(pass_context=True, name='add')
    async def pl_add(self, ctx, *args):
        """Добавить песенки в плейлист.

        !playlist add {song} {song} ... {playlist}
        """
        to_add = []
        for arg in args:
            if arg.strip().isdigit():
                if int(arg) in range(1, len(self.songs) + 1):
                    song_name = self.songs[int(arg)-1]
                    to_add.append(song_name)
            elif arg in self.playlists:
                self.playlists[arg] += to_add
                pl_json = {'name': arg, 'songs': self.playlists[arg]}
                self.bot.yadisk.upload(self.songs_dir + 'playlists/' + arg + '.json', json.dumps(pl_json))
                await self.bot.say('Плейлист {} обновлён.'.format(arg))
                to_add = []

    @playlist.command(name = 'new')
    async def pl_new(self, name : str):
        """Создать новый плейлист.
        (Имя не должно содержать пробелов. Имя не может быть числом.)
        """
        name = name.strip().split(' ')[0]
        self.playlists[name] = []
        await self.bot.say('Плейлист {} создан.'.format(name))

    @playlist.command(name = 'show')
    async def pl_show(self, name : str):
        """Показать плейлист."""
        name = name.strip().split(' ')[0]
        if name in self.playlists:
            song_list = ""
            for song in self.playlists[name]:
                try:
                    id = self.songs.index(song) + 1
                except:
                    await self.bot.say('Плейлист {} повреждён.'.format(name))
                song_list += "{}. {}\n".format(id, song)
                if len(song_list) > 1800:
                    await self.bot.say(song_list)
                    song_list = ''
            await self.bot.say(song_list)
        else:
            await self.bot.say('Нет такого плейлиста.')

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


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

logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)
try:
    logging.info('stats[datadog]: initalized')
    # noinspection PyPackageRequirements
    from datadog import statsd
except ImportError:
    logging.info('stats[datadog]: datadog not installed')
    logging.info('stats[datadog]: disabling datadog')
    datadog_enabled = False
else:
    logging.info('stats[datadog]: success')
    datadog_enabled = True

async def find_channel(guild):
    """
    Finds a suitable guild channel for posting the
    welcome message. You shouldn't need to call this
    yourself. on_guild_join calls this automatically.

    Thanks FrostLuma for code!
    """
    for c in guild.text_channels:
        if not c.permissions_for(guild.me).send_messages:
            continue
        return c

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

    async def dogpost(self):
        """
        This async function does a post of server and shard count to Datadog.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if datadog_enabled:
            statsd.gauge('lolbot.servers', len(self.bot.guilds))
            statsd.gauge('lolbot.shards', len(self.bot.shards))
        else:
            pass

    async def dblpost(self):
        """
        This async function does a post of server and shard count to discordbots.org.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if self.bot.config['dbl'] != "":
            headers = {
                'Authorization': self.bot.config['dbl'],
                'Content-Type': 'application/json'
            }
            data = {
                'server_count': len(self.bot.guilds),
                'shard_count': len(self.bot.shards)
            }
            i = await self.bot.application_info()
            req = await self.bot.session.post(f'https://discordbots.org/api/bots/{i.id}/stats',
                                              data=json.dumps(data), headers=headers)
            if req.status == 200:
                logging.info('poster[dbl]: done')
            else:
                t = await req.text()
                logging.error(f'poster[dbl]: oops (code {req.status})')
                logging.error(f'poster[dbl]: response: {t}')
        else:
            pass

    async def dpwpost(self):
        """
        This async function does a post of server and shard count
        to bots.discord.pw.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if self.bot.config['dbots'] != "":
            headers = {
                'Authorization': self.bot.config['dbots'],
                'Content-Type': 'application/json'
            }
            data = {
                'server_count': len(self.bot.guilds),
                'shard_count': len(self.bot.shards)
            }
            i = await self.bot.application_info()
            req = await self.bot.session.post(f'https://bots.discord.pw/api/bots/{i.id}/stats',
                                              data=json.dumps(data), headers=headers)
            status = req.status
            if status == 200:
                logging.info('poster[dbots]: done')
            else:
                resp = await req.text()
                logging.error(f'poster[dbots]: oops (code {status})')
                logging.error(f'poster[dbots]: response: {resp}')

    async def post(self):
        """
        This async function is a wrapper for post functions.
        You shouldn't need to call this yourself, the guild events do this for you.
        """
        if self.bot.config['dbotsorg']:
            await self.dblpost()
        else:
            pass
        if self.bot.config['dbotspw']:
            await self.dpwpost()
        else:
            pass
        if datadog_enabled:
            await self.dogpost()
        else:
            pass

    async def on_guild_join(self, guild):
        """
        This async function is called whenever a guild adds a lolbot instance.
        You shouldn't need to call this yourself, discord.py does this automatically.
        """
        logging.info('Joined guild "' + str(guild.name) + '" ID: ' + str(guild.id))
        welcome_channel = await find_channel(guild)
        we = discord.Embed(title='Hello!',
                           description='Thanks for inviting me.'
                                       ' I am required to tell you that I may'
                                       ' log command usage, user/channel/server IDs, and'
                                       ' other information. Thanks for your understanding!', colour=0x690E8)
        await welcome_channel.send(embed=we)
        await self.post()

    async def on_guild_remove(self, guild):
        """
        This async function is called whenever a guild removes a lolbot instance (rip).
        You shouldn't need to call this yourself, discord.py does this automatically.
        """
        logging.info('Left ' + str(guild.name))
        await self.post()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def poststats(self, ctx):
        """Posts guild stats to bot lists"""
        ok = discord.utils.get(self.bot.emojis, name='check')
        not_ok = discord.utils.get(self.bot.emojis, name='notcheck')
        land = await ctx.send('Hold on a sec...')
        logging.info('poster: forcing post')
        dbl = await ctx.send('Posting to discordbots.org...')
        if self.bot.config['dbotsorg']:
            try:
                await self.dblpost()
            except Exception as e:
                await dbl.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await dbl.edit(content=f'<:check:{ok.id}> Success.')
        else:
            await dbl.edit(content='No key configured, skipping discordbots.org!')
        dpw = await ctx.send('Posting to bots.discord.pw...')
        if self.bot.config['dbotspw']:
            try:
                await self.dpwpost()
            except Exception as e:
                await dpw.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await dpw.edit(content=f'<:check:{ok.id}> Success.')
        else:
            await dpw.edit(content=f'No key configured, skipping bots.discord.pw!')
        ddg = await ctx.send('Posting to Datadog...')
        if datadog_enabled:
            try:
                await self.dogpost()
            except Exception as e:
                await ddg.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await ddg.edit(content=f'<:check:{ok.id}> Success.')
        else:
            await ddg.edit(content='Integration disabled, skipping Datadog!')
        await land.edit(content='Posted count.')

def setup(bot):
    bot.add_cog(Stats(bot))
<commit_msg>cogs[stats]: context, context<commit_after>import json
import logging
# noinspection PyPackageRequirements
import discord
from discord.ext import commands

logging.basicConfig(format='[%(levelname)s] - %(message)s', level=logging.INFO)
try:
    logging.info('stats[datadog]: initalized')
    # noinspection PyPackageRequirements
    from datadog import statsd
except ImportError:
    logging.info('stats[datadog]: datadog not installed')
    logging.info('stats[datadog]: disabling datadog')
    datadog_enabled = False
else:
    logging.info('stats[datadog]: success')
    datadog_enabled = True

async def find_channel(guild):
    """
    Finds a suitable guild channel for posting the
    welcome message. You shouldn't need to call this
    yourself. on_guild_join calls this automatically.

    Thanks FrostLuma for code!
    """
    for c in guild.text_channels:
        if not c.permissions_for(guild.me).send_messages:
            continue
        return c

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

    async def dogpost(self):
        """
        This async function does a post of server and shard count to Datadog.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if datadog_enabled:
            statsd.gauge('lolbot.servers', len(self.bot.guilds))
            statsd.gauge('lolbot.shards', len(self.bot.shards))
        else:
            pass

    async def dblpost(self):
        """
        This async function does a post of server and shard count to discordbots.org.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if self.bot.config['dbl'] != "":
            headers = {
                'Authorization': self.bot.config['dbl'],
                'Content-Type': 'application/json'
            }
            data = {
                'server_count': len(self.bot.guilds),
                'shard_count': len(self.bot.shards)
            }
            i = await self.bot.application_info()
            req = await self.bot.session.post(f'https://discordbots.org/api/bots/{i.id}/stats',
                                              data=json.dumps(data), headers=headers)
            if req.status == 200:
                logging.info('poster[dbl]: done')
            else:
                t = await req.text()
                logging.error(f'poster[dbl]: oops (code {req.status})')
                logging.error(f'poster[dbl]: response: {t}')
        else:
            pass

    async def dpwpost(self):
        """
        This async function does a post of server and shard count
        to bots.discord.pw.
        You should not have to call this yourself, post() is a wrapper and
        does it for you.
        """
        if self.bot.config['dbots'] != "":
            headers = {
                'Authorization': self.bot.config['dbots'],
                'Content-Type': 'application/json'
            }
            data = {
                'server_count': len(self.bot.guilds),
                'shard_count': len(self.bot.shards)
            }
            i = await self.bot.application_info()
            req = await self.bot.session.post(f'https://bots.discord.pw/api/bots/{i.id}/stats',
                                              data=json.dumps(data), headers=headers)
            status = req.status
            if status == 200:
                logging.info('poster[dbots]: done')
            else:
                resp = await req.text()
                logging.error(f'poster[dbots]: oops (code {status})')
                logging.error(f'poster[dbots]: response: {resp}')

    async def post(self):
        """
        This async function is a wrapper for post functions.
        You shouldn't need to call this yourself, the guild events do this for you.
        """
        if self.bot.config['dbotsorg']:
            await self.dblpost()
        else:
            pass
        if self.bot.config['dbotspw']:
            await self.dpwpost()
        else:
            pass
        if datadog_enabled:
            await self.dogpost()
        else:
            pass

    async def on_guild_join(self, guild):
        """
        This async function is called whenever a guild adds a lolbot instance.
        You shouldn't need to call this yourself, discord.py does this automatically.
        """
        logging.info('Joined guild "' + str(guild.name) + '" ID: ' + str(guild.id))
        welcome_channel = await find_channel(guild)
        we = discord.Embed(title='Hello!',
                           description='Thanks for inviting me.'
                                       ' I am required to tell you that I may'
                                       ' log command usage, user/channel/server IDs, and'
                                       ' other information. Thanks for your understanding!', colour=0x690E8)
        await welcome_channel.send(embed=we)
        await self.post()

    async def on_guild_remove(self, guild):
        """
        This async function is called whenever a guild removes a lolbot instance (rip).
        You shouldn't need to call this yourself, discord.py does this automatically.
        """
        logging.info('Left ' + str(guild.name))
        await self.post()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def poststats(self, ctx):
        """Posts guild stats to bot lists"""
        ok = discord.utils.get(self.bot.emojis, name='check')
        not_ok = discord.utils.get(self.bot.emojis, name='notcheck')
        land = await ctx.send('Hold on a sec...')
        logging.info('poster: forcing post')
        dbl = await ctx.send('Posting to discordbots.org...')
        if self.bot.config['dbotsorg']:
            try:
                await self.dblpost()
            except Exception as e:
                await dbl.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await dbl.edit(content=f'<:check:{ok.id}> Posted to discordbots.org.')
        else:
            await dbl.edit(content='No key configured, skipping discordbots.org!')
        dpw = await ctx.send('Posting to bots.discord.pw...')
        if self.bot.config['dbotspw']:
            try:
                await self.dpwpost()
            except Exception as e:
                await dpw.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await dpw.edit(content=f'<:check:{ok.id}> Posted to bots.discord.pw.')
        else:
            await dpw.edit(content=f'No key configured, skipping bots.discord.pw!')
        ddg = await ctx.send('Posting to Datadog...')
        if datadog_enabled:
            try:
                await self.dogpost()
            except Exception as e:
                await ddg.edit(content=f'<:notcheck:{not_ok.id}> Error: `\`\`\py\n{e}\n`\`\`')
            else:
                await ddg.edit(content=f'<:check:{ok.id}> Posted to Datadog.')
        else:
            await ddg.edit(content='Integration disabled, skipping Datadog!')
        await land.edit(content='Posted count.')

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


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

"""This is a sample Hello World API implemented using Google Cloud
Endpoints."""

# [START imports]
import endpoints
from endpoints import message_types
from endpoints import messages
from endpoints import remote
# [END imports]

# [START messages]
class EchoRequest(messages.Message):
    content = messages.StringField(1)

class EchoResponse(messages.Message):
    """A proto Message that contains a simple string field."""
    content = messages.StringField(1)

ECHO_RESOURCE = endpoints.ResourceContainer(
    EchoRequest,
    n=messages.IntegerField(2, default=1))
# [END messages]

# [START echo_api]
@endpoints.api(name='echo', version='v1')
class EchoApi(remote.Service):

    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        ECHO_RESOURCE,
        # This method returns an Echo message.
        EchoResponse,
        path='echo',
        http_method='POST',
        name='echo')
    def echo(self, request):
        output_content = ' '.join([request.content] * request.n)
        return EchoResponse(content=output_content)

    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        ECHO_RESOURCE,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/{n}',
        http_method='POST',
        name='echo_path_parameter')
    def echo_path_parameter(self, request):
        output_content = ' '.join([request.content] * request.n)
        return EchoResponse(content=output_content)

    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        message_types.VoidMessage,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/getApiKey',
        http_method='GET',
        name='echo_api_key',
        api_key_required=True)
    def echo_api_key(self, request):
        key, key_type = request.get_unrecognized_field_info('key')
        return EchoResponse(content=key)

    @endpoints.method(
        # This method takes an empty request body.
        message_types.VoidMessage,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/getUserEmail',
        http_method='GET',
        # Require auth tokens to have the following scopes to access this API.
        scopes=[endpoints.EMAIL_SCOPE],
        # OAuth2 audiences allowed in incoming tokens.
        audiences=['your-oauth-client-id.com'])
    def get_user_email(self, request):
        user = endpoints.get_current_user()
        # If there's no user defined, the request was unauthenticated, so we
        # raise 401 Unauthorized.
        if not user:
            raise endpoints.UnauthorizedException
        return EchoResponse(content=user.email())
# [END echo_api]

# [START api_server]
api = endpoints.api_server([EchoApi])
# [END api_server]
<commit_msg>Changed region tags in sample (#1612)<commit_after># Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This is a sample Hello World API implemented using Google Cloud
Endpoints."""

# [START imports]
import endpoints
from endpoints import message_types
from endpoints import messages
from endpoints import remote
# [END imports]

# [START messages]
class EchoRequest(messages.Message):
    content = messages.StringField(1)

class EchoResponse(messages.Message):
    """A proto Message that contains a simple string field."""
    content = messages.StringField(1)

ECHO_RESOURCE = endpoints.ResourceContainer(
    EchoRequest,
    n=messages.IntegerField(2, default=1))
# [END messages]

# [START echo_api_class]
@endpoints.api(name='echo', version='v1')
class EchoApi(remote.Service):

    # [START echo_api_method]
    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        ECHO_RESOURCE,
        # This method returns an Echo message.
        EchoResponse,
        path='echo',
        http_method='POST',
        name='echo')
    def echo(self, request):
        output_content = ' '.join([request.content] * request.n)
        return EchoResponse(content=output_content)
    # [END echo_api_method]

    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        ECHO_RESOURCE,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/{n}',
        http_method='POST',
        name='echo_path_parameter')
    def echo_path_parameter(self, request):
        output_content = ' '.join([request.content] * request.n)
        return EchoResponse(content=output_content)

    @endpoints.method(
        # This method takes a ResourceContainer defined above.
        message_types.VoidMessage,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/getApiKey',
        http_method='GET',
        name='echo_api_key',
        api_key_required=True)
    def echo_api_key(self, request):
        key, key_type = request.get_unrecognized_field_info('key')
        return EchoResponse(content=key)

    @endpoints.method(
        # This method takes an empty request body.
        message_types.VoidMessage,
        # This method returns an Echo message.
        EchoResponse,
        path='echo/getUserEmail',
        http_method='GET',
        # Require auth tokens to have the following scopes to access this API.
        scopes=[endpoints.EMAIL_SCOPE],
        # OAuth2 audiences allowed in incoming tokens.
        audiences=['your-oauth-client-id.com'])
    def get_user_email(self, request):
        user = endpoints.get_current_user()
        # If there's no user defined, the request was unauthenticated, so we
        # raise 401 Unauthorized.
        if not user:
            raise endpoints.UnauthorizedException
        return EchoResponse(content=user.email())
# [END echo_api_class]

# [START api_server]
api = endpoints.api_server([EchoApi])
# [END api_server]
<|endoftext|>


<commit_before>""" Module for requesting data from coinchoose.com and parsing it. """
from datetime import date
from datetime import datetime
from datetime import time as tm
from decimal import Decimal
import json
import logging
import requests
import os
from random import random
import sys
import time
import unittest

baseUrl = "http://www.coinchoose.com"
countRequested = 0
interReqTime = 2
lastReqTime = None

def _request(payloadString):
    """Private method for requesting an arbitrary query string."""
    global countRequested
    global lastReqTime
    if lastReqTime is not None and time.time() - lastReqTime < interReqTime:
        timeToSleep = random()*(interReqTime-time.time()+lastReqTime)*2
        logging.info("Sleeping for {0} seconds before request.".format(
            timeToSleep))
        time.sleep(timeToSleep)
    logging.info("Issuing request for the following payload: {0}".format(
        payloadString))
    r = requests.get("{0}/{1}".format(baseUrl, payloadString))
    lastReqTime = time.time()
    countRequested += 1
    if r.status_code == requests.codes.ok:
        return r.text
    else:
        raise Exception("Could not process request. \
            Received status code {0}.".format(r.status_code))

def requestLatest():
    """Method for requesting a the lastest set of information."""
    return _request("api.php?base=BTC")

def parseLatestCurrencies(jsonDump):
    """Parse the latest currency list from an API call."""
    data = []
    rawData = json.loads(jsonDump)
    for rawDatum in rawData:
        datum = {}
        datum['symbol'] = rawDatum['symbol']
        datum['name'] = rawDatum['name']
        datum['algo'] = rawDatum['algo']
        data.append(datum)
    return data

def parseLatestNetworkStatus(jsonDump, scrapeTime=datetime.utcnow()):
    """Parse the latest network status from API call."""
    data = []
    rawData = json.loads(jsonDump)
    for rawDatum in rawData:
        datum = {}
        datum['symbol'] = rawDatum['symbol']
        datum['scrape_time'] = scrapeTime
        datum['current_blocks'] = long(rawDatum['currentBlocks'])
        datum['difficulty'] = Decimal(rawDatum['difficulty'])
        datum['reward'] = Decimal(rawDatum['reward'])
        datum['hash_rate'] = long(rawDatum['networkhashrate'])
        datum['avg_hash_rate'] = Decimal(rawDatum['avgHash'])
        data.append(datum)
    return data

class CoinchooseTest(unittest.TestCase):

    """"Testing suite for coinchoose module."""

    def testRequestLatest(self):
        """Test requestLatest."""
        jsonDump = requestLatest()
        f = open("{0}/data/test_api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'w')
        f.write(jsonDump)
        f.close()
        json.loads(jsonDump)

    def testParseLatestCurrencies(self):
        """Method for testing parseLatestCurrencies."""
        f = open("{0}/example/api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'r')
        jsonDump = f.read()
        f.close()
        data = parseLatestCurrencies(jsonDump)
        self.assertEqual(len(data), 59)
        expectedFirst = {
            'symbol': 'ALF',
            'name': 'Alphacoin',
            'algo': 'scrypt'
        }
        self.assertEqual(data[0], expectedFirst)
        expectedLast = {
            'symbol': 'GLC',
            'name': 'GlobalCoin',
            'algo': 'scrypt'
        }
        self.assertEqual(data[-1], expectedLast)

    def testParseLatestNetworkStatus(self):
        """Method for testing parseLatestNetworkStatus."""
        f = open("{0}/example/api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'r')
        jsonDump = f.read()
        f.close()
        now = datetime.utcnow()
        data = parseLatestNetworkStatus(jsonDump, scrapeTime=now)
        self.assertEqual(len(data), 59)
        expectedFirst = {
            'symbol': 'ALF',
            'scrape_time': now,
            'current_blocks': long(655258),
            'difficulty': Decimal("1.52109832"),
            'reward': Decimal(50),
            'hash_rate': long(10308452),
            'avg_hash_rate': Decimal("10308452.0000")
        }
        self.assertEqual(data[0], expectedFirst)
        expectedLast = {
            'symbol': 'GLC',
            'scrape_time': now,
            'current_blocks': long(300011),
            'difficulty': Decimal("0.768"),
            'reward': Decimal(100),
            'hash_rate': long(0),
            'avg_hash_rate': Decimal("0")
        }
        self.assertEqual(data[-1], expectedLast)

if __name__ == "__main__":
    unittest.main()
<commit_msg>Improved handling of null values returned from JSON-formatted API response<commit_after>""" Module for requesting data from coinchoose.com and parsing it. """
from datetime import date
from datetime import datetime
from datetime import time as tm
from decimal import Decimal
import json
import logging
import requests
import os
from random import random
import sys
import time
import unittest

baseUrl = "http://www.coinchoose.com"
countRequested = 0
interReqTime = 2
lastReqTime = None

def _request(payloadString):
    """Private method for requesting an arbitrary query string."""
    global countRequested
    global lastReqTime
    if lastReqTime is not None and time.time() - lastReqTime < interReqTime:
        timeToSleep = random()*(interReqTime-time.time()+lastReqTime)*2
        logging.info("Sleeping for {0} seconds before request.".format(
            timeToSleep))
        time.sleep(timeToSleep)
    logging.info("Issuing request for the following payload: {0}".format(
        payloadString))
    r = requests.get("{0}/{1}".format(baseUrl, payloadString))
    lastReqTime = time.time()
    countRequested += 1
    if r.status_code == requests.codes.ok:
        return r.text
    else:
        raise Exception("Could not process request. \
            Received status code {0}.".format(r.status_code))

def requestLatest():
    """Method for requesting a the lastest set of information."""
    return _request("api.php?base=BTC")

def parseLatestCurrencies(jsonDump):
    """Parse the latest currency list from an API call."""
    data = []
    rawData = json.loads(jsonDump)
    for rawDatum in rawData:
        datum = {}
        datum['symbol'] = rawDatum['symbol']
        datum['name'] = rawDatum['name']
        datum['algo'] = rawDatum['algo']
        data.append(datum)
    return data

def parseLatestNetworkStatus(jsonDump, scrapeTime=datetime.utcnow()):
    """Parse the latest network status from API call."""
    data = []
    rawData = json.loads(jsonDump)
    for rawDatum in rawData:
        datum = {}
        datum['symbol'] = rawDatum['symbol']
        datum['scrape_time'] = scrapeTime
        datum['current_blocks'] = long(rawDatum['currentBlocks']) if rawDatum['currentBlocks'] is not None else None
        datum['difficulty'] = Decimal(rawDatum['difficulty']) if rawDatum['difficulty'] is not None else None
        datum['reward'] = Decimal(rawDatum['reward']) if rawDatum['reward'] is not None else None
        datum['hash_rate'] = long(rawDatum['networkhashrate']) if rawDatum['networkhashrate'] is not None else None
        datum['avg_hash_rate'] = Decimal(rawDatum['avgHash']) if rawDatum['avgHash'] is not None else None
        data.append(datum)
    return data

class CoinchooseTest(unittest.TestCase):

    """"Testing suite for coinchoose module."""

    def testRequestLatest(self):
        """Test requestLatest."""
        jsonDump = requestLatest()
        f = open("{0}/data/test_api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'w')
        f.write(jsonDump)
        f.close()
        json.loads(jsonDump)

    def testParseLatestCurrencies(self):
        """Method for testing parseLatestCurrencies."""
        f = open("{0}/example/api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'r')
        jsonDump = f.read()
        f.close()
        data = parseLatestCurrencies(jsonDump)
        self.assertEqual(len(data), 59)
        expectedFirst = {
            'symbol': 'ALF',
            'name': 'Alphacoin',
            'algo': 'scrypt'
        }
        self.assertEqual(data[0], expectedFirst)
        expectedLast = {
            'symbol': 'GLC',
            'name': 'GlobalCoin',
            'algo': 'scrypt'
        }
        self.assertEqual(data[-1], expectedLast)

    def testParseLatestNetworkStatus(self):
        """Method for testing parseLatestNetworkStatus."""
        f = open("{0}/example/api.json".format(
            os.path.dirname(os.path.abspath(__file__))), 'r')
        jsonDump = f.read()
        f.close()
        now = datetime.utcnow()
        data = parseLatestNetworkStatus(jsonDump, scrapeTime=now)
        self.assertEqual(len(data), 59)
        expectedFirst = {
            'symbol': 'ALF',
            'scrape_time': now,
            'current_blocks': long(655258),
            'difficulty': Decimal("1.52109832"),
            'reward': Decimal(50),
            'hash_rate': long(10308452),
            'avg_hash_rate': Decimal("10308452.0000")
        }
        self.assertEqual(data[0], expectedFirst)
        expectedLast = {
            'symbol': 'GLC',
            'scrape_time': now,
            'current_blocks': long(300011),
            'difficulty': Decimal("0.768"),
            'reward': Decimal(100),
            'hash_rate': long(0),
            'avg_hash_rate': Decimal("0")
        }
        self.assertEqual(data[-1], expectedLast)

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


<commit_before>#! /usr/bin/env python
import glob
from xml.etree import ElementTree
import logging

log = logging.getLogger('DBus')

INTROSPECTABLE_DBUS = """
<interface name="org.freedesktop.Introspectable">
</interface>
"""

class DBusDevice:
    def __init__(self, bus, proxy):
        self.proxy = proxy
        self.interfaces = set((i for i in (bus.get_interface_for(f)
                                           for f in dir(self.proxy)
                                           if f[0].isupper())
                               if i is not None))
        bus.register_device(self)

    def __setattr__(self, key, value):
        if key[0].islower():
            super().__setattr__(key, value)
            return
        log.debug("set {}.{} = {}".format(self.proxy, key, value))
        setattr(self.proxy, key, value)

    def __getattr__(self, key):
        if key[0].islower():
            return super().__getattr__(key)
        v = getattr(self.proxy, key)
        log.debug("get {}.{} = {}".format(self.proxy, key, v))

        return v if v is not None else ''

class CoiotDBusDeviceInterface:
    def __init__(self, device, path):
        self.device = device
        self.path = "/org/coiot/device/" + path
        self.dbus = '<node>{}</node>'.format("".join(device.interfaces))

    def register_on(self, bus):
        log.info('register {}'.format(self))
        return bus.register_object(self.path, self.device, self.dbus)

    def __str__(self):
        return "{} {}".format(self.path,
                              [e.attrib['name']
                               for e in ElementTree.fromstring(self.dbus)])

def CoiotDBusInterface(xml):
    class Interface:
        def __init__(self, et):
            self.et = et

        @property
        def fields(self):
            return [e.attrib['name']
                    for e in self.et]

        def __str__(self):
            return 'CoiotDBusInterface<{}>'.format(self.et.attrib['name'])

        def xml(self):
            return ElementTree.tostring(self.et).decode('utf-8')

    et = ElementTree.fromstring(xml)
    for e in et:
        if e.tag == 'interface':
            return Interface(e)

class CoiotDBus:
    def __init__(self, bus):
        self.bus = bus
        root_interface = ('/org/coiot/device', self,
                          "<node>{}</node>".format(INTROSPECTABLE_DBUS))
        self.publication = self.bus.publish('org.coiot', root_interface)
        self.known_interfaces = []
        for path in glob.glob('dbus-1/interfaces/org.coiot.*.xml'):
            with open(path, 'r') as f:
                self.known_interfaces.append(CoiotDBusInterface(f.read()))

    def register_device(self, device):
        d = CoiotDBusDeviceInterface(device, device.ID).register_on(self.bus)
        self.publication._at_exit(d.__exit__)

    def get_interface_for(self, field):
        for i in self.known_interfaces:
            if field in i.fields:
                return i.xml()
        return None
<commit_msg>add warnings<commit_after>#! /usr/bin/env python
import glob
from xml.etree import ElementTree
import logging

log = logging.getLogger('DBus')

INTROSPECTABLE_DBUS = """
<interface name="org.freedesktop.Introspectable">
</interface>
"""

class DBusDevice:
    def __init__(self, bus, proxy):
        self.proxy = proxy
        self.interfaces = set((i for i in (bus.get_interface_for(f)
                                           for f in dir(self.proxy)
                                           if f[0].isupper())
                               if i is not None))
        bus.register_device(self)

    def __setattr__(self, key, value):
        if key[0].islower():
            super().__setattr__(key, value)
            return
        log.debug("set {}.{} = {}".format(self.proxy, key, value))
        setattr(self.proxy, key, value)

    def __getattr__(self, key):
        if key[0].islower():
            return super().__getattr__(key)
        v = getattr(self.proxy, key)
        log.debug("get {}.{} = {}".format(self.proxy, key, v))

        return v if v is not None else ''

class CoiotDBusDeviceInterface:
    def __init__(self, device, path):
        self.device = device
        self.path = "/org/coiot/device/" + path
        self.dbus = '<node>{}</node>'.format("".join(device.interfaces))

    def register_on(self, bus):
        log.info('register {}'.format(self))
        return bus.register_object(self.path, self.device, self.dbus)

    def __str__(self):
        return "{} {}".format(self.path,
                              [e.attrib['name']
                               for e in ElementTree.fromstring(self.dbus)])

def CoiotDBusInterface(xml):
    class Interface:
        def __init__(self, et):
            self.et = et

        @property
        def fields(self):
            return [e.attrib['name']
                    for e in self.et]

        def __str__(self):
            return 'CoiotDBusInterface<{}>'.format(self.et.attrib['name'])

        def xml(self):
            return ElementTree.tostring(self.et).decode('utf-8')

    et = ElementTree.fromstring(xml)
    for e in et:
        if e.tag == 'interface':
            return Interface(e)

class CoiotDBus:
    def __init__(self, bus):
        self.bus = bus
        root_interface = ('/org/coiot/device', self,
                          "<node>{}</node>".format(INTROSPECTABLE_DBUS))
        self.publication = self.bus.publish('org.coiot', root_interface)
        self.known_interfaces = []
        for path in glob.glob('dbus-1/interfaces/org.coiot.*.xml'):
            with open(path, 'r') as f:
                self.known_interfaces.append(CoiotDBusInterface(f.read()))

    def register_device(self, device):
        d = CoiotDBusDeviceInterface(device, device.ID).register_on(self.bus)
        self.publication._at_exit(d.__exit__)

    def get_interface_for(self, field):
        for i in self.known_interfaces:
            if field in i.fields:
                return i.xml()
        log.warning("no DBus interface known for {}".format(field))
        return None
<|endoftext|>


<commit_before>#!/usr/bin/python

# This program will update a bar graph of sensor reading in real-time as sensor data is
# received over the serial port. Data input should be in form "x,y;\n" where "x" is the
# sensor index, and "y" is the sensor reading.

#Using pySerial API
from serial.tools import list_ports
import serial

#Using Matplotlib API
import numpy as np
import matplotlib.pyplot as pyplot

import time
import os

N = 8 #number of sensors
BAUD_RATE = 115200

#Limits on sensor readings
Y_max = 1024
Y_min = 0

def main():

    serialPort = setupSerial()

    if (serialPort == None):
        exit()

    pyplot.ion() #turn interactive mode on
    pyplot.figure() #create a figure

    x=[]
    y=[]
    for ii in range(0,10):
        x.append(ii)
        y.append(0)

    drawBarGraph(x,y)

    while 1:

        line = serialPort.readline() #read until we get a newline
        if (line):
            #print line #print the line we got
            tokens = line.split(';')[0].split(',')
            try:
                assert(len(tokens) == 2)

                sensorIndex = int(tokens[0])
                sensorRead = int(tokens[1])
                print "Reading on sensor %s = %s.\n" % (sensorIndex, sensorRead)
                assert(sensorIndex > 0 and sensorIndex < N)

            except ValueError:
                print "Bad serial input (%s)!" % line
                pass
            except AssertionError:
                print "Bad serial input (%s)!" % line
                pass
            else:
			    y[sensorIndex] = sensorRead

			    #Draw the latest plot
			    drawBarGraph(x,y)

def setupSerial():

    print "Available COM ports:"

    ii = 0
    availablePorts = list_serial_ports()
    numSerialPorts = len(availablePorts)
    print availablePorts
    for port in availablePorts:
        print "[%01d] %s" % (ii, port)
        ii = ii + 1

    userIn = raw_input("Which serial port? ")
    try:
        ser_index = int(userIn)
        if (ser_index >= numSerialPorts or ser_index < 0):
            print "Bad input."
            return None
    except ValueError:
        print "Bad input."
        return None

    portName = availablePorts[ser_index]
    print "Attempting to open %s..." % portName
    try:
        ser = serial.Serial(portName,  baudrate=BAUD_RATE, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
    except SerialExcepton as err:
        print "Error opening serial port: %s" % err
        return None

    print "Successfully opened the serial port!"

    return ser

def drawBarGraph(x,y):
    pyplot.bar(np.array(x), np.array(y), width=0.8,align = 'center')
    pyplot.hold(True)
    pyplot.axis([-1, N+1, Y_min, Y_max])
    pyplot.grid()
    pyplot.xlabel('Position')
    pyplot.ylabel('Reading')
    pyplot.hold(False)
    pyplot.draw()

def list_serial_ports():
    # Windows
    if os.name == 'nt':
        # Scan for available ports.
        available = []
        for i in range(256):
            try:
                s = serial.Serial(i)
                available.append('COM'+str(i + 1))
                s.close()
            except serial.SerialException:
                pass
        return available
    else:
        # Mac / Linux
        return [port[0] for port in list_ports.comports()]

if __name__ == '__main__':
    main()
<commit_msg>Minor changes. Works,slowly<commit_after>#!/usr/bin/python

# This program will update a bar graph of sensor reading in real-time as sensor data is
# received over the serial port. Data input should be in form "x,y;\n" where "x" is the
# sensor index, and "y" is the sensor reading.

#Using pySerial API
from serial.tools import list_ports
import serial

#Using Matplotlib API
import numpy as np
import matplotlib.pyplot as pyplot

import time
import os

N = 8 #number of sensors
BAUD_RATE = 115200

#Limits on sensor readings
Y_max = 1024
Y_min = 0

def main():

    serialPort = setupSerial()

    if (serialPort == None):
        exit()

    pyplot.ion() #turn interactive mode on
    pyplot.figure() #create a figure

    x=[]
    y=[]
    for ii in range(0,10):
        x.append(ii)
        y.append(0)

    drawBarGraph(x,y)

    while 1:

        line = serialPort.readline() #read until we get a newline,
        if (line):
            tokens = line.split(';')[0].split(',')
            try:
                assert(len(tokens) == 2)

                sensorIndex = int(tokens[0])
                sensorRead = int(tokens[1])
                print "Reading on sensor %s = %s.\n" % (sensorIndex, sensorRead)
                assert(sensorIndex > 0 and sensorIndex < N)

            except ValueError:
                print "Bad serial input (%s)!" % line
            except AssertionError:
                print "Bad serial input (%s)!" % line
            else:
                y[sensorIndex] = sensorRead
                drawBarGraph(x,y) #redraw

def setupSerial():

    print "Available COM ports:"

    ii = 0
    availablePorts = list_serial_ports()
    numSerialPorts = len(availablePorts)

    for port in availablePorts:
        print "[%01d] %s" % (ii, port)
        ii = ii + 1

    userIn = raw_input("Which serial port? ")
    try:
        ser_index = int(userIn)
        if (ser_index >= numSerialPorts or ser_index < 0):
            print "Bad input."
            return None
    except ValueError:
        print "Bad input."
        return None

    portName = availablePorts[ser_index]
    print "Attempting to open %s..." % portName
    try:
        ser = serial.Serial(portName,  baudrate=BAUD_RATE, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
    except SerialExcepton as err:
        print "Error opening serial port: %s" % err
        return None

    print "Successfully opened the serial port!"

    return ser

def drawBarGraph(x,y):
    pyplot.bar(np.array(x), np.array(y), width=0.8,align = 'center')
    pyplot.hold(True)
    pyplot.axis([-1, N+1, Y_min, Y_max])
    pyplot.grid()
    pyplot.xlabel('Position')
    pyplot.ylabel('Reading')
    pyplot.hold(False)
    pyplot.draw()

def list_serial_ports():
    # Windows
    if os.name == 'nt':
        # Scan for available ports.
        available = []
        for i in range(256):
            try:
                s = serial.Serial(i)
                available.append('COM'+str(i + 1))
                s.close()
            except serial.SerialException:
                pass
        return available
    else:
        # Mac / Linux
        return [port[0] for port in list_ports.comports()]

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


<commit_before>import sublime
import sublime_plugin
import re
from xml.dom.minidom import *
from os.path import basename

class IndentxmlCommand(sublime_plugin.TextCommand):
    def is_enabled(self):
        """
        Enables or disables the 'indentxml' command.
        Command will be disabled if there are currently no text selections and current file is not 'XML' or 'Plain Text'.
        This helps clarify to the user about when the command can be executed, especially useful for UI controls.
        """
        view = self.view
        if view == None:
            return False
        syntax = view.settings().get('syntax')
        language = basename(syntax).replace('.tmLanguage', '').lower() if syntax != None else "plain text"
        return ((language == "xml") or (language == "plain text"))

    def run(self, edit):
        """
        Main plugin logic for the 'indentxml' command.
        """
        view = self.view
        regions = view.sel()
        # if there are more than 1 region or region one and it's not empty
        if len(regions) > 1 or not regions[0].empty():
                for region in view.sel():
                    if not region.empty():
                        s = view.substr(region)
                        s = self.indentxml(s)
                        view.replace(edit, region, s)
        else:   #format all text
                alltextreg = sublime.Region(0, view.size())
                s = view.substr(alltextreg)
                s = self.indentxml(s)
                view.replace(edit, alltextreg, s)

    def indentxml(self, s):
        # convert to utf
        s = s.encode("utf-8")
        # convert to plain string without indents and spaces
        s = re.compile('>\s+([^\s])', re.DOTALL).sub('>\g<1>', s)
        # replace tags to convince minidom process cdata as text
        s = s.replace('<![CDATA[', '%CDATAESTART%').replace(']]>', '%CDATAEEND%')
        s = parseString(s).toprettyxml()
        # remove line breaks
        s = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL).sub('>\g<1></', s)
        # restore cdata
        s = s.replace('%CDATAESTART%', '<![CDATA[').replace('%CDATAEEND%', ']]>')
        # remove xml header
        s = s.replace("<?xml version=\"1.0\" ?>", "").strip()
        return s<commit_msg>xml header processing, closes #8<commit_after>import sublime
import sublime_plugin
import re
from xml.dom.minidom import *
from os.path import basename

class IndentxmlCommand(sublime_plugin.TextCommand):
    def is_enabled(self):
        """
        Enables or disables the 'indentxml' command.
        Command will be disabled if there are currently no text selections and current file is not 'XML' or 'Plain Text'.
        This helps clarify to the user about when the command can be executed, especially useful for UI controls.
        """
        view = self.view
        if view == None:
            return False
        syntax = view.settings().get('syntax')
        language = basename(syntax).replace('.tmLanguage', '').lower() if syntax != None else "plain text"
        return ((language == "xml") or (language == "plain text"))

    def run(self, edit):
        """
        Main plugin logic for the 'indentxml' command.
        """
        view = self.view
        regions = view.sel()
        # if there are more than 1 region or region one and it's not empty
        if len(regions) > 1 or not regions[0].empty():
                for region in view.sel():
                    if not region.empty():
                        s = view.substr(region)
                        s = self.indentxml(s)
                        view.replace(edit, region, s)
        else:   #format all text
                alltextreg = sublime.Region(0, view.size())
                s = view.substr(alltextreg)
                s = self.indentxml(s)
                view.replace(edit, alltextreg, s)

    def indentxml(self, s):
        # convert to utf
        s = s.encode("utf-8")
        xmlheader = re.compile("<\?.*\?>").match(s)
        # convert to plain string without indents and spaces
        s = re.compile('>\s+([^\s])', re.DOTALL).sub('>\g<1>', s)
        # replace tags to convince minidom process cdata as text
        s = s.replace('<![CDATA[', '%CDATAESTART%').replace(']]>', '%CDATAEEND%')
        s = parseString(s).toprettyxml()
        # remove line breaks
        s = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL).sub('>\g<1></', s)
        # restore cdata
        s = s.replace('%CDATAESTART%', '<![CDATA[').replace('%CDATAEEND%', ']]>')
        # remove xml header
        s = s.replace("<?xml version=\"1.0\" ?>", "").strip()
        if xmlheader:
                s = xmlheader.group() + "\n" + s
        return s<|endoftext|>