<commit_before>from django.contrib.auth.models import User

from tastypie import fields
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource

from comics.api.authentication import SecretKeyAuthentication
from comics.api.authorization import SubscriptionAuthorization
from comics.core.models import Comic, Release, Image
from comics.accounts.models import Subscription

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        fields = ['email', 'date_joined', 'last_login']
        resource_name = 'user'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    def dehydrate(self, bundle):
        bundle.data['secret_key'] = \
            bundle.request.user.comics_profile.secret_key
        return bundle

class ComicsResource(ModelResource):
    class Meta:
        queryset = Comic.objects.all()
        resource_name = 'comics'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'active': 'exact',
            'language': 'exact',
            'name': ALL,
            'slug': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(userprofile__user=request.user)
        else:
            return object_list

class ImagesResource(ModelResource):
    class Meta:
        queryset = Image.objects.all()
        resource_name = 'images'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'fetched': ALL,
            'title': ALL,
            'text': ALL,
            'height': ALL,
            'width': ALL,
        }

class ReleasesResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')
    images = fields.ToManyField(ImagesResource, 'images', full=True)

    class Meta:
        queryset = Release.objects.select_related(depth=1
            ).order_by('-fetched')
        resource_name = 'releases'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
            'images': ALL_WITH_RELATIONS,
            'pub_date': ALL,
            'fetched': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(comic__userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(comic__userprofile__user=request.user)
        else:
            return object_list

class SubscriptionResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')

    class Meta:
        queryset = Subscription.objects.all()
        resource_name = 'subscriptions'
        authentication = SecretKeyAuthentication()
        authorization = SubscriptionAuthorization()
        list_allowed_methods = ['get', 'post', 'patch']
        detail_allowed_methods = ['get', 'delete', 'put']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
        }

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(userprofile__user=request.user)

    def obj_create(self, bundle, request=None, **kwargs):
        return super(SubscriptionResource, self).obj_create(bundle, request,
            userprofile=request.user.comics_profile)
<commit_msg>Remove redundant authorization limit<commit_after>from django.contrib.auth.models import User

from tastypie import fields
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource

from comics.api.authentication import SecretKeyAuthentication
from comics.api.authorization import SubscriptionAuthorization
from comics.core.models import Comic, Release, Image
from comics.accounts.models import Subscription

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        fields = ['email', 'date_joined', 'last_login']
        resource_name = 'user'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    def dehydrate(self, bundle):
        bundle.data['secret_key'] = \
            bundle.request.user.comics_profile.secret_key
        return bundle

class ComicsResource(ModelResource):
    class Meta:
        queryset = Comic.objects.all()
        resource_name = 'comics'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'active': 'exact',
            'language': 'exact',
            'name': ALL,
            'slug': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(userprofile__user=request.user)
        else:
            return object_list

class ImagesResource(ModelResource):
    class Meta:
        queryset = Image.objects.all()
        resource_name = 'images'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'fetched': ALL,
            'title': ALL,
            'text': ALL,
            'height': ALL,
            'width': ALL,
        }

class ReleasesResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')
    images = fields.ToManyField(ImagesResource, 'images', full=True)

    class Meta:
        queryset = Release.objects.select_related(depth=1
            ).order_by('-fetched')
        resource_name = 'releases'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
            'images': ALL_WITH_RELATIONS,
            'pub_date': ALL,
            'fetched': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(comic__userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(comic__userprofile__user=request.user)
        else:
            return object_list

class SubscriptionResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')

    class Meta:
        queryset = Subscription.objects.all()
        resource_name = 'subscriptions'
        authentication = SecretKeyAuthentication()
        authorization = SubscriptionAuthorization()
        list_allowed_methods = ['get', 'post', 'patch']
        detail_allowed_methods = ['get', 'delete', 'put']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
        }

    def obj_create(self, bundle, request=None, **kwargs):
        return super(SubscriptionResource, self).obj_create(bundle, request,
            userprofile=request.user.comics_profile)
<|endoftext|>


<commit_before>from django.shortcuts import get_object_or_404, render, redirect
from django.http import JsonResponse, HttpResponse, Http404
from directory.models import CipherSuite, Rfc
import json

def reformat_cs(cs):
    # replace int security rating by string
    if cs['security'] == 0:
        cs['security'] = "recommended"
    elif cs['security'] == 1:
        cs['security'] = "secure"
    elif cs['security'] == 2:
        cs['security'] = "weak"
    elif cs['security'] == 3:
        cs['security'] = "insecure"

    return {cs.pop('name'):cs}

def reformat_rfc(rfc):
    return {rfc.pop('number'):rfc}

def api_root(request):
    api_definition = open('./static/openapi.json', 'rb')
    response = HttpResponse(content=api_definition)
    response['Content-Type'] = 'application/json'
    return response

def cs_all(request):
    cs = [reformat_cs(x.to_dict()) for x in CipherSuite.objects.all()]
    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_single(request, iana_name):
    cs = get_object_or_404(CipherSuite, pk=iana_name)
    return JsonResponse(reformat_cs(cs.to_dict()), safe=False)

def cs_by_security(request, sec_level):
    if sec_level == 'insecure':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=3)]
    elif sec_level == 'weak':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=2)]
    elif sec_level == 'secure':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=1)]
    elif sec_level == 'recommended':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=0)]
    else:
        raise Http404(f"Security level '{sec_level}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_by_software(request, software):
    if software == 'openssl':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.exclude(openssl_name="")]
    elif software == 'gnutls':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.exclude(gnutls_name="")]
    else:
        raise Http404(f"Software '{software}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_by_tlsversion(request, tlsv):
    if tlsv == '10':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="10")]
    elif tlsv == '11':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="11")]
    elif tlsv == '12':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="12")]
    elif tlsv == '13':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="13")]
    else:
        raise Http404(f"TLS version '{tlsv}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def rfc_all(request):
    rfc = [reformat_rfc(x.to_dict()) for x in Rfc.objects.all()]
    return JsonResponse({"rfcs":rfc}, safe=False)

def rfc_single(request, rfc_number):
    rfc = get_object_or_404(Rfc, pk=rfc_number)
    return JsonResponse(reformat_rfc(rfc.to_dict()), safe=False)<commit_msg>fixes path definition of OpenAPI spec<commit_after>from django.shortcuts import get_object_or_404, render, redirect
from django.http import JsonResponse, HttpResponse, Http404
from directory.models import CipherSuite, Rfc
from django.conf import settings
from os.path import join

def reformat_cs(cs):
    # replace int security rating by string
    if cs['security'] == 0:
        cs['security'] = "recommended"
    elif cs['security'] == 1:
        cs['security'] = "secure"
    elif cs['security'] == 2:
        cs['security'] = "weak"
    elif cs['security'] == 3:
        cs['security'] = "insecure"

    return {cs.pop('name'):cs}

def reformat_rfc(rfc):
    return {rfc.pop('number'):rfc}

def api_root(request):
    api_definition = open(join(settings.BASE_DIR, 'static/openapi.json'), 'rb')
    response = HttpResponse(content=api_definition)
    response['Content-Type'] = 'application/json'
    return response

def cs_all(request):
    cs = [reformat_cs(x.to_dict()) for x in CipherSuite.objects.all()]
    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_single(request, iana_name):
    cs = get_object_or_404(CipherSuite, pk=iana_name)
    return JsonResponse(reformat_cs(cs.to_dict()), safe=False)

def cs_by_security(request, sec_level):
    if sec_level == 'insecure':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=3)]
    elif sec_level == 'weak':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=2)]
    elif sec_level == 'secure':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=1)]
    elif sec_level == 'recommended':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(security=0)]
    else:
        raise Http404(f"Security level '{sec_level}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_by_software(request, software):
    if software == 'openssl':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.exclude(openssl_name="")]
    elif software == 'gnutls':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.exclude(gnutls_name="")]
    else:
        raise Http404(f"Software '{software}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def cs_by_tlsversion(request, tlsv):
    if tlsv == '10':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="10")]
    elif tlsv == '11':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="11")]
    elif tlsv == '12':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="12")]
    elif tlsv == '13':
        cs = [reformat_cs(cs.to_dict()) for cs in
                CipherSuite.objects.filter(tls_version__short="13")]
    else:
        raise Http404(f"TLS version '{tlsv}' does not exist.")

    return JsonResponse({"ciphersuites":cs}, safe=False)

def rfc_all(request):
    rfc = [reformat_rfc(x.to_dict()) for x in Rfc.objects.all()]
    return JsonResponse({"rfcs":rfc}, safe=False)

def rfc_single(request, rfc_number):
    rfc = get_object_or_404(Rfc, pk=rfc_number)
    return JsonResponse(reformat_rfc(rfc.to_dict()), safe=False)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import urllib
from module.plugins.Hoster import Hoster

class DepositfilesCom(Hoster):
    __name__ = "DepositfilesCom"
    __type__ = "hoster"
    __pattern__ = r"http://[\w\.]*?depositfiles\.com(/\w{1,3})?/files/[\w]+"
    __version__ = "0.32"
    __description__ = """Depositfiles.com Download Hoster"""
    __author_name__ = ("spoob")
    __author_mail__ = ("spoob@pyload.org")

    def setup(self):
        self.req.canContinue = self.multiDL = True if self.account else False

    def process(self, pyfile):
        self.html = self.load(self.pyfile.url, cookies=True if self.account else False)

        if re.search(r"Such file does not exist or it has been removed for infringement of copyrights", self.html):
            self.offline()

        if not self.account:
            self.handleFree()

        pyfile.name = re.search('File name: ', self.html).group(1)

        if self.account:
            link = urllib.unquote(re.search('
\s*<a href="(http://.+?\.depositfiles.com/.+?)"', self.html).group(1))
        else:
            link = urllib.unquote(re.search('<form action="(http://.+?\.depositfiles.com/.+?)" method="get"', self.html).group(1))

        self.download(link)

    def handleFree(self):
        tmp_url = self.pyfile.url
        match = re.search(r"depositfiles.com/(?:(?P<lang>[\w]{1,3})/)?files/(?P<id>[\w]+)", tmp_url)
        if match:
            if match.group("id"):
                tmp_url = "http://depositfiles.com/en/files/" + match.group("id")

        if re.search(r'File is checked, please try again in a minute.', self.html) is not None:
            self.log.info("DepositFiles.com: The file is being checked. Waiting 1 minute.")
            self.setWait(61)
            self.wait()
            self.retry()

        if re.search(r'Such file does not exist or it has been removed for infringement of copyrights', self.html) is not None:
            self.offline()

        self.html = self.load(tmp_url, post={"gateway_result":"1"})

        m = re.search(r'Attention! You used up your limit for file downloading! Please try in\s+(\d+) minute', self.html)
        if m is not None:
            wait_time = int( m.group(1) )
            self.log.info( "%s: Traffic used up. Waiting %d minutes." % (self.__name__, wait_time) )
            self.setWait(wait_time * 60 + 61) # add another minute :)
            # do we want this?
            #self.wantReconnect = True
            self.wait()

            self.html = self.load(tmp_url, post={"gateway_result":"1"})

        #wait_time = int(re.search(r'(.*?)', self.html).group(1))
        #self.setWait(wait_time)
        #self.log.debug("DepositFiles.com: Waiting %d seconds." % wait_time)
<commit_msg>depositfiles workaround<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import urllib
from module.plugins.Hoster import Hoster

class DepositfilesCom(Hoster):
    __name__ = "DepositfilesCom"
    __type__ = "hoster"
    __pattern__ = r"http://[\w\.]*?depositfiles\.com(/\w{1,3})?/files/[\w]+"
    __version__ = "0.32"
    __description__ = """Depositfiles.com Download Hoster"""
    __author_name__ = ("spoob")
    __author_mail__ = ("spoob@pyload.org")

    def setup(self):
        self.req.canContinue = self.multiDL = True if self.account else False

    def process(self, pyfile):
        self.html = self.load(self.pyfile.url, cookies=True if self.account else False)

        if re.search(r"Such file does not exist or it has been removed for infringement of copyrights", self.html):
            self.offline()

        if not self.account:
            self.handleFree()

        try:
            pyfile.name = re.search('File name: ', self.html).group(1)
        except:
            pyfile.name = re.search('Dateiname: ', self.html).group(1)

        if self.account:
            link = urllib.unquote(re.search('
\s*<a href="(http://.+?\.depositfiles.com/.+?)"', self.html).group(1))
        else:
            link = urllib.unquote(re.search('<form action="(http://.+?\.depositfiles.com/.+?)" method="get"', self.html).group(1))

        self.download(link)

    def handleFree(self):
        tmp_url = self.pyfile.url
        match = re.search(r"depositfiles.com/(?:(?P<lang>[\w]{1,3})/)?files/(?P<id>[\w]+)", tmp_url)
        if match:
            if match.group("id"):
                tmp_url = "http://depositfiles.com/en/files/" + match.group("id")

        if re.search(r'File is checked, please try again in a minute.', self.html) is not None:
            self.log.info("DepositFiles.com: The file is being checked. Waiting 1 minute.")
            self.setWait(61)
            self.wait()
            self.retry()

        if re.search(r'Such file does not exist or it has been removed for infringement of copyrights', self.html) is not None:
            self.offline()

        self.html = self.load(tmp_url, post={"gateway_result":"1"})

        m = re.search(r'Attention! You used up your limit for file downloading! Please try in\s+(\d+) minute', self.html)
        if m is not None:
            wait_time = int( m.group(1) )
            self.log.info( "%s: Traffic used up. Waiting %d minutes." % (self.__name__, wait_time) )
            self.setWait(wait_time * 60 + 61) # add another minute :)
            # do we want this?
            #self.wantReconnect = True
            self.wait()

            self.html = self.load(tmp_url, post={"gateway_result":"1"})

        #wait_time = int(re.search(r'(.*?)', self.html).group(1))
        #self.setWait(wait_time)
        #self.log.debug("DepositFiles.com: Waiting %d seconds." % wait_time)
<|endoftext|>


<commit_before>from django.contrib.auth.models import User

from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource

from comics.api.authentication import (SecretKeyAuthentication,
    MultiAuthentication)
from comics.api.authorization import SubscriptionAuthorization
from comics.core.models import Comic, Release, Image
from comics.accounts.models import Subscription

class UsersResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        fields = ['email', 'date_joined', 'last_login']
        resource_name = 'users'
        authentication = MultiAuthentication(
            BasicAuthentication(realm='Comics API'),
            SecretKeyAuthentication())
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    def dehydrate(self, bundle):
        bundle.data['secret_key'] = \
            bundle.request.user.comics_profile.secret_key
        return bundle

class ComicsResource(ModelResource):
    class Meta:
        queryset = Comic.objects.all()
        resource_name = 'comics'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'active': 'exact',
            'language': 'exact',
            'name': ALL,
            'slug': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(userprofile__user=request.user)
        else:
            return object_list

class ImagesResource(ModelResource):
    class Meta:
        queryset = Image.objects.all()
        resource_name = 'images'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'fetched': ALL,
            'title': ALL,
            'text': ALL,
            'height': ALL,
            'width': ALL,
        }

class ReleasesResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')
    images = fields.ToManyField(ImagesResource, 'images', full=True)

    class Meta:
        queryset = Release.objects.select_related(depth=1
            ).order_by('-fetched')
        resource_name = 'releases'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
            'images': ALL_WITH_RELATIONS,
            'pub_date': ALL,
            'fetched': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(comic__userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(comic__userprofile__user=request.user)
        else:
            return object_list

class SubscriptionsResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')

    class Meta:
        queryset = Subscription.objects.all()
        resource_name = 'subscriptions'
        authentication = SecretKeyAuthentication()
        authorization = SubscriptionAuthorization()
        list_allowed_methods = ['get', 'post', 'patch']
        detail_allowed_methods = ['get', 'delete', 'put']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
        }

    def obj_create(self, bundle, request=None, **kwargs):
        return super(SubscriptionResource, self).obj_create(bundle, request,
            userprofile=request.user.comics_profile)
<commit_msg>Fix renaming bug<commit_after>from django.contrib.auth.models import User

from tastypie import fields
from tastypie.authentication import BasicAuthentication
from tastypie.constants import ALL, ALL_WITH_RELATIONS
from tastypie.resources import ModelResource

from comics.api.authentication import (SecretKeyAuthentication,
    MultiAuthentication)
from comics.api.authorization import SubscriptionAuthorization
from comics.core.models import Comic, Release, Image
from comics.accounts.models import Subscription

class UsersResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        fields = ['email', 'date_joined', 'last_login']
        resource_name = 'users'
        authentication = MultiAuthentication(
            BasicAuthentication(realm='Comics API'),
            SecretKeyAuthentication())
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    def dehydrate(self, bundle):
        bundle.data['secret_key'] = \
            bundle.request.user.comics_profile.secret_key
        return bundle

class ComicsResource(ModelResource):
    class Meta:
        queryset = Comic.objects.all()
        resource_name = 'comics'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'active': 'exact',
            'language': 'exact',
            'name': ALL,
            'slug': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(userprofile__user=request.user)
        else:
            return object_list

class ImagesResource(ModelResource):
    class Meta:
        queryset = Image.objects.all()
        resource_name = 'images'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'fetched': ALL,
            'title': ALL,
            'text': ALL,
            'height': ALL,
            'width': ALL,
        }

class ReleasesResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')
    images = fields.ToManyField(ImagesResource, 'images', full=True)

    class Meta:
        queryset = Release.objects.select_related(depth=1
            ).order_by('-fetched')
        resource_name = 'releases'
        authentication = SecretKeyAuthentication()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
            'images': ALL_WITH_RELATIONS,
            'pub_date': ALL,
            'fetched': ALL,
        }

    def apply_authorization_limits(self, request, object_list):
        if request.GET.get('subscribed') == 'true':
            return object_list.filter(comic__userprofile__user=request.user)
        elif request.GET.get('subscribed') == 'false':
            return object_list.exclude(comic__userprofile__user=request.user)
        else:
            return object_list

class SubscriptionsResource(ModelResource):
    comic = fields.ToOneField(ComicsResource, 'comic')

    class Meta:
        queryset = Subscription.objects.all()
        resource_name = 'subscriptions'
        authentication = SecretKeyAuthentication()
        authorization = SubscriptionAuthorization()
        list_allowed_methods = ['get', 'post', 'patch']
        detail_allowed_methods = ['get', 'delete', 'put']
        filtering = {
            'comic': ALL_WITH_RELATIONS,
        }

    def obj_create(self, bundle, request=None, **kwargs):
        return super(SubscriptionsResource, self).obj_create(bundle, request,
            userprofile=request.user.comics_profile)
<|endoftext|>


<commit_before>import simplejson as json
import yaml
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt

import api.models as models
import directions.models as directions
import users.models as users
from slog import models as slog

def translit(locallangstring):
    """
    Translit func
    :param locallangstring: orign
    :return: translit of locallangstring
    """
    conversion = {
        u'\u0410' : 'A',    u'\u0430' : 'a',
        u'\u0411' : 'B',    u'\u0431' : 'b',
        u'\u0412' : 'V',    u'\u0432' : 'v',
        u'\u0413' : 'G',    u'\u0433' : 'g',
        u'\u0414' : 'D',    u'\u0434' : 'd',
        u'\u0415' : 'E',    u'\u0435' : 'e',
        u'\u0401' : 'Yo',   u'\u0451' : 'yo',
        u'\u0416' : 'Zh',   u'\u0436' : 'zh',
        u'\u0417' : 'Z',    u'\u0437' : 'z',
        u'\u0418' : 'I',    u'\u0438' : 'i',
        u'\u0419' : 'Y',    u'\u0439' : 'y',
        u'\u041a' : 'K',    u'\u043a' : 'k',
        u'\u041b' : 'L',    u'\u043b' : 'l',
        u'\u041c' : 'M',    u'\u043c' : 'm',
        u'\u041d' : 'N',    u'\u043d' : 'n',
        u'\u041e' : 'O',    u'\u043e' : 'o',
        u'\u041f' : 'P',    u'\u043f' : 'p',
        u'\u0420' : 'R',    u'\u0440' : 'r',
        u'\u0421' : 'S',    u'\u0441' : 's',
        u'\u0422' : 'T',    u'\u0442' : 't',
        u'\u0423' : 'U',    u'\u0443' : 'u',
        u'\u0424' : 'F',    u'\u0444' : 'f',
        u'\u0425' : 'H',    u'\u0445' : 'h',
        u'\u0426' : 'Ts',   u'\u0446' : 'ts',
        u'\u0427' : 'Ch',   u'\u0447' : 'ch',
        u'\u0428' : 'Sh',   u'\u0448' : 'sh',
        u'\u0429' : 'Sch',  u'\u0449' : 'sch',
        u'\u042a' : '',    u'\u044a' : '',
        u'\u042b' : 'Y',    u'\u044b' : 'y',
        u'\u042c' : '',   u'\u044c' : '',
        u'\u042d' : 'E',    u'\u044d' : 'e',
        u'\u042e' : 'Yu',   u'\u044e' : 'yu',
        u'\u042f' : 'Ya',   u'\u044f' : 'ya',
    }
    translitstring = []
    for c in locallangstring:
        translitstring.append(conversion.setdefault(c, c))
    return ''.join(translitstring)

@csrf_exempt
def send(request):
    """
    Sysmex save results
    :param request:
    :return:
    """
    result = {"ok": False}
    try:
        if request.method == "POST":
            resdict = yaml.load(request.POST["result"])
            appkey = request.POST.get("key", "")
        else:
            resdict = yaml.load(request.GET["result"])
            appkey = request.GET.get("key", "")

        astm_user = users.DoctorProfile.objects.filter(user__username="astm").first()
        resdict["pk"] = int(resdict.get("pk", -111))
        if "LYMPH%" in resdict["result"]:
            resdict["orders"] = {}

        dpk = -1
        if "bydirection" in request.POST or "bydirection" in request.GET:
            dpk = resdict["pk"]

            if dpk >= 4600000000000:
                dpk -= 4600000000000
                dpk //= 10

                if directions.TubesRegistration.objects.filter(issledovaniya__napravleniye__pk=dpk).exists():
                    resdict["pk"] = directions.TubesRegistration.objects.filter(
                        issledovaniya__napravleniye__pk=dpk).first().pk
                else:
                    resdict["pk"] = False
                resdict["bysapphire"] = True
        result["A"] = appkey
        if resdict["pk"] and models.Application.objects.filter(key=appkey).exists() and models.Application.objects.get(key=appkey).active and directions.TubesRegistration.objects.filter(pk=resdict["pk"]).exists():
            tubei = directions.TubesRegistration.objects.get(pk=resdict["pk"])
            direction = tubei.issledovaniya_set.first().napravleniye
            for key in resdict["result"].keys():
                if models.RelationFractionASTM.objects.filter(astm_field=key).exists():
                    fractionRels = models.RelationFractionASTM.objects.filter(astm_field=key)
                    for fractionRel in fractionRels:
                        fraction = fractionRel.fraction
                        if directions.Issledovaniya.objects.filter(napravleniye=direction,
                                                                   research=fraction.research, doc_confirmation__isnull=True).exists():
                            issled = directions.Issledovaniya.objects.filter(napravleniye=direction,
                                                                          research=fraction.research, doc_confirmation__isnull=True).order_by("pk")[0]
                            fraction_result = None
                            if directions.Result.objects.filter(issledovaniye=issled,
                                                                fraction=fraction).exists():  # Если результат для фракции существует
                                fraction_result = directions.Result.objects.get(issledovaniye=issled,
                                                                                fraction__pk=fraction.pk)  # Выборка результата из базы
                            else:
                                fraction_result = directions.Result(issledovaniye=issled,
                                                                    fraction=fraction)  # Создание нового результата
                            fraction_result.value = str(resdict["result"][key]).strip()  # Установка значения
                            if fraction_result.value.isdigit():
                                fraction_result.value = "%s.0" % fraction_result.value
                            import re
                            find = re.findall("\d+.\d+", fraction_result.value)
                            if len(find) > 0:
                                val = float(find[0]) * fractionRel.get_multiplier_display()
                                if fractionRel.full_round:
                                    val = round(val)
                                fraction_result.value = fraction_result.value.replace(find[0], str(val))

                            fraction_result.iteration = 1  # Установка итерации
                            ref = fractionRel.default_ref
                            if ref:
                                fraction_result.ref_title = ref.title
                                fraction_result.ref_about = ref.about
                                fraction_result.ref_m = ref.m
                                fraction_result.ref_f = ref.f
                            fraction_result.save()  # Сохранение
                            issled.api_app = models.Application.objects.get(key=appkey)
                            issled.save()
                            fraction_result.get_ref(re_save=True)
                            fraction_result.issledovaniye.doc_save = astm_user  # Кто сохранил
                            from datetime import datetime
                            fraction_result.issledovaniye.time_save = timezone.now()  # Время сохранения
                            fraction_result.issledovaniye.save()
            slog.Log(key=appkey, type=22, body=json.dumps(resdict), user=astm_user).save()
            result["ok"] = True
        elif not directions.TubesRegistration.objects.filter(pk=resdict["pk"]).exists():
            if dpk > -1:
                resdict["pk"] = dpk
            slog.Log(key=resdict["pk"], type=23, body=json.dumps(resdict), user=astm_user).save()
    except Exception as e:
        result = {"ok": False, "Exception": True, "MSG": str(e)}
    return HttpResponse(json.dumps(result), content_type="application/json")  # Создание JSON
<commit_msg>Bugfix<commit_after>import simplejson as json
import yaml
from django.http import HttpResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt

import api.models as models
import directions.models as directions
import users.models as users
from slog import models as slog

def translit(locallangstring):
    """
    Translit func
    :param locallangstring: orign
    :return: translit of locallangstring
    """
    conversion = {
        u'\u0410' : 'A',    u'\u0430' : 'a',
        u'\u0411' : 'B',    u'\u0431' : 'b',
        u'\u0412' : 'V',    u'\u0432' : 'v',
        u'\u0413' : 'G',    u'\u0433' : 'g',
        u'\u0414' : 'D',    u'\u0434' : 'd',
        u'\u0415' : 'E',    u'\u0435' : 'e',
        u'\u0401' : 'Yo',   u'\u0451' : 'yo',
        u'\u0416' : 'Zh',   u'\u0436' : 'zh',
        u'\u0417' : 'Z',    u'\u0437' : 'z',
        u'\u0418' : 'I',    u'\u0438' : 'i',
        u'\u0419' : 'Y',    u'\u0439' : 'y',
        u'\u041a' : 'K',    u'\u043a' : 'k',
        u'\u041b' : 'L',    u'\u043b' : 'l',
        u'\u041c' : 'M',    u'\u043c' : 'm',
        u'\u041d' : 'N',    u'\u043d' : 'n',
        u'\u041e' : 'O',    u'\u043e' : 'o',
        u'\u041f' : 'P',    u'\u043f' : 'p',
        u'\u0420' : 'R',    u'\u0440' : 'r',
        u'\u0421' : 'S',    u'\u0441' : 's',
        u'\u0422' : 'T',    u'\u0442' : 't',
        u'\u0423' : 'U',    u'\u0443' : 'u',
        u'\u0424' : 'F',    u'\u0444' : 'f',
        u'\u0425' : 'H',    u'\u0445' : 'h',
        u'\u0426' : 'Ts',   u'\u0446' : 'ts',
        u'\u0427' : 'Ch',   u'\u0447' : 'ch',
        u'\u0428' : 'Sh',   u'\u0448' : 'sh',
        u'\u0429' : 'Sch',  u'\u0449' : 'sch',
        u'\u042a' : '',    u'\u044a' : '',
        u'\u042b' : 'Y',    u'\u044b' : 'y',
        u'\u042c' : '',   u'\u044c' : '',
        u'\u042d' : 'E',    u'\u044d' : 'e',
        u'\u042e' : 'Yu',   u'\u044e' : 'yu',
        u'\u042f' : 'Ya',   u'\u044f' : 'ya',
    }
    translitstring = []
    for c in locallangstring:
        translitstring.append(conversion.setdefault(c, c))
    return ''.join(translitstring)

@csrf_exempt
def send(request):
    """
    Sysmex save results
    :param request:
    :return:
    """
    result = {"ok": False}
    try:
        if request.method == "POST":
            resdict = yaml.load(request.POST["result"])
            appkey = request.POST.get("key", "")
        else:
            resdict = yaml.load(request.GET["result"])
            appkey = request.GET.get("key", "")

        astm_user = users.DoctorProfile.objects.filter(user__username="astm").first()
        resdict["pk"] = int(resdict.get("pk", -111))
        if "LYMPH%" in resdict["result"]:
            resdict["orders"] = {}

        dpk = -1
        if "bydirection" in request.POST or "bydirection" in request.GET:
            dpk = resdict["pk"]

            if dpk >= 4600000000000:
                dpk -= 4600000000000
                dpk //= 10

            if directions.TubesRegistration.objects.filter(issledovaniya__napravleniye__pk=dpk).exists():
                resdict["pk"] = directions.TubesRegistration.objects.filter(
                    issledovaniya__napravleniye__pk=dpk).first().pk
            else:
                resdict["pk"] = False
        result["A"] = appkey
        if resdict["pk"] and models.Application.objects.filter(key=appkey).exists() and models.Application.objects.get(key=appkey).active and directions.TubesRegistration.objects.filter(pk=resdict["pk"]).exists():
            tubei = directions.TubesRegistration.objects.get(pk=resdict["pk"])
            direction = tubei.issledovaniya_set.first().napravleniye
            for key in resdict["result"].keys():
                if models.RelationFractionASTM.objects.filter(astm_field=key).exists():
                    fractionRels = models.RelationFractionASTM.objects.filter(astm_field=key)
                    for fractionRel in fractionRels:
                        fraction = fractionRel.fraction
                        if directions.Issledovaniya.objects.filter(napravleniye=direction,
                                                                   research=fraction.research, doc_confirmation__isnull=True).exists():
                            issled = directions.Issledovaniya.objects.filter(napravleniye=direction,
                                                                          research=fraction.research, doc_confirmation__isnull=True).order_by("pk")[0]
                            fraction_result = None
                            if directions.Result.objects.filter(issledovaniye=issled,
                                                                fraction=fraction).exists():  # Если результат для фракции существует
                                fraction_result = directions.Result.objects.get(issledovaniye=issled,
                                                                                fraction__pk=fraction.pk)  # Выборка результата из базы
                            else:
                                fraction_result = directions.Result(issledovaniye=issled,
                                                                    fraction=fraction)  # Создание нового результата
                            fraction_result.value = str(resdict["result"][key]).strip()  # Установка значения
                            if fraction_result.value.isdigit():
                                fraction_result.value = "%s.0" % fraction_result.value
                            import re
                            find = re.findall("\d+.\d+", fraction_result.value)
                            if len(find) > 0:
                                val = float(find[0]) * fractionRel.get_multiplier_display()
                                if fractionRel.full_round:
                                    val = round(val)
                                fraction_result.value = fraction_result.value.replace(find[0], str(val))

                            fraction_result.iteration = 1  # Установка итерации
                            ref = fractionRel.default_ref
                            if ref:
                                fraction_result.ref_title = ref.title
                                fraction_result.ref_about = ref.about
                                fraction_result.ref_m = ref.m
                                fraction_result.ref_f = ref.f
                            fraction_result.save()  # Сохранение
                            issled.api_app = models.Application.objects.get(key=appkey)
                            issled.save()
                            fraction_result.get_ref(re_save=True)
                            fraction_result.issledovaniye.doc_save = astm_user  # Кто сохранил
                            from datetime import datetime
                            fraction_result.issledovaniye.time_save = timezone.now()  # Время сохранения
                            fraction_result.issledovaniye.save()
            slog.Log(key=appkey, type=22, body=json.dumps(resdict), user=astm_user).save()
            result["ok"] = True
        elif not directions.TubesRegistration.objects.filter(pk=resdict["pk"]).exists():
            if dpk > -1:
                resdict["pk"] = dpk
            slog.Log(key=resdict["pk"], type=23, body=json.dumps(resdict), user=astm_user).save()
    except Exception as e:
        result = {"ok": False, "Exception": True, "MSG": str(e)}
    return HttpResponse(json.dumps(result), content_type="application/json")  # Создание JSON
<|endoftext|>


<commit_before># import logging
import sqlite3
import os
import re
import telebot
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def db_setup(dbfile='troll.db'):
    db = sqlite3.connect(dbfile)
    cursor = db.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS quotes (chatid int, quote text)')
    cursor.execute('DELETE FROM quotes WHERE chatid = 0')
    with open(os.path.expanduser('~/staticquotes.txt'), 'r') as staticquotes:
        for line in staticquotes:
            cursor.execute('''INSERT INTO quotes(chatid,quote) VALUES(?,?)''', (0, line.strip()))
    db.commit()
    db.close()

if 'TOKEN' not in os.environ:
    print("missing TOKEN.Leaving...")
    os._exit(1)

# logger = telebot.logger
# telebot.logger.setLevel(logging.DEBUG)
bot = telebot.TeleBot(os.environ['TOKEN'])
botname = "@%s" % bot.get_me().username

@bot.message_handler(commands=['start', "start%s" % botname])
def start(message):
    startmessage = ''' *Welcome to the troll bot*

This bot is designed to ease trolling within your group chats

/troll to get a random troll
/troll PATTERN to get matching troll
/trolladd PATTERN to add troll to current group
/trolldelete PATTERN to delete troll from current group
'''
    bot.reply_to(message, startmessage, parse_mode='Markdown')

@bot.message_handler(commands=['trollhelp', 'help', "help%s" % botname])
def help(message):
    helpmessage = '''Those are the commands available:
troll - Displays random or matching troll
trolladd - Adds indicated troll
trolldelete - Deletes given troll
trolllist - Lists all trolls
trollhelp - This help
'''
    bot.reply_to(message, helpmessage)

@bot.message_handler(commands=['troll'])
def get(message):
    global trolldb
    quote = re.sub(r"/troll(%s|)" % botname, '', message.text).strip()
    chatid = message.chat.id if message.chat.title is not None else 0
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    if quote == '':
        cursor.execute('''SELECT quote FROM quotes WHERE chatid = ? OR chatid = 0 ORDER BY RANDOM() LIMIT 1''', (chatid,))
        fetch = cursor.fetchone()
    else:
        cursor.execute("SELECT quote FROM quotes WHERE quote like ? AND (chatid = ? OR chatid = 0) ORDER BY RANDOM() LIMIT 1", ('%' + quote + '%', chatid,))
        fetch = cursor.fetchone()
        if fetch is None:
            print("No Matching quote found")
            bot.reply_to(message, 'No Matching quote found')
            return
    quote = fetch[0]
    db.close()
    print("Sending troll message to user %s" % message.from_user.username)
    bot.reply_to(message, quote)

@bot.message_handler(commands=['trollall', 'trolllist'])
def all(message):
    global trolldb
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    if 'group' in message.chat.type:
        cursor.execute('SELECT quote FROM quotes where chatid = ? or chatid = 0', (message.chat.id,))
    else:
        cursor.execute('SELECT quote FROM quotes where chatid = 0')
    quotes = '\n'.join([q[0] for q in cursor.fetchall()])
    db.close()
    print("Sending all troll messages to user %s" % message.from_user.username)
    bot.reply_to(message, quotes)

@bot.message_handler(commands=['trolladd'])
def add(message):
    global trolldb
    quote = re.sub(r"/trolladd(%s|)" % botname, '', message.text).strip()
    if quote == '':
        bot.reply_to(message, 'Missing troll text to add')
        return
    quote = quote.strip()
    if 'group' not in message.chat.type:
        bot.reply_to(message, 'Trolls can only be added to groups')
        return
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    cursor.execute('''INSERT INTO quotes(chatid,quote) VALUES(?,?)''', (message.chat.id, quote))
    print("Adding Troll message to group %s" % message.chat.title)
    bot.reply_to(message, 'Troll added to your group')
    db.commit()
    db.close()

@bot.message_handler(commands=['trolldel', 'trolldelete'])
def delete(message):
    global trolldb
    quote = re.sub(r"/troll(delete|del)(%s|)" % botname, '', message.text).strip()
    print quote
    if quote == '':
        bot.reply_to(message, 'Missing troll text to delete')
        return
    if 'group' not in message.chat.type:
        bot.reply_to(message, 'Trolls can only be deleted from groups')
        return
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    deleted = cursor.execute('''DELETE FROM QUOTES WHERE chatid = ? and  quote = ?''', (message.chat.id, quote))
    if deleted.rowcount > 0:
        print("Deleted Troll message from group %s" % message.chat.title)
        bot.reply_to(message, 'Troll deleted from your channel')
    else:
        print("No Troll message deleted from group %s" % message.chat.title)
        bot.reply_to(message, 'Troll was not deleted from your group')
    db.commit()
    db.close()

trolldb = os.path.expanduser("~/troll.db")
db_setup(dbfile=trolldb)
print("Ready for trolling!")
bot.polling()
<commit_msg>Answer chupito everytime transcoding keyword is detected<commit_after># import logging
import sqlite3
import os
import re
import telebot
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def db_setup(dbfile='troll.db'):
    db = sqlite3.connect(dbfile)
    cursor = db.cursor()
    cursor.execute('CREATE TABLE IF NOT EXISTS quotes (chatid int, quote text)')
    cursor.execute('DELETE FROM quotes WHERE chatid = 0')
    with open(os.path.expanduser('~/staticquotes.txt'), 'r') as staticquotes:
        for line in staticquotes:
            cursor.execute('''INSERT INTO quotes(chatid,quote) VALUES(?,?)''', (0, line.strip()))
    db.commit()
    db.close()

if 'TOKEN' not in os.environ:
    print("missing TOKEN.Leaving...")
    os._exit(1)

# logger = telebot.logger
# telebot.logger.setLevel(logging.DEBUG)
bot = telebot.TeleBot(os.environ['TOKEN'])
botname = "@%s" % bot.get_me().username

@bot.message_handler(commands=['start', "start%s" % botname])
def start(message):
    startmessage = ''' *Welcome to the troll bot*

This bot is designed to ease trolling within your group chats

/troll to get a random troll
/troll PATTERN to get matching troll
/trolladd PATTERN to add troll to current group
/trolldelete PATTERN to delete troll from current group
'''
    bot.reply_to(message, startmessage, parse_mode='Markdown')

@bot.message_handler(commands=['trollhelp', 'help', "help%s" % botname])
def help(message):
    helpmessage = '''Those are the commands available:
troll - Displays random or matching troll
trolladd - Adds indicated troll
trolldelete - Deletes given troll
trolllist - Lists all trolls
trollhelp - This help
'''
    bot.reply_to(message, helpmessage)

@bot.message_handler(commands=['troll'])
def get(message):
    global trolldb
    quote = re.sub(r"/troll(%s|)" % botname, '', message.text).strip()
    chatid = message.chat.id if message.chat.title is not None else 0
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    if quote == '':
        cursor.execute('''SELECT quote FROM quotes WHERE chatid = ? OR chatid = 0 ORDER BY RANDOM() LIMIT 1''', (chatid,))
        fetch = cursor.fetchone()
    else:
        cursor.execute("SELECT quote FROM quotes WHERE quote like ? AND (chatid = ? OR chatid = 0) ORDER BY RANDOM() LIMIT 1", ('%' + quote + '%', chatid,))
        fetch = cursor.fetchone()
        if fetch is None:
            print("No Matching quote found")
            bot.reply_to(message, 'No Matching quote found')
            return
    quote = fetch[0]
    db.close()
    print("Sending troll message to user %s" % message.from_user.username)
    bot.reply_to(message, quote)

@bot.message_handler(commands=['trollall', 'trolllist'])
def all(message):
    global trolldb
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    if 'group' in message.chat.type:
        cursor.execute('SELECT quote FROM quotes where chatid = ? or chatid = 0', (message.chat.id,))
    else:
        cursor.execute('SELECT quote FROM quotes where chatid = 0')
    quotes = '\n'.join([q[0] for q in cursor.fetchall()])
    db.close()
    print("Sending all troll messages to user %s" % message.from_user.username)
    bot.reply_to(message, quotes)

@bot.message_handler(commands=['trolladd'])
def add(message):
    global trolldb
    quote = re.sub(r"/trolladd(%s|)" % botname, '', message.text).strip()
    if quote == '':
        bot.reply_to(message, 'Missing troll text to add')
        return
    quote = quote.strip()
    if 'group' not in message.chat.type:
        bot.reply_to(message, 'Trolls can only be added to groups')
        return
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    cursor.execute('''INSERT INTO quotes(chatid,quote) VALUES(?,?)''', (message.chat.id, quote))
    print("Adding Troll message to group %s" % message.chat.title)
    bot.reply_to(message, 'Troll added to your group')
    db.commit()
    db.close()

@bot.message_handler(commands=['trolldel', 'trolldelete'])
def delete(message):
    global trolldb
    quote = re.sub(r"/troll(delete|del)(%s|)" % botname, '', message.text).strip()
    print quote
    if quote == '':
        bot.reply_to(message, 'Missing troll text to delete')
        return
    if 'group' not in message.chat.type:
        bot.reply_to(message, 'Trolls can only be deleted from groups')
        return
    db = sqlite3.connect(trolldb)
    cursor = db.cursor()
    deleted = cursor.execute('''DELETE FROM QUOTES WHERE chatid = ? and  quote = ?''', (message.chat.id, quote))
    if deleted.rowcount > 0:
        print("Deleted Troll message from group %s" % message.chat.title)
        bot.reply_to(message, 'Troll deleted from your channel')
    else:
        print("No Troll message deleted from group %s" % message.chat.title)
        bot.reply_to(message, 'Troll was not deleted from your group')
    db.commit()
    db.close()

@bot.message_handler(func=lambda m: True)
def custom(message):
    if 'transcoding' in message.text.lower():
        bot.reply_to(message, 'chupito!!!')

trolldb = os.path.expanduser("~/troll.db")
db_setup(dbfile=trolldb)
print("Ready for trolling!")
bot.polling()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import tornado.web

from admin.models import MyAdminBucket

class APIDashboardHandler(tornado.web.RequestHandler):
    def get(self):
        get_bucket = MyAdminBucket.get('dashboard').data
        if get_bucket is None:
            get_bucket = []

        self.write(json.dumps(get_bucket))
        self.finish()
<commit_msg>create CubeQuery to return sample cube process<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import tornado.web
import riak

from pandas import DataFrame
from sqlalchemy import create_engine
from sqlalchemy.sql import text

from settings import (RIAK_PROTOCOL, RIAK_HTTP_PORT,
                      RIAK_HOST, ADMIN_BUCKET_NAME,
                      MINING_BUCKET_NAME, MEMCACHE_CONNECTION, MEMCACHE_DEBUG)
from admin.models import MyAdminBucket

class APIDashboardHandler(tornado.web.RequestHandler):
    def get(self):
        get_bucket = MyAdminBucket.get('dashboard').data
        if get_bucket is None:
            get_bucket = []

        self.write(json.dumps(get_bucket))
        self.finish()

class CubeQuery(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        post = json.loads(self.request.body)

        MyClient = riak.RiakClient(protocol=RIAK_PROTOCOL,
                                   http_port=RIAK_HTTP_PORT,
                                   host=RIAK_HOST)

        MyAdminBucket = MyClient.bucket(ADMIN_BUCKET_NAME)

        connection = None
        for c in MyAdminBucket.get('connection').data:
            if c['slug'] == post.get('connection', None):
                connection = c['connection']

        sql = """SELECT * FROM ({}) AS CUBE LIMIT 10;""".format(
            post.get('sql', None))

        e = create_engine(connection)
        connection = e.connect()
        resoverall = connection.execute(text(sql))

        df = DataFrame(resoverall.fetchall())
        if df.empty:
            self.finish()
        df.columns = resoverall.keys()
        df.head()

        self.write(df.to_json(orient='records'))
        self.finish()
<|endoftext|>


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

import pygame
from pygame.locals import *  # noqa
import sys
import random
import socket
#import Theft
import re
import select
import math

pygame.mixer.init(44100, -16,2,2048)
#pygame.mixer.music.load("main_theme_fast.ogg")
#pygame.mixer.music.play(-1)
start_sound = pygame.mixer.Sound("start.wav")
play_sound = pygame.mixer.Sound("main_theme_fast.ogg")
falling_sound = pygame.mixer.Sound("death.wav")
port = 7000
server = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
server.bind(('', port))
server.setblocking(0)
clock = pygame.time.Clock()
class FlappyBird:

    def __init__(self):

        #self.background = pygame.image.load("assets/background.png").convert()
        #self.background = pygame.transform.scale(self.background,(657, 298))
        self.screen = pygame.display.set_mode((657, 296),0,32)

        self.bird = pygame.Rect(65, 50, 26, 48) #??

        #self.clock = pygame.time.Clock()

        self.asset_1 = pygame.image.load("assets/1.png").convert_alpha()
        self.asset_2 = pygame.image.load("assets/2.png").convert_alpha()
        self.asset_3 = pygame.image.load("assets/3.png").convert_alpha()
        self.asset_d = pygame.image.load("assets/dead.png").convert_alpha()

        self.asset_1 = pygame.transform.scale(self.asset_1,(26, 48))
        self.asset_2 = pygame.transform.scale(self.asset_2,(26, 48))
        self.asset_3 = pygame.transform.scale(self.asset_3,(26, 48))
        self.asset_d = pygame.transform.scale(self.asset_d,(26, 48))

        self.birdSprites = [self.asset_1, self.asset_2, self.asset_d, self.asset_3]

        # self.birdSprites = [pygame.image.load("assets/1.png").convert_alpha(), #different motions of the birds
                            # pygame.image.load("assets/2.png").convert_alpha(),
                            # pygame.image.load("assets/dead.png")]
        # self.birdSprites = pygame.transform.scale(self.birdSprites,(26, 48))

        self.wallUp = pygame.image.load("assets/bottom.png").convert_alpha() #the walls
        self.wallUp = pygame.transform.scale(self.wallUp,(30, 150))

        #self.wallDown = pygame.image.load("assets/top.png").convert_alpha()

        self.start_img = pygame.image.load("assets/start.png").convert_alpha() #start screen
        self.start_img = pygame.transform.scale(self.start_img,(657, 298))

        self.get_ready_img = pygame.image.load("assets/get_ready.png").convert_alpha() #get ready marks
        self.gap = 200 #distance between upper wall and lower wall
        self.wallx = 657
        self.birdY = 249
        self.jump = -100
        self.jumpSpeed = 15
        self.gravity = 5
        self.dead = False
        self.sprite = 0
        self.counter = 0
        self.offset = random.randint(-50, 50)
        self.state = "start"
        self.font = 0
        clock = 0

    # def background(self):

        # b1 = "assets/background.png"
        # back = pygame.image.load(b1).convert()
        # back2 = pygame.image.load(b1).convert()
        # back = pygame.transform.scale(back,(3687, 296))
        # back2 = pygame.transform.scale(back2,(3687, 296))

        # x = 3687
        # screenWidth = 3687

        # while True:
            # for event in pygame.event.get():
                # if event.type == QUIT:
                    # pygame.quit()
                    # sys.exit()

            # self.screen.blit(back, (x,0))
            # self.screen.blit(back2,(x-screenWidth,0))

            # x = x - 1
            # if x == 0:
                # x = screenWidth

            # msElapsed = clock.tick(100)
            # pygame.display.flip()

    def updateWalls(self):
        speed = 5 + self.counter/10*2
        self.wallx -= speed
        if self.wallx < -80:
            self.wallx = 657
            self.counter += 1
            self.offset = random.randint(-50, 50)

    def birdUpdate(self):
        if self.jump > 0:
            self.jumpSpeed = self.jumpSpeed - 1
            self.birdY = self.birdY - self.jumpSpeed
            self.jump = self.jump - 1

        elif -40< self.jump <= 0:
            self.jumpSpeed = 10
            self.birdY = self.birdY + self.jumpSpeed
            self.jump = self.jump - 1
            if self.birdY >= 230:
                self.birdY = 249
                self.jump == -100

        else :
            self.birdY = self.birdY
            self.jump == -100

            # self.jump = self.jump - 1
            # self.birdY += self.gravity
            # self.gravity += 0.2

        self.bird[1] = self.birdY #provide info for collision

        # upRect = pygame.Rect(self.wallx,
                             # 200 + self.offset,
                             # self.wallUp.get_width() - 10,
                             # self.wallUp.get_height()) # the area of the plump (up plump)
        upRect = pygame.Rect(self.wallx,
                             220 + self.offset,
                             30,
                             150) # the area of the plump (up plump)

        # downRect = pygame.Rect(self.wallx,
                               # 0 - self.gap - self.offset - 10,
                               # self.wallDown.get_width() - 10,
                               # self.wallDown.get_height()) #plump (down plump)

        if upRect.colliderect(self.bird): # overlap: dead
            self.dead = True
            self.bird[1] = 50
            self.birdY = 249
            self.dead = False
            self.wallx = 657
            self.offset = random.randint(-30, 30)
            self.gravity = 5
            self.state = "end" #dead
            self.sprite = 1

         #if downRect.colliderect(self.bird):
             #self.dead = True

        # if not 0 < self.bird[1] < 720:
            # self.bird[1] = 50
            # self.birdY = 298
            # self.dead = False
            # self.wallx = 657
            # self.offset = random.randint(-50, 50)
            # self.gravity = 5
            # self.state = "end" #dead

    def play(self):

        #self.screen.fill((255, 255, 255)) #fill Surface with white color???
        #self.screen.blit(self.background, (0, 0)) #draw one image onto another
        # self.screen.blit(self.wallUp,
                         # (self.wallx, 360 + self.gap - self.offset))

        # b1 = "assets/background.png"
        # back = pygame.image.load(b1).convert()
        # back2 = pygame.image.load(b1).convert()
        # back = pygame.transform.scale(back,(3687, 296))
        # back2 = pygame.transform.scale(back2,(3687, 296))

        # x = 3687
        # screenWidth = 3687

        # while True:
            # for event in pygame.event.get():
                # if event.type == QUIT:
                    # pygame.quit()
                    # sys.exit()

        # self.screen.blit(back, (x,0))
        # self.screen.blit(back2,(x-screenWidth,0))

        # x = x - 1
        # if x == 0:
            # x = screenWidth

        # msElapsed = clock.tick(100)
        # pygame.display.flip()
        self.updateWalls()

        self.screen.blit(self.wallUp,
                          (self.wallx, 220 + self.offset))

        # self.screen.blit(self.wallDown,
                         # (self.wallx, 0 - self.gap - self.offset)) # two pipes

        self.screen.blit(self.font.render("Score:" + str(self.counter*10), # points counter
                                     -1,
                                     (255, 255, 255)),
                                     (10, 10)) #render(text, antialias, color, background=None)
        self.screen.blit(self.font.render("Level " + str(self.counter/10+1), # points counter
                                     -1,
                                     (255, 255, 255)),
                                     (550, 10)) #render(text, antialias, color, background=None)
        self.birdUpdate()

        if self.dead:
            self.sprite = 2
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        #elif self.jump >-40:
        elif self.jump >-40 :
            self.sprite = 1
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        else:
            self.sprite = 0
            #clock.tick(60)
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))
            #clock.tick(60)
            # self.sprite = 3
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

    def start_screen (self):
        self.screen.fill((255, 0, 0)) #red
        self.screen.blit(self.start_img, (0, 0))

        get_ready_x = 241 + 20 * math.sin(pygame.time.get_ticks() / 500.0)
        get_ready_y = 125 + 10 * math.sin(pygame.time.get_ticks() / 150.0)

        self.screen.blit(self.get_ready_img, (get_ready_x, get_ready_y))#get ready animation
        # self.screen.blit(self.font.render(str(self.counter),
                     # -1,
                     # (255, 255, 255)),
              # (10, 10))

    def run(self):
        #self.clock = pygame.time.Clock()
        pygame.font.init()
        self.font = pygame.font.SysFont("Consolas", 20) 	#create a Font object from the system fonts

        b1 = "assets/background.png"
        back = pygame.image.load(b1).convert()
        back2 = pygame.image.load(b1).convert()
        back = pygame.transform.scale(back,(3687, 296))
        back2 = pygame.transform.scale(back2,(3687, 296))

        x = 3687
        screenWidth = 3687
        speed = 5 + self.counter/10*2

        while True:
            clock.tick(60) #unit:ms
            readable, writable, errored  = select.select([server], [], [], 0)

            if self.state == "play":
                self.screen.blit(back, (x,0))
                self.screen.blit(back2,(x-screenWidth,0))

                x = x - speed
                if x <= 0:
                    x = screenWidth

                #msElapsed = clock.tick(60)
                pygame.display.flip()

            for s in readable: #with nodes
                if s is server:
                    data, addr = server.recvfrom(1024)
                    if data:
                        rpt = Theft.Theft(data=data, data_length=len(data)) #probably need to work with the nodes
                        if (rpt.get_sender() ==2 and rpt.get_stolen() == 1) and not self.dead: #player1, stolen: light sensor covered: jump
                            self.jump = 17
                            self.gravity = 5
                            self.jumpSpeed = 15
                        if (rpt.get_sender() ==3 and rpt.get_humidity() > 2000) and not self.dead: #player2, decrease the gap width
                            self.gap = 160
                        elif (rpt.get_sender() ==3 and rpt.get_humidity() < 2000):
                            self.gap = 200
                        if (rpt.get_sender() ==2 and rpt.get_button() == 1):
                            self.state = "play" #begin game
                            self.counter = 0
            for event in pygame.event.get():# without nodes
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.KEYDOWN and not self.dead: #press, default: space key
                    self.jump = 17
                    self.gravity = 5
                    self.jumpSpeed = 15
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.state == 'end':
                        self.state = 'start'
                    elif self.state == 'start':
                        #self.counter = 0
                        self.state = "play" #reset counter

            if self.state == "end":
                self.screen.fill((0, 0, 0)) #black
                self.screen.blit(self.font.render("Game Over. Score: " + str(10*self.counter),
                             -1,
                             (255, 255, 255)),
                      (220, 140))
                pygame.mixer.Sound.stop(play_sound)
                pygame.mixer.Sound.play(falling_sound)

            if self.state == "play":
                self.play()
                pygame.mixer.Sound.stop(start_sound)
                pygame.mixer.Sound.play(play_sound)
            if self.state == "start":
                self.start_screen();
                self.counter = 0
                pygame.mixer.Sound.stop(falling_sound)
                pygame.mixer.Sound.play(start_sound)

            pygame.display.update()

if __name__ == "__main__":
    FlappyBird().run()
<commit_msg>modified key response<commit_after>#!/usr/bin/env python

import pygame
from pygame.locals import *  # noqa
import sys
import random
import socket
#import Theft
import re
import select
import math

pygame.mixer.init(44100, -16,2,2048)
#pygame.mixer.music.load("main_theme_fast.ogg")
#pygame.mixer.music.play(-1)
start_sound = pygame.mixer.Sound("start.wav")
play_sound = pygame.mixer.Sound("main_theme_fast.ogg")
falling_sound = pygame.mixer.Sound("death.wav")
port = 7000
server = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
server.bind(('', port))
server.setblocking(0)
clock = pygame.time.Clock()

class FlappyBird:

    def __init__(self):

        #self.background = pygame.image.load("assets/background.png").convert()
        #self.background = pygame.transform.scale(self.background,(657, 298))
        self.screen = pygame.display.set_mode((657, 296),0,32)

        self.bird = pygame.Rect(65, 50, 26, 48) #??

        #self.clock = pygame.time.Clock()

        self.asset_1 = pygame.image.load("assets/1.png").convert_alpha()
        self.asset_2 = pygame.image.load("assets/2.png").convert_alpha()
        self.asset_3 = pygame.image.load("assets/3.png").convert_alpha()
        self.asset_d = pygame.image.load("assets/dead.png").convert_alpha()

        self.asset_1 = pygame.transform.scale(self.asset_1,(26, 48))
        self.asset_2 = pygame.transform.scale(self.asset_2,(26, 48))
        self.asset_3 = pygame.transform.scale(self.asset_3,(26, 48))
        self.asset_d = pygame.transform.scale(self.asset_d,(26, 48))

        self.birdSprites = [self.asset_1, self.asset_2, self.asset_d, self.asset_3]

        # self.birdSprites = [pygame.image.load("assets/1.png").convert_alpha(), #different motions of the birds
                            # pygame.image.load("assets/2.png").convert_alpha(),
                            # pygame.image.load("assets/dead.png")]
        # self.birdSprites = pygame.transform.scale(self.birdSprites,(26, 48))

        self.wallUp = pygame.image.load("assets/bottom.png").convert_alpha() #the walls
        self.wallUp = pygame.transform.scale(self.wallUp,(30, 150))

        #self.wallDown = pygame.image.load("assets/top.png").convert_alpha()

        self.start_img = pygame.image.load("assets/start.png").convert_alpha() #start screen
        self.start_img = pygame.transform.scale(self.start_img,(657, 298))

        self.get_ready_img = pygame.image.load("assets/get_ready.png").convert_alpha() #get ready marks
        self.gap = 200 #distance between upper wall and lower wall
        self.wallx = 657
        self.birdY = 249
        self.jump = -100
        self.jumpSpeed = 15
        self.gravity = 5
        self.dead = False
        self.sprite = 0
        self.counter = 0
        self.offset = random.randint(-50, 50)
        self.state = "start"
        self.font = 0
        #clock = 0
        self.enemy = 0
        self.jumpcount = 0;

    # def background(self):

        # b1 = "assets/background.png"
        # back = pygame.image.load(b1).convert()
        # back2 = pygame.image.load(b1).convert()
        # back = pygame.transform.scale(back,(3687, 296))
        # back2 = pygame.transform.scale(back2,(3687, 296))

        # x = 3687
        # screenWidth = 3687

        # while True:
            # for event in pygame.event.get():
                # if event.type == QUIT:
                    # pygame.quit()
                    # sys.exit()

            # self.screen.blit(back, (x,0))
            # self.screen.blit(back2,(x-screenWidth,0))

            # x = x - 1
            # if x == 0:
                # x = screenWidth

            # msElapsed = clock.tick(100)
            # pygame.display.flip()

    def updateWalls(self):
        speed = 5 + self.counter/10*2
        self.wallx = self.wallx - speed - self.enemy
        if self.wallx < -80:
            self.wallx = 657
            self.counter += 1
            self.offset = random.randint(-50, 50)

    def birdUpdate(self):
        if self.jump > 0:
            self.jumpSpeed = self.jumpSpeed - 1
            self.birdY = self.birdY - self.jumpSpeed
            self.jump = self.jump - 1

        elif -40< self.jump <= 0:
            self.jumpSpeed = 10
            self.birdY = self.birdY + self.jumpSpeed
            self.jump = self.jump - 1
            if self.birdY >= 230:
                self.birdY = 249
                self.jump == -100

        else :
            self.birdY = self.birdY
            self.jump == -100

            # self.jump = self.jump - 1
            # self.birdY += self.gravity
            # self.gravity += 0.2

        self.bird[1] = self.birdY #provide info for collision

        # upRect = pygame.Rect(self.wallx,
                             # 200 + self.offset,
                             # self.wallUp.get_width() - 10,
                             # self.wallUp.get_height()) # the area of the plump (up plump)
        upRect = pygame.Rect(self.wallx,
                             220 + self.offset,
                             30,
                             150) # the area of the plump (up plump)

        # downRect = pygame.Rect(self.wallx,
                               # 0 - self.gap - self.offset - 10,
                               # self.wallDown.get_width() - 10,
                               # self.wallDown.get_height()) #plump (down plump)

        if upRect.colliderect(self.bird): # overlap: dead
            self.dead = True
            self.bird[1] = 50
            self.birdY = 249
            self.dead = False
            self.wallx = 657
            self.offset = random.randint(-30, 30)
            self.gravity = 5
            self.state = "end" #dead
            self.sprite = 1

         #if downRect.colliderect(self.bird):
             #self.dead = True

        # if not 0 < self.bird[1] < 720:
            # self.bird[1] = 50
            # self.birdY = 298
            # self.dead = False
            # self.wallx = 657
            # self.offset = random.randint(-50, 50)
            # self.gravity = 5
            # self.state = "end" #dead

    def play(self):

        #self.screen.fill((255, 255, 255)) #fill Surface with white color???
        #self.screen.blit(self.background, (0, 0)) #draw one image onto another
        # self.screen.blit(self.wallUp,
                         # (self.wallx, 360 + self.gap - self.offset))

        # b1 = "assets/background.png"
        # back = pygame.image.load(b1).convert()
        # back2 = pygame.image.load(b1).convert()
        # back = pygame.transform.scale(back,(3687, 296))
        # back2 = pygame.transform.scale(back2,(3687, 296))

        # x = 3687
        # screenWidth = 3687

        # while True:
            # for event in pygame.event.get():
                # if event.type == QUIT:
                    # pygame.quit()
                    # sys.exit()

        # self.screen.blit(back, (x,0))
        # self.screen.blit(back2,(x-screenWidth,0))

        # x = x - 1
        # if x == 0:
            # x = screenWidth

        # msElapsed = clock.tick(100)
        # pygame.display.flip()
        self.updateWalls()

        self.screen.blit(self.wallUp,
                          (self.wallx, 220 + self.offset))

        # self.screen.blit(self.wallDown,
                         # (self.wallx, 0 - self.gap - self.offset)) # two pipes

        self.screen.blit(self.font.render("Score:" + str(self.counter*10), # points counter
                                     -1,
                                     (255, 255, 255)),
                                     (10, 10)) #render(text, antialias, color, background=None)
        self.screen.blit(self.font.render("Level " + str(self.counter/10+1), # points counter
                                     -1,
                                     (255, 255, 255)),
                                     (550, 10)) #render(text, antialias, color, background=None)
        self.screen.blit(self.font.render("jump: " + str(self.jump), # points counter
                                     -1,
                                     (255, 255, 255)),
                                     (300, 10)) #render(text, antialias, color, background=None)
        self.birdUpdate()

        if self.dead:
            self.sprite = 2
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        #elif self.jump >-40:
        elif self.jump >-40 :
            self.sprite = 1
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        else:
            self.sprite = 0
            #clock.tick(60)
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))
            #clock.tick(60)
            # self.sprite = 3
            # self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

        self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))

    def start_screen (self):
        self.screen.fill((255, 0, 0)) #red
        self.screen.blit(self.start_img, (0, 0))

        get_ready_x = 241 + 20 * math.sin(pygame.time.get_ticks() / 500.0)
        get_ready_y = 125 + 10 * math.sin(pygame.time.get_ticks() / 150.0)

        self.screen.blit(self.get_ready_img, (get_ready_x, get_ready_y))#get ready animation
        # self.screen.blit(self.font.render(str(self.counter),
                     # -1,
                     # (255, 255, 255)),
              # (10, 10))

    def run(self):
        #self.clock = pygame.time.Clock()
        pygame.font.init()
        self.font = pygame.font.SysFont("Consolas", 20) 	#create a Font object from the system fonts

        b1 = "assets/background.png"
        back = pygame.image.load(b1).convert()
        back2 = pygame.image.load(b1).convert()
        back = pygame.transform.scale(back,(3687, 296))
        back2 = pygame.transform.scale(back2,(3687, 296))

        x = 3687
        screenWidth = 3687
        speed = 5 + self.counter/10*2

        while True:
            clock.tick(60) #unit:ms
            readable, writable, errored  = select.select([server], [], [], 0)

            if self.state == "play":
                self.screen.blit(back, (x,0))
                self.screen.blit(back2,(x-screenWidth,0))

                x = x - speed  - self.enemy
                if x <= 0:
                    x = screenWidth

                #msElapsed = clock.tick(60)
                pygame.display.flip()

            for s in readable: #with nodes
                if s is server:
                    data, addr = server.recvfrom(1024)
                    if data:
                        rpt = Theft.Theft(data=data, data_length=len(data)) #probably need to work with the nodes
                        if (rpt.get_sender() ==2 and rpt.get_stolen() == 1) and not self.dead: #player1, stolen: light sensor covered: jump
                            self.jump = 17
                            self.gravity = 5
                            self.jumpSpeed = 15
                        if (rpt.get_sender() ==3 and rpt.get_humidity() > 2000) and not self.dead: #player2, decrease the gap width
                            self.gap = 160
                        elif (rpt.get_sender() ==3 and rpt.get_humidity() < 2000):
                            self.gap = 200
                        if (rpt.get_sender() ==2 and rpt.get_button() == 1):
                            self.state = "play" #begin game
                            self.counter = 0
            for event in pygame.event.get():# without nodes
                if event.type == pygame.QUIT:
                    sys.exit()
                #if event.type == pygame.KEYDOWN and not self.dead: #press, default: space key
                if (pygame.key.get_pressed()[pygame.K_SPACE] != 0) and (self.jump == -100):
                    self.jump = 17
                    self.gravity = 5
                    self.jumpSpeed = 15
                if (pygame.key.get_pressed()[pygame.K_UP] != 0):
                    self.enemy = 2;
                else:
                    self.enemy = 0;
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.state == 'end':
                        self.state = 'start'
                    elif self.state == 'start':
                        #self.counter = 0
                        self.state = "play" #reset counter

            if self.state == "end":
                self.screen.fill((0, 0, 0)) #black
                self.screen.blit(self.font.render("Game Over. Score: " + str(10*self.counter),
                             -1,
                             (255, 255, 255)),
                      (220, 140))
                pygame.mixer.Sound.stop(play_sound)
                pygame.mixer.Sound.play(falling_sound)

            if self.state == "play":
                self.play()
                pygame.mixer.Sound.stop(start_sound)
                pygame.mixer.Sound.play(play_sound)
            if self.state == "start":
                self.start_screen();
                self.counter = 0
                pygame.mixer.Sound.stop(falling_sound)
                pygame.mixer.Sound.play(start_sound)

            pygame.display.update()

if __name__ == "__main__":
    FlappyBird().run()
<|endoftext|>


<commit_before>from pola import logic, logic_ai
from django.http import JsonResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from product.models import Product
from pola.models import Query
from report.models import Report, Attachment
from ai_pics.models import AIPics, AIAttachment
from django.conf import settings
import json
import os
import uuid
import time
import base64
import hmac
import urllib
from hashlib import sha1
from ratelimit.decorators import ratelimit

# API v3

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def add_ai_pics(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    product_id = data.get('product_id')
    files_count = data['files_count']
    file_ext = data['file_ext']
    mime_type = data['mime_type']

    original_width = data['original_width']
    original_height = data['original_height']

    #TODO: add some down scaling if needed
    width = original_width
    height = original_height

    device_name = data['device_name']
    flash_used = data.get('flash_used', None)
    was_portrait = data.get('was_portrait', None)

    product = Product.objects.get(pk=product_id)

    ai_pics = AIPics.objects.create(product=product,
                                    client=device_id,
                                    original_width= original_width,
                                    original_height= original_height,
                                    width= width,
                                    height= height,
                                    device_name= device_name,
                                    flash_used= flash_used,
                                    was_portrait= was_portrait
                                    )

    signed_requests = []
    if files_count and file_ext and mime_type:
        if files_count > 24:
            return HttpResponseForbidden("files_count can be between 0 and 24")

        for i in range(0, files_count):
            signed_request = attach_pic_internal(ai_pics, i, file_ext, mime_type)
            signed_requests.append(signed_request)

    return JsonResponse({'width': width,
                         'height': height,
                         'signed_requests': signed_requests})

def attach_pic_internal(ai_pics, file_no, file_ext, mime_type):
    object_name = '%s/%s_%s_%s.%s' % (str(ai_pics.product.code),
                str(ai_pics.id), str(file_no), str(uuid.uuid1()), file_ext)

    signed_request = create_signed_request(mime_type, object_name, settings.AWS_STORAGE_BUCKET_AI_NAME)

    attachment = AIAttachment(ai_pics=ai_pics)
    attachment.attachment.name = object_name
    attachment.save()

    return signed_request

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code_v3(request):

    result = get_by_code_internal(request, ai_supported = True)

    return JsonResponse(result)

# API v2

def get_by_code_internal(request, ai_supported = False):
    code = request.GET['code']
    device_id = request.GET['device_id']

    result, stats, product = logic.get_result_from_code(code)

    if product is not None:
        Query.objects.create(client=device_id, product=product,
                             was_verified=stats['was_verified'],
                             was_590=stats['was_590'],
                             was_plScore=stats['was_plScore'])

    if product:
        product.increment_query_count()
        if product.company:
            product.company.increment_query_count()

    if product and ai_supported:
        result = logic_ai.add_ask_for_pics(result)

    return result

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code_v2(request):

    result = get_by_code_internal(request)

    return JsonResponse(result)

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def create_report_v2(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    description = data['description']
    product_id = data.get('product_id', None)
    files_count = data.get('files_count', None)
    file_ext = data.get('file_ext', None)
    mime_type = data.get('mime_type', None)

    product = None
    if product_id:
        product = Product.objects.get(pk=product_id)

    report = Report.objects.create(product=product, description=description,
                                   client=device_id)

    signed_requests = []
    if files_count and file_ext and mime_type:
        if files_count>10:
            return HttpResponseForbidden("files_count can be between 0 and 10")

        for _ in range(0, files_count):
            signed_request = attach_file_internal(report, file_ext, mime_type)
            signed_requests.append(signed_request)

    return JsonResponse({'id': report.id,
                         'signed_requests':signed_requests})

def attach_file_internal(report, file_ext, mime_type):
    object_name = '%s/%s.%s' % (str(report.id), str(uuid.uuid1()), file_ext)

    signed_request = create_signed_request(mime_type, object_name, settings.AWS_STORAGE_BUCKET_NAME)

    attachment = Attachment(report=report)
    attachment.attachment.name = object_name
    attachment.save()

    return signed_request

def create_signed_request(mime_type, object_name, bucket_name):
    expires = int(time.time() + 60 * 60 * 24)
    amz_headers = "x-amz-acl:public-read"

    string_to_sign = "PUT\n\n%s\n%d\n%s\n/%s/%s" % \
                     (mime_type, expires, amz_headers,
                      bucket_name, object_name)

    signature = base64.encodestring(
        hmac.new(settings.AWS_SECRET_ACCESS_KEY.encode(),
                 string_to_sign.encode('utf8'), sha1).digest())
    signature = urllib.quote_plus(signature.strip())
    url = 'https://%s.s3.amazonaws.com/%s' % (bucket_name,
                                              object_name)
    signed_request = '%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s' % \
                     (url, settings.AWS_ACCESS_KEY_ID, expires, signature),
    return signed_request

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def attach_file_v2(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    data = json.loads(request.body)
    file_ext = data['file_ext']
    mime_type = data['mime_type']

    signed_request = attach_file_internal(report, file_ext, mime_type)

    return JsonResponse({'signed_request': signed_request})

#--- API v1 (old)

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code(request, code):
    device_id = request.GET['device_id']

    product = logic.get_by_code(code=code)

    result = logic.serialize_product(product)

    Query.objects.create(client=device_id, product=product,
                         was_verified=result['verified'],
                         was_590=code.startswith('590'),
                         was_plScore=result['plScore'] is not None)

    if product:
        product.increment_query_count()
        if product.company:
            product.company.increment_query_count()

    return JsonResponse(result)

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def create_report(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    description = data['description']
    product_id = data.get('product_id', None)

    product = None
    if product_id:
        product = Product.objects.get(pk=product_id)

    report = Report.objects.create(product=product, description=description,
                                   client=device_id)

    return JsonResponse({'id': report.id})

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def update_report(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    data = json.loads(request.body)
    description = data['description']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    report.description = description
    report.save()

    return JsonResponse({'id': report.id})

@csrf_exempt
@ratelimit(key='ip', rate='5/s', block=True)
def attach_file(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    attachment = Attachment(attachment=request.FILES['file'], report=report)
    file_name, file_extension = os.path.splitext(attachment.attachment.name)
    attachment.attachment.name = str(uuid.uuid1()) + file_extension
    attachment.save()

    return JsonResponse({'id': attachment.id})
<commit_msg>testing<commit_after>from pola import logic, logic_ai
from django.http import JsonResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from product.models import Product
from pola.models import Query
from report.models import Report, Attachment
from ai_pics.models import AIPics, AIAttachment
from django.conf import settings
import json
import os
import uuid
import time
import base64
import hmac
import urllib
from hashlib import sha1
from ratelimit.decorators import ratelimit

# API v3

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def add_ai_pics(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    product_id = data.get('product_id')
    files_count = data['files_count']
    file_ext = data['file_ext']
    mime_type = data['mime_type']

    original_width = data['original_width']
    original_height = data['original_height']

    #TODO: add some down scaling if needed
    width = original_width
    height = original_height

    device_name = data['device_name']
    flash_used = data.get('flash_used', None)
    was_portrait = data.get('was_portrait', None)

    product = Product.objects.get(pk=product_id)

    ai_pics = AIPics.objects.create(product=product,
                                    client=device_id,
                                    original_width= original_width,
                                    original_height= original_height,
                                    width= width,
                                    height= height,
                                    device_name= device_name,
                                    flash_used= flash_used,
                                    was_portrait= was_portrait
                                    )

    signed_requests = []
    if files_count and file_ext and mime_type:
        if files_count > 24:
            return HttpResponseForbidden("files_count can be between 0 and 24")

        for i in range(0, files_count):
            signed_request = attach_pic_internal(ai_pics, i, file_ext, mime_type)
            signed_requests.append(signed_request)

    return JsonResponse({'width': width,
                         'height': height,
                         'signed_requests': signed_requests})

def attach_pic_internal(ai_pics, file_no, file_ext, mime_type):
    object_name = '%s/%s_%s_%s.%s' % (str(ai_pics.product.code),
                str(ai_pics.id), str(file_no), str(uuid.uuid1()), file_ext)

    signed_request = create_signed_request(mime_type, object_name, settings.AWS_STORAGE_BUCKET_AI_NAME)

    attachment = AIAttachment(ai_pics=ai_pics)
    attachment.attachment.name = object_name
    attachment.save()

    return signed_request

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code_v3(request):

    result = get_by_code_internal(request, ai_supported = True)

    return JsonResponse(result)

# API v2

def get_by_code_internal(request, ai_supported = False):
    code = request.GET['code']
    device_id = request.GET['device_id']

    result, stats, product = logic.get_result_from_code(code)

    if product is not None:
        Query.objects.create(client=device_id, product=product,
                             was_verified=stats['was_verified'],
                             was_590=stats['was_590'],
                             was_plScore=stats['was_plScore'])

    if product:
        product.increment_query_count()
        if product.company:
            product.company.increment_query_count()

    if product and ai_supported:
        result = logic_ai.add_ask_for_pics(result)

    return result

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code_v2(request):

    result = get_by_code_internal(request)

    return JsonResponse(result)

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def create_report_v2(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    description = data['description']
    product_id = data.get('product_id', None)
    files_count = data.get('files_count', None)
    file_ext = data.get('file_ext', None)
    mime_type = data.get('mime_type', None)

    product = None
    if product_id:
        product = Product.objects.get(pk=product_id)

    report = Report.objects.create(product=product, description=description,
                                   client=device_id)

    signed_requests = []
    if files_count and file_ext and mime_type:
        if files_count>10:
            return HttpResponseForbidden("files_count can be between 0 and 10")

        for _ in range(0, files_count):
            signed_request = attach_file_internal(report, file_ext, mime_type)
            signed_requests.append(signed_request)

    return JsonResponse({'id': report.id,
                         'signed_requests':signed_requests})

def attach_file_internal(report, file_ext, mime_type):
    object_name = '%s/%s.%s' % (str(report.id), str(uuid.uuid1()), file_ext)

    signed_request = create_signed_request(mime_type, object_name, settings.AWS_STORAGE_BUCKET_NAME)

    attachment = Attachment(report=report)
    attachment.attachment.name = object_name
    attachment.save()

    return signed_request

def create_signed_request(mime_type, object_name, bucket_name):
    expires = int(time.time() + 60 * 60 * 24)
    amz_headers = "x-amz-acl:public-read"

    string_to_sign = "PUT\n\n%s\n%d\n%s\n/%s/%s" % \
                     (mime_type, expires, amz_headers,
                      bucket_name, object_name)

    signature = base64.encodestring(
        hmac.new(settings.AWS_SECRET_ACCESS_KEY.encode(),
                 string_to_sign.encode('utf8'), sha1).digest())
    signature = urllib.quote_plus(signature.strip())
    url = 'https://%s.s3.eu-central-1.amazonaws.com/%s' % (bucket_name,
                                              object_name)
    signed_request = '%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s' % \
                     (url, settings.AWS_ACCESS_KEY_ID, expires, signature),
    return signed_request

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def attach_file_v2(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    data = json.loads(request.body)
    file_ext = data['file_ext']
    mime_type = data['mime_type']

    signed_request = attach_file_internal(report, file_ext, mime_type)

    return JsonResponse({'signed_request': signed_request})

#--- API v1 (old)

@ratelimit(key='ip', rate='2/s', block=True)
def get_by_code(request, code):
    device_id = request.GET['device_id']

    product = logic.get_by_code(code=code)

    result = logic.serialize_product(product)

    Query.objects.create(client=device_id, product=product,
                         was_verified=result['verified'],
                         was_590=code.startswith('590'),
                         was_plScore=result['plScore'] is not None)

    if product:
        product.increment_query_count()
        if product.company:
            product.company.increment_query_count()

    return JsonResponse(result)

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def create_report(request):
    device_id = request.GET['device_id']

    data = json.loads(request.body)
    description = data['description']
    product_id = data.get('product_id', None)

    product = None
    if product_id:
        product = Product.objects.get(pk=product_id)

    report = Report.objects.create(product=product, description=description,
                                   client=device_id)

    return JsonResponse({'id': report.id})

@csrf_exempt
@ratelimit(key='ip', rate='2/s', block=True)
def update_report(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    data = json.loads(request.body)
    description = data['description']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    report.description = description
    report.save()

    return JsonResponse({'id': report.id})

@csrf_exempt
@ratelimit(key='ip', rate='5/s', block=True)
def attach_file(request):
    device_id = request.GET['device_id']
    report_id = request.GET['report_id']

    report = Report.objects.get(pk=report_id)

    if report.client != device_id:
        return HttpResponseForbidden("Device_id mismatch")

    attachment = Attachment(attachment=request.FILES['file'], report=report)
    file_name, file_extension = os.path.splitext(attachment.attachment.name)
    attachment.attachment.name = str(uuid.uuid1()) + file_extension
    attachment.save()

    return JsonResponse({'id': attachment.id})
<|endoftext|>