commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
d86cfb740f4119049a7ac293037f9cba12a3516b
sqliteschema/_const.py
sqliteschema/_const.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ MAX_VERBOSITY_LEVEL = 100 # https://www.sqlite.org/fileformat2.html SQLITE_SYSTEM_TABLES = [ "sqlite_master", "sqlite_sequence", "sqlite_stat1", "sqlite_stat2", "sqlite_stat3", "sqlite_stat4", ] SQLITE_SYSTEM_TABLE_LIST = SQLITE_SYSTEM_TABLES # deprecated class SchemaHeader(object): ATTR_NAME = "Attribute" DATA_TYPE = "Type" PRIMARY_KEY = "PRIMARY KEY" NOT_NULL = "NOT NULL" UNIQUE = "UNIQUE" INDEX = "Index"
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ MAX_VERBOSITY_LEVEL = 100 # https://www.sqlite.org/fileformat2.html SQLITE_SYSTEM_TABLES = ( "sqlite_master", "sqlite_sequence", "sqlite_stat1", "sqlite_stat2", "sqlite_stat3", "sqlite_stat4", ) SQLITE_SYSTEM_TABLE_LIST = SQLITE_SYSTEM_TABLES # deprecated class SchemaHeader(object): ATTR_NAME = "Attribute" DATA_TYPE = "Type" PRIMARY_KEY = "PRIMARY KEY" NOT_NULL = "NOT NULL" UNIQUE = "UNIQUE" INDEX = "Index"
Change a constant type from list to tuple
Change a constant type from list to tuple
Python
mit
thombashi/sqliteschema
--- +++ @@ -8,14 +8,14 @@ MAX_VERBOSITY_LEVEL = 100 # https://www.sqlite.org/fileformat2.html -SQLITE_SYSTEM_TABLES = [ +SQLITE_SYSTEM_TABLES = ( "sqlite_master", "sqlite_sequence", "sqlite_stat1", "sqlite_stat2", "sqlite_stat3", "sqlite_stat4", -] +) SQLITE_SYSTEM_TABLE_LIST = SQLITE_SYSTEM_TABLES # deprecated
eac54b3080c37d2530077f23b0c022ed818ca9a4
util/fixedpoint-qtcreator.py
util/fixedpoint-qtcreator.py
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] d.putValue(sum(exp) * 2**-value["fractionalWidth"].integer()) if d.isExpanded(): with Children(d): d.putSubItem("fractionalWidth", value["fractionalWidth"]) d.putSubItem("integerWidth", value["integerWidth"]) d.putSubItem("v", value["v"]) def qdump__MultiwordInteger(d, value): d.putNumChild(3) raw = [ value["s"][i].integer() for i in range( value["numWords"].integer() ) ] exp = [ raw[i] * 2**(i * value["storageSize"].integer()) for i in range(len(raw)) ] d.putValue(sum(exp)) if d.isExpanded(): with Children(d): d.putSubItem("numWords", value["numWords"]) d.putSubItem("storageSize", value["storageSize"]) d.putSubItem("s", value["s"])
from dumper import * def qdump__FixedPoint(d, value): d.putNumChild(3) raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] if raw[-1] >= 2**(ss-1): exp += [ -2**(ss * len(raw)) ] d.putValue(sum(exp) * 2**-value["fractionalWidth"].integer()) if d.isExpanded(): with Children(d): d.putSubItem("fractionalWidth", value["fractionalWidth"]) d.putSubItem("integerWidth", value["integerWidth"]) d.putSubItem("v", value["v"]) def qdump__MultiwordInteger(d, value): d.putNumChild(3) raw = [ value["s"][i].integer() for i in range( value["numWords"].integer() ) ] exp = [ raw[i] * 2**(i * value["storageSize"].integer()) for i in range(len(raw)) ] d.putValue(sum(exp)) if d.isExpanded(): with Children(d): d.putSubItem("numWords", value["numWords"]) d.putSubItem("storageSize", value["storageSize"]) d.putSubItem("s", value["s"])
Support negative numbers in qtcreator debugging
Support negative numbers in qtcreator debugging
Python
mit
Cat-Ion/FixedPoint,Cat-Ion/FixedPoint
--- +++ @@ -5,6 +5,8 @@ raw = [ value["v"]["s"][i].integer() for i in range( value["v"]["numWords"].integer() ) ] ss = value["v"]["storageSize"].integer() exp = [raw[i] * 2**(i * ss) for i in range(len(raw)) ] + if raw[-1] >= 2**(ss-1): + exp += [ -2**(ss * len(raw)) ] d.putValue(sum(exp) * 2**-value["fractionalWidth"].integer()) if d.isExpanded(): with Children(d):
218b0f9a42c8d3421f80a3b2b77c9f7f3334722d
test_publisher.py
test_publisher.py
import publisher test_pdf_filename = "test/test.pdf" test_css_filename = "test/test.css" test_md_filename = "test/test.md" test_html_filename = "test/test.html" test_md = "# Test heading\n\n- test item 1\n- test item 2" def from_html_file(): print publisher.md_to_html(publisher.from_file(test_md_filename)) def md_to_html(): print publisher.md_to_html(test_source) def md_and_css_to_html(): html_source = publisher.md_and_css_to_html(publisher.from_file(test_md_filename), publisher.from_file(test_css_filename)) print html_source publisher.to_file(html_source, test_html_filename) def from_md_file_to_pdf_file(): test_html = publisher.md_to_html(publisher.from_file("README.md")) print publisher.html_to_pdf_file(test_html, test_pdf_filename, [test_css_filename]) md_and_css_to_html()
import publisher test_pdf_filename = "test/test.pdf" test_css_filename = "test/test.css" test_md_filename = "test/test.md" test_html_filename = "test/test.html" test_sender = "cpg@yakko.cs.wmich.edu" test_recipient = "cpgillem@gmail.com" test_md = "# Test heading\n\n- test item 1\n- test item 2" def from_html_file(): print publisher.md_to_html(publisher.from_file(test_md_filename)) def md_to_html(): print publisher.md_to_html(test_source) def md_and_css_to_html(): html_source = publisher.md_and_css_to_html(publisher.from_file(test_md_filename), publisher.from_file(test_css_filename)) print html_source publisher.to_file(html_source, test_html_filename) def from_md_file_to_pdf_file(): test_html = publisher.md_to_html(publisher.from_file("README.md")) print publisher.html_to_pdf_file(test_html, test_pdf_filename, [test_css_filename]) def from_md_to_html_email(): test_email = publisher.md_to_html_email(publisher.from_file(test_md_filename), publisher.from_file(test_css_filename)) print test_email # The test case currently in use from_md_to_html_email()
Add test case for HTML email messages.
Add test case for HTML email messages.
Python
mit
cpgillem/markdown_publisher,cpgillem/markdown_publisher
--- +++ @@ -4,6 +4,8 @@ test_css_filename = "test/test.css" test_md_filename = "test/test.md" test_html_filename = "test/test.html" +test_sender = "cpg@yakko.cs.wmich.edu" +test_recipient = "cpgillem@gmail.com" test_md = "# Test heading\n\n- test item 1\n- test item 2" @@ -23,4 +25,10 @@ test_html = publisher.md_to_html(publisher.from_file("README.md")) print publisher.html_to_pdf_file(test_html, test_pdf_filename, [test_css_filename]) -md_and_css_to_html() +def from_md_to_html_email(): + test_email = publisher.md_to_html_email(publisher.from_file(test_md_filename), + publisher.from_file(test_css_filename)) + print test_email + +# The test case currently in use +from_md_to_html_email()
348c28bacececb787ab73c9716dc515d0fabbe4b
armstrong/hatband/widgets/visualsearch.py
armstrong/hatband/widgets/visualsearch.py
from django.forms import Widget from django.template.loader import render_to_string from ..utils import static_url class GenericKeyWidget(Widget): template = "admin/hatband/widgets/generickey.html" class Media: js = (static_url("visualsearch/dependencies.js"), static_url("visualsearch/visualsearch.js"), static_url("generickey.js"), ) css = { "all": (static_url("visualsearch/visualsearch.css"), static_url("hatband/css/generickey.css"), ) } def __init__(self, object_id_name="object_id", content_type_name="content_type", *args, **kwargs): super(GenericKeyWidget, self).__init__(*args, **kwargs) self.object_id_name = object_id_name self.content_type_name = content_type_name def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) final_attrs["value"] = value final_attrs["is_templated"] = final_attrs["id"].find("__prefix__") > -1 final_attrs["object_id_name"] = self.object_id_name final_attrs["content_type_name"] = self.content_type_name return render_to_string(self.template, final_attrs)
from django.forms import Widget from django.template.loader import render_to_string from ..utils import static_url class GenericKeyWidget(Widget): template = "admin/hatband/widgets/generickey.html" class Media: js = (static_url("visualsearch/dependencies.js"), static_url("visualsearch/visualsearch.js"), static_url("generickey.js"), ) css = { "all": (static_url("visualsearch/visualsearch.css"), static_url("hatband/css/generickey.css"), ) } def __init__(self, object_id_name="object_id", content_type_name="content_type", *args, **kwargs): super(GenericKeyWidget, self).__init__(*args, **kwargs) self.object_id_name = object_id_name self.content_type_name = content_type_name def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) final_attrs.update({ "value": value, "is_templated": final_attrs["id"].find("__prefix__") > -1, "object_id_name": self.object_id_name, "content_type_name": self.content_type_name, }) return render_to_string(self.template, final_attrs)
Clean up this code a bit (no functional change)
Clean up this code a bit (no functional change)
Python
apache-2.0
armstrong/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband
--- +++ @@ -30,8 +30,10 @@ if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) - final_attrs["value"] = value - final_attrs["is_templated"] = final_attrs["id"].find("__prefix__") > -1 - final_attrs["object_id_name"] = self.object_id_name - final_attrs["content_type_name"] = self.content_type_name + final_attrs.update({ + "value": value, + "is_templated": final_attrs["id"].find("__prefix__") > -1, + "object_id_name": self.object_id_name, + "content_type_name": self.content_type_name, + }) return render_to_string(self.template, final_attrs)
6b5c32960565775d8b94825087c503e58f5eed27
openslides/users/migrations/0003_group.py
openslides/users/migrations/0003_group.py
# Generated by Django 1.10.5 on 2017-01-11 21:45 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models import openslides.users.models import openslides.utils.models class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('users', '0002_user_misc_default_groups'), ] operations = [ migrations.CreateModel( name='Group', fields=[( 'group_ptr', models.OneToOneField( auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group'))], options={ 'default_permissions': (), }, bases=(openslides.utils.models.RESTModelMixin, 'auth.group'), managers=[ ('objects', openslides.users.models.GroupManager()), ], ), ]
# Generated by Django 1.10.5 on 2017-01-11 21:45 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models import openslides.users.models import openslides.utils.models def create_openslides_groups(apps, schema_editor): """ Creates the users.models.Group objects for each existing django.contrib.auth.models.Group object. """ # We get the model from the versioned app registry; # if we directly import it, it will be the wrong version. DjangoGroup = apps.get_model('auth', 'Group') Group = apps.get_model('users', 'Group') for group in DjangoGroup.objects.all(): Group.objects.create(group_ptr_id=group.pk, name=group.name) class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('users', '0002_user_misc_default_groups'), ] operations = [ migrations.CreateModel( name='Group', fields=[( 'group_ptr', models.OneToOneField( auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group'))], options={ 'default_permissions': (), }, bases=(openslides.utils.models.RESTModelMixin, 'auth.group'), managers=[ ('objects', openslides.users.models.GroupManager()), ], ), migrations.RunPython( create_openslides_groups, ), ]
Fix the migration of the groups.
Fix the migration of the groups. Fixes #2915
Python
mit
tsiegleauq/OpenSlides,normanjaeckel/OpenSlides,normanjaeckel/OpenSlides,ostcar/OpenSlides,emanuelschuetze/OpenSlides,boehlke/OpenSlides,ostcar/OpenSlides,tsiegleauq/OpenSlides,CatoTH/OpenSlides,emanuelschuetze/OpenSlides,FinnStutzenstein/OpenSlides,OpenSlides/OpenSlides,normanjaeckel/OpenSlides,boehlke/OpenSlides,jwinzer/OpenSlides,FinnStutzenstein/OpenSlides,CatoTH/OpenSlides,tsiegleauq/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,boehlke/OpenSlides,jwinzer/OpenSlides,jwinzer/OpenSlides,emanuelschuetze/OpenSlides,normanjaeckel/OpenSlides,OpenSlides/OpenSlides,CatoTH/OpenSlides,FinnStutzenstein/OpenSlides,FinnStutzenstein/OpenSlides,boehlke/OpenSlides,ostcar/OpenSlides,jwinzer/OpenSlides,emanuelschuetze/OpenSlides
--- +++ @@ -6,6 +6,19 @@ import openslides.users.models import openslides.utils.models + + +def create_openslides_groups(apps, schema_editor): + """ + Creates the users.models.Group objects for each existing + django.contrib.auth.models.Group object. + """ + # We get the model from the versioned app registry; + # if we directly import it, it will be the wrong version. + DjangoGroup = apps.get_model('auth', 'Group') + Group = apps.get_model('users', 'Group') + for group in DjangoGroup.objects.all(): + Group.objects.create(group_ptr_id=group.pk, name=group.name) class Migration(migrations.Migration): @@ -35,4 +48,7 @@ ('objects', openslides.users.models.GroupManager()), ], ), + migrations.RunPython( + create_openslides_groups, + ), ]
8d7f3320a9d3fd3b7365cad7631835a0a46f374e
planner/signals.py
planner/signals.py
from django.db.models.signals import m2m_changed from django.dispatch import receiver from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from .models import Step @receiver(m2m_changed, sender=Step.passengers.through) def check_passengers(sender, **kwargs): step = kwargs['instance'] if step.passengers.count() >= 8: raise ValidationError(_("You exceeded passenger maximum number"))
from django.db.models.signals import m2m_changed from django.dispatch import receiver from .models import Step @receiver(m2m_changed, sender=Step.passengers.through) def check_passengers(sender, **kwargs): step = kwargs['instance'] if kwargs['action'] == 'post_add': if step.passengers.count() >= step.trip.max_num_passengers: step.trip.is_joinable = False elif kwargs['action'] == 'post_remove': step.trip.is_joinable = True
Make is_joinable automatic based of passenger number
Make is_joinable automatic based of passenger number
Python
mit
livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride
--- +++ @@ -1,12 +1,13 @@ from django.db.models.signals import m2m_changed from django.dispatch import receiver -from django.core.exceptions import ValidationError -from django.utils.translation import ugettext_lazy as _ from .models import Step @receiver(m2m_changed, sender=Step.passengers.through) def check_passengers(sender, **kwargs): step = kwargs['instance'] - if step.passengers.count() >= 8: - raise ValidationError(_("You exceeded passenger maximum number")) + if kwargs['action'] == 'post_add': + if step.passengers.count() >= step.trip.max_num_passengers: + step.trip.is_joinable = False + elif kwargs['action'] == 'post_remove': + step.trip.is_joinable = True
2247162e277f8d09cc951442673d71cd0a8ece65
active_link/templatetags/active_link_tags.py
active_link/templatetags/active_link_tags.py
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = request.path.find(path) == 0 if active: return css_class return ''
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None, *args, **kwargs): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname, args=args, kwargs=kwargs) if strict: active = request.path == path else: active = request.path.find(path) == 0 if active: return css_class return ''
Add ability to reverse views with args and kwargs
Add ability to reverse views with args and kwargs
Python
bsd-3-clause
valerymelou/django-active-link
--- +++ @@ -10,7 +10,7 @@ @register.simple_tag(takes_context=True) -def active_link(context, viewname, css_class=None, strict=None): +def active_link(context, viewname, css_class=None, strict=None, *args, **kwargs): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. @@ -29,7 +29,7 @@ if request is None: # Can't work without the request object. return '' - path = reverse(viewname) + path = reverse(viewname, args=args, kwargs=kwargs) if strict: active = request.path == path else:
ba00bececdcca3d1f224128123f12a9f634798b8
feedhq/feeds/management/commands/updatefeeds.py
feedhq/feeds/management/commands/updatefeeds.py
import logging from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection from raven import Client from ....tasks import enqueue from ...models import UniqueFeed, Feed from ...tasks import update_feed from ...utils import FeedUpdater logger = logging.getLogger('feedupdater') class Command(BaseCommand): """Updates the users' feeds""" def handle(self, *args, **kwargs): if args: pk = args[0] feed = Feed.objects.get(pk=pk) feed.etag = '' return FeedUpdater(feed.url).update(use_etags=False) # Making a list of unique URLs. Makes one call whatever the number of # subscribers is. urls = Feed.objects.filter(muted=False).values_list('url', flat=True) unique_urls = {} map(unique_urls.__setitem__, urls, []) for url in unique_urls: try: try: unique = UniqueFeed.objects.get(url=url) if unique.should_update(): enqueue(update_feed, url) except UniqueFeed.DoesNotExist: enqueue(update_feed, url) except Exception: # We don't know what to expect, and anyway # we're reporting the exception if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'): raise else: client = Client(dsn=settings.SENTRY_DSN) client.captureException() connection.close()
import logging from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection from raven import Client from ....tasks import enqueue from ...models import UniqueFeed, Feed from ...tasks import update_feed from ...utils import FeedUpdater logger = logging.getLogger('feedupdater') class Command(BaseCommand): """Updates the users' feeds""" def handle(self, *args, **kwargs): if args: pk = args[0] feed = Feed.objects.get(pk=pk) feed.etag = '' return FeedUpdater(feed.url).update(use_etags=False) # Making a list of unique URLs. Makes one call whatever the number of # subscribers is. urls = Feed.objects.filter(muted=False).values_list('url', flat=True) unique_urls = {} map(unique_urls.__setitem__, urls, []) for url in unique_urls: try: try: unique = UniqueFeed.objects.get(url=url) if unique.should_update(): enqueue(update_feed, url, timeout=20) except UniqueFeed.DoesNotExist: enqueue(update_feed, url, timeout=20) except Exception: # We don't know what to expect, and anyway # we're reporting the exception if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'): raise else: client = Client(dsn=settings.SENTRY_DSN) client.captureException() connection.close()
Set RQ timeout when enqueuing
Set RQ timeout when enqueuing
Python
bsd-3-clause
vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq,feedhq/feedhq,rmoorman/feedhq,rmoorman/feedhq,feedhq/feedhq,vincentbernat/feedhq,rmoorman/feedhq,rmoorman/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,rmoorman/feedhq
--- +++ @@ -34,9 +34,9 @@ try: unique = UniqueFeed.objects.get(url=url) if unique.should_update(): - enqueue(update_feed, url) + enqueue(update_feed, url, timeout=20) except UniqueFeed.DoesNotExist: - enqueue(update_feed, url) + enqueue(update_feed, url, timeout=20) except Exception: # We don't know what to expect, and anyway # we're reporting the exception if settings.DEBUG or not hasattr(settings, 'SENTRY_DSN'):
1bad824786204353ff4f5b955ae687f088f80837
employees/tests.py
employees/tests.py
from django.test import TestCase # Create your tests here.
from .models import Employee from .serializers import EmployeeSerializer, EmployeeAvatarSerializer, EmployeeListSerializer from categories.serializers import CategorySerializer from django.core.urlresolvers import reverse from django.core.paginator import Paginator from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.pagination import PageNumberPagination from rest_framework.test import APITestCase, APIClient class EmployeeTestCase(APITestCase): def setUp(self): Employee.objects.create_superuser('user', 'user@email.com', 'userpassword') def test_employee_creation(self): # token = Token.objects.get(user__username='user') # user = APIClient() # user.credentials(HTTP_AUTHORIZATION='Token ' + token.key) # employee1 = Employee.objects.get(username='user') # print user.username # #user.login(username=employee1.username, password=employee1.password) employee1 = Employee.objects.get(email='user@email.com') self.assertEqual(employee1.username, 'user') def test_employee_list(self): employees = Employee.objects.all() paginator = Paginator(employees, 20) print paginator.page(1) print paginator.page(1).object_list serializer = EmployeeListSerializer(employees, many=True) url = reverse('employees:employee_list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
Add draft testcases for employees views
Add draft testcases for employees views
Python
apache-2.0
belatrix/BackendAllStars
--- +++ @@ -1,3 +1,34 @@ -from django.test import TestCase +from .models import Employee +from .serializers import EmployeeSerializer, EmployeeAvatarSerializer, EmployeeListSerializer +from categories.serializers import CategorySerializer +from django.core.urlresolvers import reverse +from django.core.paginator import Paginator +from rest_framework import status +from rest_framework.authtoken.models import Token +from rest_framework.pagination import PageNumberPagination +from rest_framework.test import APITestCase, APIClient -# Create your tests here. + +class EmployeeTestCase(APITestCase): + def setUp(self): + Employee.objects.create_superuser('user', 'user@email.com', 'userpassword') + + def test_employee_creation(self): + # token = Token.objects.get(user__username='user') + # user = APIClient() + # user.credentials(HTTP_AUTHORIZATION='Token ' + token.key) + # employee1 = Employee.objects.get(username='user') + # print user.username + # #user.login(username=employee1.username, password=employee1.password) + employee1 = Employee.objects.get(email='user@email.com') + self.assertEqual(employee1.username, 'user') + + def test_employee_list(self): + employees = Employee.objects.all() + paginator = Paginator(employees, 20) + print paginator.page(1) + print paginator.page(1).object_list + serializer = EmployeeListSerializer(employees, many=True) + url = reverse('employees:employee_list') + response = self.client.get(url, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK)
eac90ef4d470923bb823f99dc85984faac733f08
pysuru/services.py
pysuru/services.py
# coding: utf-8 import json from collections import namedtuple from pysuru.base import BaseAPI, ObjectMixin SERVICE_INSTANCE_ATTRS = ( 'name', 'description', 'type', 'plan', 'teamOwner', ) _ServiceInstance = namedtuple('ServiceInstance', SERVICE_INSTANCE_ATTRS) class ServiceInstance(_ServiceInstance, ObjectMixin): pass class ServiceInstanceAPI(BaseAPI): def filter_by_app(self, name): http_response = self.request('GET', '/services/instances?app=' + name) response = json.loads(http_response.data.decode('utf-8')) services = [] for service_data in response: for index, instance in enumerate(service_data['instances']): data = { 'name': instance, 'type': service_data['service'], 'plan': service_data['plans'][index], } services.append(ServiceInstance.create(**data)) return services def add(self, data): http_response = self.post_json('/services/instances', data) response = json.loads(http_response.data.decode('utf-8')) if response.status == 409: raise ServiceAlreadyExists() elif response.status == 200: return True else: return False class ServiceAlreadyExists(Exception): pass
# coding: utf-8 import json from collections import namedtuple from pysuru.base import BaseAPI, ObjectMixin SERVICE_INSTANCE_ATTRS = ( 'name', 'description', 'type', 'plan', ) _ServiceInstance = namedtuple('ServiceInstance', SERVICE_INSTANCE_ATTRS) class ServiceInstance(_ServiceInstance, ObjectMixin): pass class ServiceInstanceAPI(BaseAPI): def filter_by_app(self, name): http_response = self.request('GET', '/services/instances?app=' + name) response = json.loads(http_response.data.decode('utf-8')) services = [] for service_data in response: for index, instance in enumerate(service_data['instances']): data = { 'name': instance, 'type': service_data['service'], 'plan': service_data['plans'][index], } services.append(ServiceInstance.create(**data)) return services def add(self, data): http_response = self.post_json('/services/instances', data) response = json.loads(http_response.data.decode('utf-8')) if response.status == 409: raise ServiceAlreadyExists() elif response.status == 200: return True else: return False class ServiceAlreadyExists(Exception): pass
Remove (currently) unused service instance field
Remove (currently) unused service instance field
Python
mit
rcmachado/pysuru
--- +++ @@ -10,7 +10,6 @@ 'description', 'type', 'plan', - 'teamOwner', )
1a320cadb37de27964f5973e2860804df3a5e479
agir/authentication/tasks.py
agir/authentication/tasks.py
from celery import shared_task from django.conf import settings from django.utils import timezone from agir.people.actions.mailing import send_mosaico_email def interleave_spaces(s, n=3): return ' '.join([s[i:i+n] for i in range(0, len(s), n)]) @shared_task def send_login_email(email, short_code, expiry_time): utc_expiry_time = timezone.make_aware(timezone.datetime.fromtimestamp(expiry_time), timezone.utc) local_expiry_time = timezone.localtime(utc_expiry_time) send_mosaico_email( code='LOGIN_MESSAGE', subject="Connexion à agir.lafranceinsoumise.fr", from_email=settings.EMAIL_FROM, bindings={ 'CODE': interleave_spaces(short_code), 'EXPIRY_TIME': local_expiry_time.strftime("%H:%M") }, recipients=[email] )
from celery import shared_task from django.conf import settings from django.utils import timezone from agir.people.actions.mailing import send_mosaico_email def interleave_spaces(s, n=3): return ' '.join([s[i:i+n] for i in range(0, len(s), n)]) @shared_task def send_login_email(email, short_code, expiry_time): utc_expiry_time = timezone.make_aware(timezone.datetime.utcfromtimestamp(expiry_time), timezone.utc) local_expiry_time = timezone.localtime(utc_expiry_time) send_mosaico_email( code='LOGIN_MESSAGE', subject="Connexion à agir.lafranceinsoumise.fr", from_email=settings.EMAIL_FROM, bindings={ 'CODE': interleave_spaces(short_code), 'EXPIRY_TIME': local_expiry_time.strftime("%H:%M") }, recipients=[email] )
Send correct expiration timing in login email
Send correct expiration timing in login email
Python
agpl-3.0
lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django
--- +++ @@ -11,7 +11,7 @@ @shared_task def send_login_email(email, short_code, expiry_time): - utc_expiry_time = timezone.make_aware(timezone.datetime.fromtimestamp(expiry_time), timezone.utc) + utc_expiry_time = timezone.make_aware(timezone.datetime.utcfromtimestamp(expiry_time), timezone.utc) local_expiry_time = timezone.localtime(utc_expiry_time) send_mosaico_email(
487897e4b515a4c514fa0c91dec80d981c3bb98b
tools/telemetry/telemetry/core/profile_types.py
tools/telemetry/telemetry/core/profile_types.py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os PROFILE_TYPE_MAPPING = { 'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1', 'power_user': 'chrome/test/data/extensions/profiles/content_scripts10', } PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys() def GetProfileDir(profile_type): path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/'))) assert os.path.exists(path) return path
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os PROFILE_TYPE_MAPPING = { 'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1', 'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest', } PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys() def GetProfileDir(profile_type): path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', *PROFILE_TYPE_MAPPING[profile_type].split('/'))) assert os.path.exists(path) return path
Use correct profile for power_user.
[Telemetry] Use correct profile for power_user. TEST=None BUG=None NOTRY=True Review URL: https://chromiumcodereview.appspot.com/12775015 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@188294 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,Chilledheart/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,jaruba/chromium.src,dednal/chromium.src,ltilve/chromium,ondra-novak/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,ltilve/chromium,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,Just-D/chromium-1,dednal/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,jaruba/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,Jonekee/chromium.src,ltilve/chromium,dednal/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,ltilve/chromium,ltilve/chromium,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,littlstar/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,ondra-novak/chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,jaruba/chromium.src,anirudhSK/chromium,ondra-novak/chromium.src,patrickm/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,anirudhSK/chromium,littlstar/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src
--- +++ @@ -6,7 +6,7 @@ PROFILE_TYPE_MAPPING = { 'typical_user': 'chrome/test/data/extensions/profiles/content_scripts1', - 'power_user': 'chrome/test/data/extensions/profiles/content_scripts10', + 'power_user': 'chrome/test/data/extensions/profiles/extension_webrequest', } PROFILE_TYPES = PROFILE_TYPE_MAPPING.keys()
761e74feac34c198da75f17b6145b6ca37d7afed
tests/__init__.py
tests/__init__.py
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, **kwargs): sleep = kwargs.pop('sleep', DEFAULT_SLEEP) expected_return = kwargs.pop('expected_return', None) call = kwargs.pop('call', True) def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) else: raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
import threading import time DEFAULT_SLEEP = 0.01 class CustomError(Exception): pass def defer(callback, *args, **kwargs): sleep = kwargs.pop('sleep', DEFAULT_SLEEP) expected_return = kwargs.pop('expected_return', None) call = kwargs.pop('call', True) def func(): time.sleep(sleep) if call: assert expected_return == callback(*args, **kwargs) else: print("generator is not re-called") t = threading.Thread(target=func) t.start() def wait_until_finished(wrapper, timeout=1, sleep=DEFAULT_SLEEP): start_time = time.time() while time.time() < start_time + timeout: # Relies on .has_terminated, but shouldn't be a problem if wrapper.has_terminated(): return time.sleep(sleep) raise RuntimeError("Has not been collected within %ss" % timeout) class State(object): """Helper class to keep track of a test's state.""" def __init__(self): self.reset() def inc(self): self.counter += 1 def reset(self): self.counter = 0 self.run = False
Fix test case being unable to fail
Fix test case being unable to fail
Python
mit
FichteFoll/resumeback
--- +++ @@ -33,8 +33,8 @@ if wrapper.has_terminated(): return time.sleep(sleep) - else: - raise RuntimeError("Has not been collected within %ss" % timeout) + + raise RuntimeError("Has not been collected within %ss" % timeout) class State(object):
4a549a5d7509fa23fc6787662b4950291baa3407
tests/conftest.py
tests/conftest.py
import tempfile import pytest from coaction import create_app from coaction.extensions import db as _db dbfile = tempfile.NamedTemporaryFile(delete=False) dbfile.close() TEST_DATABASE_FILE = dbfile.name TEST_DATABASE_URI = "sqlite:///" + TEST_DATABASE_FILE TESTING = True DEBUG = False DEBUG_TB_ENABLED = False DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = TEST_DATABASE_URI WTF_CSRF_ENABLED = False @pytest.fixture def app(): app = create_app() app.config.from_object(__name__) return app @pytest.fixture def db(app, request): def teardown(): _db.drop_all() _db.app = app _db.create_all() request.addfinalizer(teardown) _db.app = app return _db
import tempfile import pytest from toolshed import create_app from toolshed.extensions import db as _db dbfile = tempfile.NamedTemporaryFile(delete=False) dbfile.close() TEST_DATABASE_FILE = dbfile.name TEST_DATABASE_URI = "postgres://localhost/" + TEST_DATABASE_FILE TESTING = True DEBUG = False DEBUG_TB_ENABLED = False DEBUG_TB_INTERCEPT_REDIRECTS = False SQLALCHEMY_DATABASE_URI = TEST_DATABASE_URI WTF_CSRF_ENABLED = False @pytest.fixture def app(): app = create_app() app.config.from_object(__name__) return app @pytest.fixture def db(app, request): def teardown(): _db.drop_all() _db.app = app _db.create_all() request.addfinalizer(teardown) _db.app = app return _db
Correct imports, switch to postgresql
Correct imports, switch to postgresql
Python
mit
PythonClutch/python-clutch,PythonClutch/python-clutch,PythonClutch/python-clutch
--- +++ @@ -2,15 +2,15 @@ import pytest -from coaction import create_app -from coaction.extensions import db as _db +from toolshed import create_app +from toolshed.extensions import db as _db dbfile = tempfile.NamedTemporaryFile(delete=False) dbfile.close() TEST_DATABASE_FILE = dbfile.name -TEST_DATABASE_URI = "sqlite:///" + TEST_DATABASE_FILE +TEST_DATABASE_URI = "postgres://localhost/" + TEST_DATABASE_FILE TESTING = True DEBUG = False DEBUG_TB_ENABLED = False
d14a34bff8e0462ebc2b8da9bc021f9c6f8f432d
libclang_samples/kernel-sigs.py
libclang_samples/kernel-sigs.py
import pprint import sys import clang.cindex from clang.cindex import CursorKind def handle_function_decl(fdecl_cursor): children = list(fdecl_cursor.get_children()) # Only interested in functions that have a CUDAGLOBAL_ATTR attached. if not any(c.kind == CursorKind.CUDAGLOBAL_ATTR for c in children): return print fdecl_cursor.displayname # Look at param decls for c in children: if c.kind == CursorKind.PARM_DECL: print '>>', c.spelling, c.type.spelling def visitor(cursor): if cursor.kind == CursorKind.FUNCTION_DECL: handle_function_decl(cursor) for child in cursor.get_children(): visitor(child) index = clang.cindex.Index.create() # Parse as CUDA tu = index.parse(sys.argv[1], args=['-x', 'cuda']) diagnostics = list(tu.diagnostics) if len(diagnostics) > 0: print 'There were parse errors' pprint.pprint(diagnostics) else: visitor(tu.cursor)
import pprint import sys import clang.cindex from clang.cindex import CursorKind def handle_function_decl(fdecl_cursor): children = list(fdecl_cursor.get_children()) # Only interested in functions that have a CUDAGLOBAL_ATTR attached. if not any(c.kind == CursorKind.CUDAGLOBAL_ATTR for c in children): return print fdecl_cursor.displayname # Look at param decls for c in children: if c.kind == CursorKind.PARM_DECL: print '>>', c.spelling, c.type.spelling index = clang.cindex.Index.create() # Parse as CUDA tu = index.parse(sys.argv[1], args=['-x', 'cuda']) diagnostics = list(tu.diagnostics) if len(diagnostics) > 0: print 'There were parse errors' pprint.pprint(diagnostics) else: for c in tu.cursor.walk_preorder(): if c.kind == CursorKind.FUNCTION_DECL: handle_function_decl(c)
Use walk_preorder instead of manual visiting
Use walk_preorder instead of manual visiting
Python
unlicense
eliben/llvm-clang-samples,eliben/llvm-clang-samples,eliben/llvm-clang-samples,eliben/llvm-clang-samples,eliben/llvm-clang-samples,eliben/llvm-clang-samples
--- +++ @@ -19,13 +19,6 @@ print '>>', c.spelling, c.type.spelling -def visitor(cursor): - if cursor.kind == CursorKind.FUNCTION_DECL: - handle_function_decl(cursor) - - for child in cursor.get_children(): - visitor(child) - index = clang.cindex.Index.create() # Parse as CUDA tu = index.parse(sys.argv[1], args=['-x', 'cuda']) @@ -35,4 +28,6 @@ print 'There were parse errors' pprint.pprint(diagnostics) else: - visitor(tu.cursor) + for c in tu.cursor.walk_preorder(): + if c.kind == CursorKind.FUNCTION_DECL: + handle_function_decl(c)
dda9904a756e309047bebcbfecd2120383a257cc
django_countries/settings.py
django_countries/settings.py
from django.conf import settings def _build_flag_url(): if hasattr(settings, 'COUNTRIES_FLAG_URL'): url = settings.COUNTRIES_FLAG_URL else: url = 'flags/%(code)s.gif' prefix = getattr(settings, 'STATIC_URL', '') or settings.MEDIA_URL if not prefix.endswith('/'): prefix = '%s/' % prefix return '%s%s' % (prefix, url) FLAG_URL = _build_flag_url()
from django.conf import settings def _build_flag_url(): if hasattr(settings, 'COUNTRIES_FLAG_URL'): url = settings.COUNTRIES_FLAG_URL else: url = 'flags/%(code)s.gif' prefix = getattr(settings, 'STATIC_URL', '') or \ getattr(settings, 'STATICFILES_URL', '') or \ settings.MEDIA_URL if not prefix.endswith('/'): prefix = '%s/' % prefix return '%s%s' % (prefix, url) FLAG_URL = _build_flag_url()
Add django 1.3 staticfiles compatibility
Add django 1.3 staticfiles compatibility
Python
mit
degenhard/django-countries
--- +++ @@ -6,7 +6,11 @@ url = settings.COUNTRIES_FLAG_URL else: url = 'flags/%(code)s.gif' - prefix = getattr(settings, 'STATIC_URL', '') or settings.MEDIA_URL + + prefix = getattr(settings, 'STATIC_URL', '') or \ + getattr(settings, 'STATICFILES_URL', '') or \ + settings.MEDIA_URL + if not prefix.endswith('/'): prefix = '%s/' % prefix return '%s%s' % (prefix, url)
4b65ab0fbc5839be9a49dd235549a13996a56108
tests/tabular_output/test_tabulate_adapter.py
tests/tabular_output/test_tabulate_adapter.py
# -*- coding: utf-8 -*- """Test the tabulate output adapter.""" from __future__ import unicode_literals from textwrap import dedent from cli_helpers.tabular_output import tabulate_adapter def test_tabulate_wrapper(): """Test the *output_formatter.tabulate_wrapper()* function.""" data = [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output = tabulate_adapter.adapter(data, headers, table_format='psql') assert output == dedent('''\ +-----------+----------+ | letters | number | |-----------+----------| | abc | 1 | | d | 456 | +-----------+----------+''')
# -*- coding: utf-8 -*- """Test the tabulate output adapter.""" from __future__ import unicode_literals from textwrap import dedent from cli_helpers.tabular_output import tabulate_adapter def test_tabulate_wrapper(): """Test the *output_formatter.tabulate_wrapper()* function.""" data = [['abc', 1], ['d', 456]] headers = ['letters', 'number'] output = tabulate_adapter.adapter(data, headers, table_format='psql') assert output == dedent('''\ +-----------+----------+ | letters | number | |-----------+----------| | abc | 1 | | d | 456 | +-----------+----------+''')
Fix tabulate adapter test with numparse on.
Fix tabulate adapter test with numparse on.
Python
bsd-3-clause
dbcli/cli_helpers,dbcli/cli_helpers
--- +++ @@ -14,8 +14,8 @@ output = tabulate_adapter.adapter(data, headers, table_format='psql') assert output == dedent('''\ +-----------+----------+ - | letters | number | + | letters | number | |-----------+----------| - | abc | 1 | - | d | 456 | + | abc | 1 | + | d | 456 | +-----------+----------+''')
d67099ce7d30e31b98251f7386b33caaa5199a01
censusreporter/config/prod/wsgi.py
censusreporter/config/prod/wsgi.py
import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
import os from django.core.wsgi import get_wsgi_application import newrelic.agent newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
Correct location of newrelic config
Correct location of newrelic config
Python
mit
sseguku/simplecensusug,Code4SA/censusreporter,Code4SA/censusreporter,Code4SA/censusreporter,sseguku/simplecensusug,4bic/censusreporter,sseguku/simplecensusug,4bic/censusreporter,Code4SA/censusreporter,4bic/censusreporter
--- +++ @@ -2,7 +2,7 @@ from django.core.wsgi import get_wsgi_application import newrelic.agent -newrelic.agent.initialize('/var/www-data/censusreporter/conf/newrelic.ini') +newrelic.agent.initialize(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../../conf/newrelic.ini')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.prod.settings") application = get_wsgi_application()
f69e6555387d4cb6828baaac3ce1a17217577b48
faddsdata/format_definitions/__init__.py
faddsdata/format_definitions/__init__.py
from apt import APT_RECORDS, ATT_RECORDS, RWY_RECORDS, RMK_RECORDS, APT_RECORD_MAP from arb import ARB_RECORDS from awos import AWOS_RECORDS
from apt import APT_RECORDS, ATT_RECORDS, RWY_RECORDS, RMK_RECORDS, APT_RECORD_MAP from awos import AWOS_RECORDS
Remove import for lib not commited yet.
Remove import for lib not commited yet.
Python
bsd-3-clause
adamfast/faddsdata
--- +++ @@ -1,3 +1,2 @@ from apt import APT_RECORDS, ATT_RECORDS, RWY_RECORDS, RMK_RECORDS, APT_RECORD_MAP -from arb import ARB_RECORDS from awos import AWOS_RECORDS
76177710323f1ccb408fd006ef7b87ff36743f8c
telostats/settings/heroku.py
telostats/settings/heroku.py
from __future__ import absolute_import import dj_database_url import urlparse from os import environ from .base import * ENV = 'HEROKU' # Store files on S3 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' redis_url = urlparse.urlparse(environ.get('REDISTOGO_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, 'DB': 1, }, }, } # Grab database info DATABASES = { 'default': dj_database_url.config() } # Setup sentry / raven SENTRY_DSN = environ.get('SENTRY_DSN') INSTALLED_APPS += ( 'raven.contrib.django', )
from __future__ import absolute_import import dj_database_url import urlparse from os import environ from .base import * ENV = 'HEROKU' # Store files on S3 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' redis_url = urlparse.urlparse(environ.get('REDISTOGO_URL')) CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, 'DB': 0, }, }, } # Grab database info DATABASES = { 'default': dj_database_url.config() } # Setup sentry / raven SENTRY_DSN = environ.get('SENTRY_DSN') INSTALLED_APPS += ( 'raven.contrib.django', )
Fix wrong Redis DB setting
Fix wrong Redis DB setting
Python
bsd-3-clause
idan/telostats,idan/telostats,idan/telostats
--- +++ @@ -18,7 +18,7 @@ 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'PASSWORD': redis_url.password, - 'DB': 1, + 'DB': 0, }, }, }
5550217c028c422e7dc2d54c3b8b61ea43cfc26f
dosagelib/__pyinstaller/hook-dosagelib.py
dosagelib/__pyinstaller/hook-dosagelib.py
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2020 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage')
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
Make sure data files are included
PyInstaller: Make sure data files are included
Python
mit
webcomics/dosage,webcomics/dosage
--- +++ @@ -1,6 +1,6 @@ # SPDX-License-Identifier: MIT -# Copyright (C) 2016-2020 Tobias Gruetzmacher -from PyInstaller.utils.hooks import collect_submodules, copy_metadata +# Copyright (C) 2016-2022 Tobias Gruetzmacher +from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') -datas = copy_metadata('dosage') +datas = copy_metadata('dosage') + collect_data_files('dosagelib')
76af6248c479127f1a212c331a2278f69484bcbc
project/api/management/commands/rebuild_data.py
project/api/management/commands/rebuild_data.py
# Django from django.apps import apps from django.core.management.base import BaseCommand from django.utils import timezone import datetime class Command(BaseCommand): help = "Command to rebuild denorms." def add_arguments(self, parser): parser.add_argument( '--days', type=int, dest='days', nargs='?', const=1, help='Number of days to update.', ) parser.add_argument( '--hours', type=int, dest='hours', nargs='?', const=1, help='Number of hours to update.', ) parser.add_argument( '--minutes', type=int, dest='minutes', nargs='?', const=1, help='Number of hours to update.', ) def handle(self, *args, **options): # Set Cursor if options['days']: cursor = timezone.now() - datetime.timedelta(days=options['days'], hours=1) elif options['hours']: cursor = timezone.now() - datetime.timedelta(hours=options['hours'], minutes=5) elif options['minutes']: cursor = timezone.now() - datetime.timedelta(minutes=options['minutes'], seconds=5) else: cursor = None Group = apps.get_model('api.group') Group.objects.denormalize(cursor=cursor) # Group.objects.sort_tree() Group.objects.update_seniors() Award = apps.get_model('api.award') Award.objects.sort_tree() return
# Django from django.apps import apps from django.core.management.base import BaseCommand from django.utils import timezone import datetime class Command(BaseCommand): help = "Command to rebuild denorms." def add_arguments(self, parser): parser.add_argument( '--days', type=int, dest='days', nargs='?', const=1, help='Number of days to update.', ) parser.add_argument( '--hours', type=int, dest='hours', nargs='?', const=1, help='Number of hours to update.', ) parser.add_argument( '--minutes', type=int, dest='minutes', nargs='?', const=1, help='Number of hours to update.', ) def handle(self, *args, **options): # Set Cursor if options['days']: cursor = timezone.now() - datetime.timedelta(days=options['days'], hours=1) elif options['hours']: cursor = timezone.now() - datetime.timedelta(hours=options['hours'], minutes=5) elif options['minutes']: cursor = timezone.now() - datetime.timedelta(minutes=options['minutes'], seconds=5) else: cursor = None Group = apps.get_model('api.group') # Group.objects.denormalize(cursor=cursor) # Group.objects.sort_tree() # Group.objects.update_seniors() Award = apps.get_model('api.award') Award.objects.sort_tree() return
Disable group rebuild until fix indexing
Disable group rebuild until fix indexing
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api
--- +++ @@ -1,4 +1,4 @@ -# Django + # Django from django.apps import apps from django.core.management.base import BaseCommand from django.utils import timezone @@ -46,9 +46,9 @@ else: cursor = None Group = apps.get_model('api.group') - Group.objects.denormalize(cursor=cursor) + # Group.objects.denormalize(cursor=cursor) # Group.objects.sort_tree() - Group.objects.update_seniors() + # Group.objects.update_seniors() Award = apps.get_model('api.award') Award.objects.sort_tree() return
84490442de881788a7f83bc18ec4eedb7f6edb99
tests/bugs/test-200908231005.py
tests/bugs/test-200908231005.py
import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="structure"> <xs:complexType><xs:anyAttribute processContents="lax"/></xs:complexType> </xs:element> </xs:schema>''' #file('schema.xsd', 'w').write(xsd) code = pyxb.binding.generate.GeneratePython(schema_text=xsd) file('code.py', 'w').write(code) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest AttributeNamespace = pyxb.namespace.NamespaceInstance('URN:attr:200908231005') class TestTrac_200908231005 (unittest.TestCase): def testParsing (self): xmls = '<structure xmlns:attr="%s" attr:field="value"/>' % (AttributeNamespace.uri(),) instance = CreateFromDocument(xmls) wam = instance.wildcardAttributeMap() self.assertEqual(1, len(wam)) self.assertEqual('value', wam.get(AttributeNamespace.createExpandedName('field'))) if __name__ == '__main__': unittest.main()
import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="structure"> <xs:complexType><xs:anyAttribute processContents="lax"/></xs:complexType> </xs:element> </xs:schema>''' #file('schema.xsd', 'w').write(xsd) code = pyxb.binding.generate.GeneratePython(schema_text=xsd) #file('code.py', 'w').write(code) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest AttributeNamespace = pyxb.namespace.NamespaceInstance('URN:attr:200908231005') class TestTrac_200908231005 (unittest.TestCase): def testParsing (self): xmls = '<structure xmlns:attr="%s" attr:field="value"/>' % (AttributeNamespace.uri(),) instance = CreateFromDocument(xmls) wam = instance.wildcardAttributeMap() self.assertEqual(1, len(wam)) self.assertEqual('value', wam.get(AttributeNamespace.createExpandedName('field'))) if __name__ == '__main__': unittest.main()
Stop writing generated code unnecessarily
Stop writing generated code unnecessarily
Python
apache-2.0
jonfoster/pyxb-upstream-mirror,pabigot/pyxb,pabigot/pyxb,jonfoster/pyxb2,balanced/PyXB,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,jonfoster/pyxb2,CantemoInternal/pyxb,balanced/PyXB,balanced/PyXB,jonfoster/pyxb2,CantemoInternal/pyxb,jonfoster/pyxb1,CantemoInternal/pyxb
--- +++ @@ -13,7 +13,7 @@ #file('schema.xsd', 'w').write(xsd) code = pyxb.binding.generate.GeneratePython(schema_text=xsd) -file('code.py', 'w').write(code) +#file('code.py', 'w').write(code) rv = compile(code, 'test', 'exec') eval(rv)
ae1a2b73d0c571c49726528f9b8730c9e02ce35f
tests/integration/test_webui.py
tests/integration/test_webui.py
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://nginx' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { 'page': '/login', 'matching_text': 'Please sign in', }, { 'page': '/about', 'matching_text': 'Use the following credentials to login', }, { 'page': '/overview', }, { 'page': '/api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { 'page': '', 'matching_text': 'Diamond', }, { 'page': 'scoreboard', }, { 'page': 'login', 'matching_text': 'Please sign in', }, { 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { 'page': 'overview', }, { 'page': 'api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
Fix webui integration tests to use https
Fix webui integration tests to use https
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
--- +++ @@ -4,29 +4,29 @@ class TestWebUI(object): def get_page(self, page): - return requests.get('http://nginx' + page) + return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { - 'page': '/', + 'page': '', 'matching_text': 'Diamond', }, { - 'page': '/scoreboard', + 'page': 'scoreboard', }, { - 'page': '/login', + 'page': 'login', 'matching_text': 'Please sign in', }, { - 'page': '/about', + 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { - 'page': '/overview', + 'page': 'overview', }, { - 'page': '/api/overview/data' + 'page': 'api/overview/data' } ]
afb8aadcc1dbea109c7882c1a1d65fc328372a74
resources/Dependencies/DecoraterBotCore/Core.py
resources/Dependencies/DecoraterBotCore/Core.py
# coding=utf-8 """ DecoraterBotCore ~~~~~~~~~~~~~~~~~~~ Core to DecoraterBot :copyright: (c) 2015-2018 AraHaan :license: MIT, see LICENSE for more details. """ from DecoraterBotUtils.utils import BaseClient, config __all__ = ['main', 'BotClient'] class BotClient(BaseClient): """ Bot Main client Class. This is where the Events are Registered. """ def __init__(self, **kwargs): super(BotClient, self).__init__(**kwargs) def main(): """ EntryPoint to DecoraterBot. """ BotClient(command_prefix=config.bot_prefix, description=config.description, pm_help=False)
# coding=utf-8 """ DecoraterBotCore ~~~~~~~~~~~~~~~~~~~ Core to DecoraterBot :copyright: (c) 2015-2018 AraHaan :license: MIT, see LICENSE for more details. """ from DecoraterBotUtils.utils import BotClient, config __all__ = ['main'] def main(): """ EntryPoint to DecoraterBot. """ BotClient(command_prefix=config.bot_prefix, description=config.description, pm_help=False)
Update to use new client class name on the DecoraterBotUtils.utils module.
Update to use new client class name on the DecoraterBotUtils.utils module.
Python
mit
DecoraterBot-devs/DecoraterBot
--- +++ @@ -9,19 +9,10 @@ :license: MIT, see LICENSE for more details. """ -from DecoraterBotUtils.utils import BaseClient, config +from DecoraterBotUtils.utils import BotClient, config -__all__ = ['main', 'BotClient'] - - -class BotClient(BaseClient): - """ - Bot Main client Class. - This is where the Events are Registered. - """ - def __init__(self, **kwargs): - super(BotClient, self).__init__(**kwargs) +__all__ = ['main'] def main():
f862823b24bfe59f6fb15fc417aea8ebacdc092d
autoresponse/__init__.py
autoresponse/__init__.py
import twisted.python.failure import twisted.web.error import scrapy.item class Autoresponder(object): # The purpose of Autoresponder is to be initialized during a run # of a test case and used to iterate over scrapy Request objects # until finally there are no more Requests to execute. # # Instead of passing the Requests to the 'net, it handles them # through the configuration you pass it. # # Successful (status=200) Responses can be generated by configuring # url2filename. # # Error responses (status usually 4xx) can be generated by configuring # url2errors. def __init__(self, url2filename, url2errors=None): self.url2filename = url2filename if url2errors is None: url2errors = {} self.url2errors = url2errors @staticmethod def manufacture_http_failure(status_code): error = twisted.web.error.Error(code=status_code) failure = twisted.python.failure.Failure( exc_value=error, exc_type=twisted.web.error.Error) return failure def respond_recursively(self, request_iterable): items = [] work_queue = [] work_queue.extend(request_iterable) while work_queue: thing = work_queue.pop(0) if isinstance(thing, scrapy.item.Item): items.append(thing) continue request = thing if request.url in self.url2filename: raise NotImplemented if request.url in self.url2errors: status_code = self.url2errors[request.url] failure = ( Autoresponder.manufacture_http_failure(status_code)) results = request.errback(failure) if results: if isinstance(results, scrapy.item.Item): results = [results] work_queue.extend(results) return items
Add an implementation that works for testing errbacks
Add an implementation that works for testing errbacks
Python
apache-2.0
paulproteus/autoresponse
--- +++ @@ -0,0 +1,55 @@ +import twisted.python.failure +import twisted.web.error +import scrapy.item + + +class Autoresponder(object): + # The purpose of Autoresponder is to be initialized during a run + # of a test case and used to iterate over scrapy Request objects + # until finally there are no more Requests to execute. + # + # Instead of passing the Requests to the 'net, it handles them + # through the configuration you pass it. + # + # Successful (status=200) Responses can be generated by configuring + # url2filename. + # + # Error responses (status usually 4xx) can be generated by configuring + # url2errors. + def __init__(self, url2filename, url2errors=None): + self.url2filename = url2filename + if url2errors is None: + url2errors = {} + self.url2errors = url2errors + + @staticmethod + def manufacture_http_failure(status_code): + error = twisted.web.error.Error(code=status_code) + failure = twisted.python.failure.Failure( + exc_value=error, exc_type=twisted.web.error.Error) + return failure + + def respond_recursively(self, request_iterable): + items = [] + work_queue = [] + work_queue.extend(request_iterable) + while work_queue: + thing = work_queue.pop(0) + if isinstance(thing, scrapy.item.Item): + items.append(thing) + continue + + request = thing + if request.url in self.url2filename: + raise NotImplemented + + if request.url in self.url2errors: + status_code = self.url2errors[request.url] + failure = ( + Autoresponder.manufacture_http_failure(status_code)) + results = request.errback(failure) + if results: + if isinstance(results, scrapy.item.Item): + results = [results] + work_queue.extend(results) + return items
ca6508bf6e8a1fd2032baaacb81e9131c088c6f8
UCP/news_event/serializers.py
UCP/news_event/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from login.models import UserProfile from discussion.serializers import UserShortSerializer, UserProfileShortSerializer from news_event.models import Event, News class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'title', 'description','posted_at', 'image') class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = ('id', 'title', 'description')
from django.contrib.auth.models import User from rest_framework import serializers from login.models import UserProfile from discussion.serializers import UserShortSerializer, UserProfileShortSerializer from news_event.models import Event, News class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'title', 'description','posted_at', 'image', 'venue') class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = ('id', 'title', 'description')
Add venue to event serializer
Add venue to event serializer
Python
bsd-3-clause
BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP
--- +++ @@ -11,7 +11,7 @@ class Meta: model = Event - fields = ('id', 'title', 'description','posted_at', 'image') + fields = ('id', 'title', 'description','posted_at', 'image', 'venue') class NewsSerializer(serializers.ModelSerializer):
77b943b8bace86d82f76dfa159c5de48d9379dbb
svenv/blog/settings.py
svenv/blog/settings.py
BLOG_TITLE = 'Svenv.nl' BLOG_DESCRIPTION = 'Blogposts about tech related subject like Unix, Linux, Docker and programming.' BASE_URL = 'http://svenv.nl' CONTACT_PAGE_PATH = 'contact' CONTACT_THANK_YOU_PAGE = '/thankyou' EMAIL = 'svenvandescheur@gmail.com' EMAIL_FROM = 'noreply@svenv.nl' SMTP_HOST = 'localhost' REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.OrderingFilter',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 12, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], }
BLOG_TITLE = 'Svenv.nl' BLOG_DESCRIPTION = 'Blogposts about tech related subject like Unix, Linux, Docker and programming.' BASE_URL = 'https://svenv.nl' CONTACT_PAGE_PATH = 'contact' CONTACT_THANK_YOU_PAGE = '/thankyou' EMAIL = 'svenvandescheur@gmail.com' EMAIL_FROM = 'noreply@svenv.nl' SMTP_HOST = 'localhost' REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.OrderingFilter',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 12, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], }
Set base url to https
Set base url to https
Python
mit
svenvandescheur/svenv.nl-app,svenvandescheur/svenv.nl-app,svenvandescheur/svenv.nl-app,svenvandescheur/svenv.nl-app
--- +++ @@ -1,7 +1,7 @@ BLOG_TITLE = 'Svenv.nl' BLOG_DESCRIPTION = 'Blogposts about tech related subject like Unix, Linux, Docker and programming.' -BASE_URL = 'http://svenv.nl' +BASE_URL = 'https://svenv.nl' CONTACT_PAGE_PATH = 'contact' CONTACT_THANK_YOU_PAGE = '/thankyou'
958426d43a5aa8e153e0999417377b54be67f04b
ctypeslib/experimental/byref_at.py
ctypeslib/experimental/byref_at.py
# hack a byref_at function from ctypes import * try: set except NameError: from sets import Set as set def _determine_layout(): result = set() for obj in (c_int(), c_longlong(), c_float(), c_double(), (c_int * 32)()): ref = byref(obj) result.add((c_void_p * 32).from_address(id(ref))[:].index(id(obj)) * sizeof(c_void_p)) if len(result) != 1: raise RuntimeError, "cannot determine byref() object layout" return result.pop() offset = _determine_layout() __all__ = ["byref_at"]
from ctypes import * """ struct tagPyCArgObject { PyObject_HEAD ffi_type *pffi_type; char tag; union { char c; char b; short h; int i; long l; #ifdef HAVE_LONG_LONG PY_LONG_LONG q; #endif double d; float f; void *p; } value; PyObject *obj; int size; /* for the 'V' tag */ }; """ class value(Union): _fields_ = [("c", c_char), ("h", c_short), ("i", c_int), ("l", c_long), ("q", c_longlong), ("d", c_double), ("f", c_float), ("p", c_void_p)] # Thanks to Lenard Lindstrom for this tip: The sizeof(PyObject_HEAD) # is the same as object.__basicsize__. class PyCArgObject(Structure): _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__), ("pffi_type", c_void_p), ("value", value), ("obj", c_void_p), ("size", c_int)] _anonymous_ = ["value"] assert sizeof(PyCArgObject) == type(byref(c_int())).__basicsize__ print "sizeof(PyCArgObject)", sizeof(PyCArgObject) for name in "c h i l q d f p".split(): print name, getattr(PyCArgObject, name)
Define the structure of PyCArgObject in ctypes.
Define the structure of PyCArgObject in ctypes. git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@52772 6015fed2-1504-0410-9fe1-9d1591cc4771
Python
mit
trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib
--- +++ @@ -1,21 +1,51 @@ -# hack a byref_at function - from ctypes import * -try: - set -except NameError: - from sets import Set as set +""" +struct tagPyCArgObject { + PyObject_HEAD + ffi_type *pffi_type; + char tag; + union { + char c; + char b; + short h; + int i; + long l; +#ifdef HAVE_LONG_LONG + PY_LONG_LONG q; +#endif + double d; + float f; + void *p; + } value; + PyObject *obj; + int size; /* for the 'V' tag */ +}; +""" -def _determine_layout(): - result = set() - for obj in (c_int(), c_longlong(), c_float(), c_double(), (c_int * 32)()): - ref = byref(obj) - result.add((c_void_p * 32).from_address(id(ref))[:].index(id(obj)) * sizeof(c_void_p)) - if len(result) != 1: - raise RuntimeError, "cannot determine byref() object layout" - return result.pop() +class value(Union): + _fields_ = [("c", c_char), + ("h", c_short), + ("i", c_int), + ("l", c_long), + ("q", c_longlong), + ("d", c_double), + ("f", c_float), + ("p", c_void_p)] -offset = _determine_layout() +# Thanks to Lenard Lindstrom for this tip: The sizeof(PyObject_HEAD) +# is the same as object.__basicsize__. -__all__ = ["byref_at"] +class PyCArgObject(Structure): + _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__), + ("pffi_type", c_void_p), + ("value", value), + ("obj", c_void_p), + ("size", c_int)] + _anonymous_ = ["value"] + +assert sizeof(PyCArgObject) == type(byref(c_int())).__basicsize__ + +print "sizeof(PyCArgObject)", sizeof(PyCArgObject) +for name in "c h i l q d f p".split(): + print name, getattr(PyCArgObject, name)
93650f0ae762949affcee4bfcf4a94093fe651d5
neuralmonkey/runners/perplexity_runner.py
neuralmonkey/runners/perplexity_runner.py
from typing import Dict, List from typeguard import check_argument_types import tensorflow as tf import numpy as np from neuralmonkey.decoders.autoregressive import AutoregressiveDecoder from neuralmonkey.decorators import tensor from neuralmonkey.runners.base_runner import BaseRunner class PerplexityRunner(BaseRunner[AutoregressiveDecoder]): # pylint: disable=too-few-public-methods # Pylint issue here: https://github.com/PyCQA/pylint/issues/2607 class Executable(BaseRunner.Executable["PerplexityRunner"]): def collect_results(self, results: List[Dict]) -> None: perplexities = np.mean( [2 ** res["xents"] for res in results], axis=0) xent = float(np.mean([res["xents"] for res in results])) self.set_runner_result(outputs=perplexities.tolist(), losses=[xent]) # pylint: enable=too-few-public-methods def __init__(self, output_series: str, decoder: AutoregressiveDecoder) -> None: check_argument_types() BaseRunner[AutoregressiveDecoder].__init__( self, output_series, decoder) @tensor def fetches(self) -> Dict[str, tf.Tensor]: return {"xents": self.decoder.train_xents} @property def loss_names(self) -> List[str]: return ["xents"]
from typing import Dict, List from typeguard import check_argument_types import tensorflow as tf import numpy as np from neuralmonkey.decoders.autoregressive import AutoregressiveDecoder from neuralmonkey.decorators import tensor from neuralmonkey.runners.base_runner import BaseRunner class PerplexityRunner(BaseRunner[AutoregressiveDecoder]): # pylint: disable=too-few-public-methods # Pylint issue here: https://github.com/PyCQA/pylint/issues/2607 class Executable(BaseRunner.Executable["PerplexityRunner"]): def collect_results(self, results: List[Dict]) -> None: perplexities = np.mean( [2 ** res["xents"] for res in results], axis=0) xent = float(np.mean([res["xents"] for res in results])) self.set_runner_result(outputs=perplexities.tolist(), losses=[xent]) # pylint: enable=too-few-public-methods def __init__(self, output_series: str, decoder: AutoregressiveDecoder) -> None: check_argument_types() BaseRunner[AutoregressiveDecoder].__init__( self, output_series, decoder) @tensor def fetches(self) -> Dict[str, tf.Tensor]: return {"xents": self.decoder.train_xents} @property def loss_names(self) -> List[str]: return ["xent"]
Revert "small fix in perplexity runner"
Revert "small fix in perplexity runner" This reverts commit b195416761f12df496baa389df4686b2cf60c675.
Python
bsd-3-clause
ufal/neuralmonkey,ufal/neuralmonkey,ufal/neuralmonkey,ufal/neuralmonkey,ufal/neuralmonkey
--- +++ @@ -36,4 +36,4 @@ @property def loss_names(self) -> List[str]: - return ["xents"] + return ["xent"]
db537ab80444b9e4cc22f332577c2cba640fca0a
tasks/factory_utils.py
tasks/factory_utils.py
from factory import enums from collections import namedtuple import gc # Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes # theirs easy to override! enums.SPLITTER = "____" # More flexible than FactoryBoy's sequences because you can create and # destroy them where-ever you want. class Adder: def __init__(self, x=0): self.x = x def __call__(self, value): self.x += value return int(self.x) def reset(self, x): self.x = x # Boilerplate that every factory would need to deal with. def SessionBase(session): class BaseMeta: sqlalchemy_session = session sqlalchemy_session_persistence = "commit" return BaseMeta # Thin collector for the factories and a place to try to achieve better # scalability than the create_batch function from FactoryBoy. class Factories: unflushed_record_counter = 0 def __init__(self, session, namespace): self.session = session self.factory_classes = { key: value for key, value in namespace.items() if hasattr(value, "generate_batch") } def create_batch(self, classname, batchsize, **kwargs): cls = self.factory_classes.get(classname, None) assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?" for _ in range(batchsize): cls.create(**kwargs)
from factory import enums from collections import namedtuple import gc # Factoryboy uses "__" and Salesforce uses "__". Luckily Factoryboy makes # theirs easy to override! enums.SPLITTER = "____" # More flexible than FactoryBoy's sequences because you can create and # destroy them where-ever you want. class Adder: def __init__(self, x=0): self.x = x def __call__(self, value): self.x += value return int(self.x) def reset(self, x): self.x = x # Boilerplate that every factory would need to deal with. def SessionBase(session): class BaseMeta: sqlalchemy_session = session sqlalchemy_session_persistence = "commit" return BaseMeta # Thin collector for the factories and a place to try to achieve better # scalability than the create_batch function from FactoryBoy. class Factories: unflushed_record_counter = 0 def __init__(self, session, namespace): self.session = session self.factory_classes = { key: value for key, value in namespace.items() if hasattr(value, "generate_batch") } def create_batch(self, classname, batchsize, **kwargs): cls = self.factory_classes.get(classname, None) assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?" for _ in range(batchsize): cls.create(**kwargs) def __getitem__(self, name): return self.factory_classes[name]
Make it easy to get a single item.
Make it easy to get a single item.
Python
bsd-3-clause
SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus,SalesforceFoundation/Cumulus
--- +++ @@ -45,3 +45,6 @@ assert cls, f"Cannot find a factory class named {classname}. Did you misspell it?" for _ in range(batchsize): cls.create(**kwargs) + + def __getitem__(self, name): + return self.factory_classes[name]
180062c4d1159185ab113e98f41bb219d52086e8
test.py
test.py
from pyserializable import serialize, deserialize, autoserialized from pyserializable.util import repr_func @autoserialized class Color: serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8' serial_attr_converters = {'r': [int, str]} __repr__ = repr_func('r', 'g', 'b', 'a') @autoserialized class Tile: serial_format = 'enabled=uint:1, color=Color, elite=uint:1' serial_fmt_converters = {'uint:1': [int, bool]} __repr__ = repr_func('enabled', 'color', 'elite') t = Tile() t.enabled = False t.elite = True t.color = Color() t.color.r = '201' t.color.g = 202 t.color.b = 203 t.color.a = 204 data = serialize(t) # Deserialize based on class t2 = deserialize(Tile, data) #Deserialize into existing instance t3 = Tile() deserialize(t3, data) print(t) print(t2) print(t3)
from pyserializable import serialize, deserialize, autoserialized from pyserializable.util import repr_func @autoserialized class Color(object): serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8' serial_attr_converters = {'r': [int, str]} __repr__ = repr_func('r', 'g', 'b', 'a') @autoserialized class Tile(object): serial_format = 'enabled=uint:1, color=Color, elite=uint:1' serial_fmt_converters = {'uint:1': [int, bool]} __repr__ = repr_func('enabled', 'color', 'elite') t = Tile() t.enabled = False t.elite = True t.color = Color() t.color.r = '201' t.color.g = 202 t.color.b = 203 t.color.a = 204 data = serialize(t) # Deserialize based on class t2 = deserialize(Tile, data) #Deserialize into existing instance t3 = Tile() deserialize(t3, data) print(t) print(t2) print(t3)
Fix base class for python 2.x
Fix base class for python 2.x
Python
mit
numberoverzero/origami
--- +++ @@ -3,14 +3,14 @@ @autoserialized -class Color: +class Color(object): serial_format = 'r=uint:8, g=uint:8, b=uint:8, a=uint:8' serial_attr_converters = {'r': [int, str]} __repr__ = repr_func('r', 'g', 'b', 'a') @autoserialized -class Tile: +class Tile(object): serial_format = 'enabled=uint:1, color=Color, elite=uint:1' serial_fmt_converters = {'uint:1': [int, bool]} __repr__ = repr_func('enabled', 'color', 'elite')
42f67bdbf94a1a186518788f9685786b5c767eec
performance/web.py
performance/web.py
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) self.started = time() response = getattr(requests, self.type)( url=self.url, data=data ) self.finished = time() self.status_code = response.status_code except AttributeError: raise RequestTypeError(type=self.type) def get_response_time(self): try: return self.finished - self.started except AttributeError: raise RequestTimeError class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type class RequestTimeError(Exception): pass
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type class RequestTimeError(Exception): pass
Update Request, only return response time
Update Request, only return response time Request: remove status_code and get_response_time() and only return the response time on do() function
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
--- +++ @@ -23,21 +23,15 @@ data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) - self.started = time() + started = time() response = getattr(requests, self.type)( url=self.url, data=data ) - self.finished = time() - self.status_code = response.status_code + finished = time() + return finished - started except AttributeError: raise RequestTypeError(type=self.type) - - def get_response_time(self): - try: - return self.finished - self.started - except AttributeError: - raise RequestTimeError class RequestData:
24fa27e05e0ed58e955ed6365de101b2e9653a7b
cli.py
cli.py
#!/usr/bin/env python import sys,os from copy import deepcopy from scrabble import make_board,top_moves,read_dictionary def show_board(board,play=None): if not play: for row in board: print ''.join(row) else: b = deepcopy(board) for x,r,c in play: b[r][c] = x.lower() show_board(b) if __name__ == '__main__': assert len(sys.argv) >= 3, 'Usage: ./scrabble.py boardfile hand [num_moves]' board = make_board(open(sys.argv[1])) hand = sys.argv[2].upper() path = os.path.dirname(sys.argv[0]) num_moves = int(sys.argv[3]) if len(sys.argv) > 3 else 20 for score,words,play in top_moves(board,read_dictionary(path),hand,num_moves): print score, ', '.join(words) show_board(board,play) print ''
#!/usr/bin/env python import os from copy import deepcopy from optparse import OptionParser from scrabble import make_board,top_moves,read_dictionary def show_board(board, play=None): if not play: for row in board: print ''.join(row) else: b = deepcopy(board) for x,r,c in play: b[r][c] = x.lower() show_board(b) def main(): op = OptionParser(usage='%prog [-n 20] boardfile hand') op.add_option('-n', '--num-plays', type=int, default=20, help='Number of possible plays to display') opts, args = op.parse_args() if len(args) != 2: op.error('Must provide boardfile and hand as arguments') board = make_board(open(args[0])) hand = args[1].upper() word_list = read_dictionary(os.path.dirname(__file__)) for score, words, play in top_moves(board, word_list, hand, opts.num_plays): print score, ', '.join(words) show_board(board, play) print '' if __name__ == '__main__': main()
Use optparse instead of hand-rolled options
Use optparse instead of hand-rolled options
Python
mit
perimosocordiae/wwf,perimosocordiae/wwf
--- +++ @@ -1,9 +1,11 @@ #!/usr/bin/env python -import sys,os +import os from copy import deepcopy +from optparse import OptionParser from scrabble import make_board,top_moves,read_dictionary -def show_board(board,play=None): + +def show_board(board, play=None): if not play: for row in board: print ''.join(row) @@ -13,13 +15,22 @@ b[r][c] = x.lower() show_board(b) + +def main(): + op = OptionParser(usage='%prog [-n 20] boardfile hand') + op.add_option('-n', '--num-plays', type=int, default=20, + help='Number of possible plays to display') + opts, args = op.parse_args() + if len(args) != 2: + op.error('Must provide boardfile and hand as arguments') + board = make_board(open(args[0])) + hand = args[1].upper() + word_list = read_dictionary(os.path.dirname(__file__)) + for score, words, play in top_moves(board, word_list, hand, opts.num_plays): + print score, ', '.join(words) + show_board(board, play) + print '' + if __name__ == '__main__': - assert len(sys.argv) >= 3, 'Usage: ./scrabble.py boardfile hand [num_moves]' - board = make_board(open(sys.argv[1])) - hand = sys.argv[2].upper() - path = os.path.dirname(sys.argv[0]) - num_moves = int(sys.argv[3]) if len(sys.argv) > 3 else 20 - for score,words,play in top_moves(board,read_dictionary(path),hand,num_moves): - print score, ', '.join(words) - show_board(board,play) - print '' + main() +
1bd540f43c25dec125085acee7bbe0904363c204
test.py
test.py
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('U', rotor.encode_reverse('A')) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
import unittest from enigma import Enigma, Steckerbrett, Umkehrwalze, Walzen class RotorTestCase(unittest.TestCase): def test_rotor_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('E', rotor.encode('A')) def test_rotor_reverse_encoding(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('U', rotor.encode_reverse('A')) def test_rotor_different_setting(self): rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', setting='B') self.assertEqual('K', rotor.encode('A')) self.assertEqual('K', rotor.encode_reverse('A')) def run_tests(): runner = unittest.TextTestRunner() suite = unittest.TestLoader().loadTestsFromTestCase(RotorTestCase) runner.run(suite) if __name__ == '__main__': # pragma: no cover run_tests()
Test if rotor encodes with different setting properly
Test if rotor encodes with different setting properly
Python
mit
ranisalt/enigma
--- +++ @@ -13,6 +13,12 @@ rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q') self.assertEqual('U', rotor.encode_reverse('A')) + def test_rotor_different_setting(self): + rotor = Walzen(wiring='EKMFLGDQVZNTOWYHXUSPAIBRCJ', notch='Q', + setting='B') + self.assertEqual('K', rotor.encode('A')) + self.assertEqual('K', rotor.encode_reverse('A')) + def run_tests(): runner = unittest.TextTestRunner()
0b2d523665f3989d9375cd83970400ace0e40336
sites/docs/conf.py
sites/docs/conf.py
# Obtain shared config values import os, sys sys.path.append(os.path.abspath('..')) sys.path.append(os.path.abspath('../..')) from shared_conf import * # Enable autodoc, intersphinx extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']) # Autodoc settings autodoc_default_flags = ['members', 'special-members']
# Obtain shared config values import os, sys sys.path.append(os.path.abspath('..')) sys.path.append(os.path.abspath('../..')) from shared_conf import * # Enable autodoc, intersphinx extensions.extend(['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']) # Autodoc settings autodoc_default_flags = ['members', 'special-members'] # Intersphinx connection to stdlib intersphinx_mapping = { 'python': ('http://docs.python.org/2.6', None), }
Connect to Python stdlib intersphinx
Connect to Python stdlib intersphinx
Python
lgpl-2.1
torkil/paramiko,ameily/paramiko,SebastianDeiss/paramiko,dorianpula/paramiko,remram44/paramiko,zarr12steven/paramiko,mirrorcoder/paramiko,fvicente/paramiko,davidbistolas/paramiko,CptLemming/paramiko,redixin/paramiko,digitalquacks/paramiko,reaperhulk/paramiko,thisch/paramiko,rcorrieri/paramiko,mhdaimi/paramiko,paramiko/paramiko,jaraco/paramiko,anadigi/paramiko,Automatic/paramiko,toby82/paramiko,varunarya10/paramiko,thusoy/paramiko,selboo/paramiko,jorik041/paramiko,esc/paramiko,dlitz/paramiko,zpzgone/paramiko
--- +++ @@ -9,3 +9,8 @@ # Autodoc settings autodoc_default_flags = ['members', 'special-members'] + +# Intersphinx connection to stdlib +intersphinx_mapping = { + 'python': ('http://docs.python.org/2.6', None), +}
890c0d919aba273489c27243c513c822399c5d35
datasurvey/packages.py
datasurvey/packages.py
import gzip import bz2 import rarfile import zipfile import tarfile class PackageHandler: def __init__(self, buffer): self.buffer = buffer def __iter__(self): for name in self.archive.namelist(): with self.archive.open(name) as ar: # TODO: Handle archives outbuf = ar.read(1000) yield (name, outbuf) class ZipHandler(PackageHandler): MIMETYPES = ["application/zip"] def __init__(self, buffer): PackageHandler.__init__(self, buffer) self.archive = zipfile.ZipFile(buffer) class RarHandler(PackageHandler): MIMETYPES = ["application/x-rar-compressed"] def __init__(self, buffer): PackageHandler.__init__(self, buffer) self.archive = zipfile.RarFile(buffer) package_handlers = {} def register_handler(handler): for mt in handler.MIMETYPES: package_handlers[mt] = handler register_handler(ZipHandler) register_handler(RarHandler)
import gzip import bz2 import rarfile import zipfile import tarfile class PackageHandler: def __init__(self, buffer): self.buffer = buffer def __iter__(self): for name in self.archive.namelist(): info = self.archive.getinfo(name) if hasattr(info, 'isdir') and info.isdir(): continue if name[-1] == "/": continue with self.archive.open(name) as ar: # TODO: Handle archives outbuf = ar.read(1000) yield (name, outbuf) class ZipHandler(PackageHandler): MIMETYPES = ["application/zip"] def __init__(self, buffer): PackageHandler.__init__(self, buffer) self.archive = zipfile.ZipFile(buffer) class RarHandler(PackageHandler): MIMETYPES = ["application/x-rar-compressed"] def __init__(self, buffer): PackageHandler.__init__(self, buffer) self.archive = zipfile.RarFile(buffer) package_handlers = {} def register_handler(handler): for mt in handler.MIMETYPES: package_handlers[mt] = handler register_handler(ZipHandler) register_handler(RarHandler)
Fix recursion issue with zip/rar files
Fix recursion issue with zip/rar files
Python
mit
occrp/datasurvey
--- +++ @@ -10,6 +10,11 @@ def __iter__(self): for name in self.archive.namelist(): + info = self.archive.getinfo(name) + if hasattr(info, 'isdir') and info.isdir(): + continue + if name[-1] == "/": + continue with self.archive.open(name) as ar: # TODO: Handle archives outbuf = ar.read(1000)
bb7de7e76302fbd3eeeeb740d00c234faadef4ef
tests/test_nonsensefilter.py
tests/test_nonsensefilter.py
from unittest import TestCase from spicedham.nonsensefilter import NonsenseFilter class TestNonsenseFilter(TestCase): # TODO: This test will likely fail spectacularly because of a lack of # training. def test_classify(self): nonsense = NonsenseFilter() nonsense.filter_match = 1 nonsense.filter_miss = 0 reverse = lambda x: x[::-1] match_message = map(reverse, ['supposedly', 'nonsense', 'words']) miss_message = ['Firefox'] self.assertEqual(nonsense.classify(match_message), 1) self.assertEqual(nonsense.classify(miss_message), 0)
from tests.test_classifierbase import TestClassifierBase from spicedham.backend import load_backend from spicedham.nonsensefilter import NonsenseFilter class TestNonsenseFilter(TestClassifierBase): def test_train(self): backend = load_backend() nonsense = NonsenseFilter() alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) self._training(nonsense, alphabet, reversed_alphabet) for letter in alphabet: self.assertEqual(True, backend.get_key(nonsense.__class__.__name__, letter)) def test_classify(self): nonsense = NonsenseFilter() nonsense.filter_match = 1 nonsense.filter_miss = 0 alphabet = map(chr, range(97, 123)) reversed_alphabet = reversed(alphabet) self._training(nonsense, alphabet, reversed_alphabet) match_message = ['not', 'in', 'training', 'set'] miss_message = ['a'] self.assertEqual(nonsense.classify(match_message), 1) self.assertEqual(nonsense.classify(miss_message), 0)
Add a base class and a test_train function
Add a base class and a test_train function Overall, fix a very incomplete test.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
--- +++ @@ -1,18 +1,28 @@ -from unittest import TestCase +from tests.test_classifierbase import TestClassifierBase +from spicedham.backend import load_backend from spicedham.nonsensefilter import NonsenseFilter -class TestNonsenseFilter(TestCase): +class TestNonsenseFilter(TestClassifierBase): + + def test_train(self): + backend = load_backend() + nonsense = NonsenseFilter() + alphabet = map(chr, range(97, 123)) + reversed_alphabet = reversed(alphabet) + self._training(nonsense, alphabet, reversed_alphabet) + for letter in alphabet: + self.assertEqual(True, + backend.get_key(nonsense.__class__.__name__, letter)) - # TODO: This test will likely fail spectacularly because of a lack of - # training. def test_classify(self): nonsense = NonsenseFilter() nonsense.filter_match = 1 nonsense.filter_miss = 0 - reverse = lambda x: x[::-1] - match_message = map(reverse, ['supposedly', 'nonsense', 'words']) - miss_message = ['Firefox'] + alphabet = map(chr, range(97, 123)) + reversed_alphabet = reversed(alphabet) + self._training(nonsense, alphabet, reversed_alphabet) + match_message = ['not', 'in', 'training', 'set'] + miss_message = ['a'] self.assertEqual(nonsense.classify(match_message), 1) self.assertEqual(nonsense.classify(miss_message), 0) -
4672e447617e754d6b4d229ce775fbf9ee0b35aa
tests/test_requesthandler.py
tests/test_requesthandler.py
from unittest import TestCase from ppp_datamodel.communication import Request from ppp_datamodel import Triple, Resource, Missing from ppp_libmodule.tests import PPPTestCase from ppp_spell_checker import app class RequestHandlerTest(PPPTestCase(app)): def testCorrectSentence(self): original = 'What is the birth date of George Washington' j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], 'tree': {'type': 'sentence', 'value': original}} answer = self.request(j) self.assertEquals(len(answer), 0) def testWrongSentence(self): original = 'What is the bitrh date of George Washington' expected = 'What is the birth date of George Washington' j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], 'tree': {'type': 'sentence', 'value': original}} answer = self.request(j) self.assertEquals(len(answer), 1) self.assertIsInstance(answer[0].tree, Resource) result = answer[0].tree.__getattr__('value') self.assertEqual(result, expected)
from unittest import TestCase from ppp_datamodel.communication import Request from ppp_datamodel import Triple, Resource, Missing from ppp_libmodule.tests import PPPTestCase from ppp_spell_checker import app class RequestHandlerTest(PPPTestCase(app)): def testCorrectSentence(self): original = 'What is the birth date of George Washington' j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], 'tree': {'type': 'sentence', 'value': original}} answer = self.request(j) self.assertEquals(len(answer), 0) def testWrongSentence(self): original = 'What is the bitrh date of George Washington' expected = 'What is the birth date of George Washington' j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], 'tree': {'type': 'sentence', 'value': original}} answer = self.request(j) self.assertEquals(len(answer), 1) self.assertIsInstance(answer[0].tree, Resource) result = answer[0].tree.__getattr__('value') self.assertEqual(result, expected) def testIrrelevantInput(self): original = 'What is the birth date of George Washington' j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], 'tree': {'type': 'resource', 'value': original}} answer = self.request(j) self.assertEquals(len(answer), 0)
Add test for irrelevant input.
Add test for irrelevant input.
Python
mit
ProjetPP/PPP-Spell-Checker,ProjetPP/PPP-Spell-Checker
--- +++ @@ -23,3 +23,10 @@ self.assertIsInstance(answer[0].tree, Resource) result = answer[0].tree.__getattr__('value') self.assertEqual(result, expected) + + def testIrrelevantInput(self): + original = 'What is the birth date of George Washington' + j = {'id': '1', 'language': 'en', 'measures': {}, 'trace': [], + 'tree': {'type': 'resource', 'value': original}} + answer = self.request(j) + self.assertEquals(len(answer), 0)
978dd0161552458331870af0b524cdcff25fd71d
furious/handlers/__init__.py
furious/handlers/__init__.py
# # Copyright 2012 WebFilings, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) work = Async.from_dict(async_options) logging.info(work._function_path) run_job(work) return 200, work._function_path
# # Copyright 2012 WebFilings, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import json import logging from ..async import Async from ..processors import run_job def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) async = Async.from_dict(async_options) logging.info(work._function_path) with context.job_context_from_async(async): run_job(async) return 200, work._function_path
Adjust async run handler to use the JobContext manager.
Adjust async run handler to use the JobContext manager.
Python
apache-2.0
mattsanders-wf/furious,beaulyddon-wf/furious,Workiva/furious,andreleblanc-wf/furious,rosshendrickson-wf/furious,andreleblanc-wf/furious,beaulyddon-wf/furious,robertkluin/furious,rosshendrickson-wf/furious,Workiva/furious,mattsanders-wf/furious
--- +++ @@ -25,11 +25,12 @@ def process_async_task(headers, request_body): """Process an Async task and execute the requested function.""" async_options = json.loads(request_body) - work = Async.from_dict(async_options) + async = Async.from_dict(async_options) logging.info(work._function_path) - run_job(work) + with context.job_context_from_async(async): + run_job(async) return 200, work._function_path
713b91c4d7dc3737223bc70aa329ec9de2c48fb8
mycli/packages/special/utils.py
mycli/packages/special/utils.py
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' directory = '' error = False tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] try: os.chdir(directory) subprocess.call(['pwd']) return True, None except OSError as e: return False, e.strerror
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] if len(tokens) > 1 else None if not directory: return False, "No folder name was provided." try: os.chdir(directory) subprocess.call(['pwd']) return True, None except OSError as e: return False, e.strerror
Add validation for 'cd' command argument
Add validation for 'cd' command argument
Python
bsd-3-clause
mdsrosa/mycli,mdsrosa/mycli
--- +++ @@ -4,12 +4,10 @@ def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' - directory = '' - error = False - tokens = arg.split(CD_CMD + ' ') - directory = tokens[-1] - + directory = tokens[-1] if len(tokens) > 1 else None + if not directory: + return False, "No folder name was provided." try: os.chdir(directory) subprocess.call(['pwd'])
75b1fdc9f290c85b4d469cdce5e5d1154aed4881
indra/tests/test_util.py
indra/tests/test_util.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB from indra.util import unicode_strs from io import BytesIO def test_unicode_tree_builder(): xml = u'<html><bar>asdf</bar></html>'.encode('utf-8') xml_io = BytesIO(xml) tree = ET.parse(xml_io, parser=UTB()) bar = tree.find('.//bar') assert unicode_strs(bar)
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import json import xml.etree.ElementTree as ET from indra.util import UnicodeXMLTreeBuilder as UTB, kappy_json_to_graph from indra.util import unicode_strs from io import BytesIO def test_unicode_tree_builder(): xml = u'<html><bar>asdf</bar></html>'.encode('utf-8') xml_io = BytesIO(xml) tree = ET.parse(xml_io, parser=UTB()) bar = tree.find('.//bar') assert unicode_strs(bar) def test_kappy_influence_json_to_graph(): with open('kappy_influence.json', 'r') as f: imap = json.load(f) graph = kappy_json_to_graph(imap) assert graph is not None, 'No graph produced.' n_nodes = len(graph.nodes) n_edges = len(graph.edges) assert n_nodes == 4, \ 'Wrong number (%d vs. %d) of nodes on the graph.' % (n_nodes, 4) assert n_edges == 6, \ "Wrong number (%d vs. %d) of edges on graph." % (n_edges, 4)
Implement test for basic graph.
Implement test for basic graph.
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/belpy,bgyori/indra,johnbachman/indra
--- +++ @@ -1,9 +1,12 @@ from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str + +import json import xml.etree.ElementTree as ET -from indra.util import UnicodeXMLTreeBuilder as UTB +from indra.util import UnicodeXMLTreeBuilder as UTB, kappy_json_to_graph from indra.util import unicode_strs from io import BytesIO + def test_unicode_tree_builder(): xml = u'<html><bar>asdf</bar></html>'.encode('utf-8') @@ -12,3 +15,16 @@ bar = tree.find('.//bar') assert unicode_strs(bar) + +def test_kappy_influence_json_to_graph(): + with open('kappy_influence.json', 'r') as f: + imap = json.load(f) + graph = kappy_json_to_graph(imap) + assert graph is not None, 'No graph produced.' + n_nodes = len(graph.nodes) + n_edges = len(graph.edges) + assert n_nodes == 4, \ + 'Wrong number (%d vs. %d) of nodes on the graph.' % (n_nodes, 4) + assert n_edges == 6, \ + "Wrong number (%d vs. %d) of edges on graph." % (n_edges, 4) +
052367e1239e918cdcb9106b4494a48e34e92643
pychecker2/File.py
pychecker2/File.py
from pychecker2.util import type_filter from compiler import ast class File: def __init__(self, name): self.name = name self.parseTree = None self.scopes = {} self.root_scope = None self.warnings = [] def __cmp__(self, other): return cmp(self.name, other.name) def warning(self, line, warn, *args): try: line = line.lineno except AttributeError: pass self.warnings.append( (line, warn, args) ) def scope_filter(self, type): return [(n, s) for n, s in self.scopes.iteritems() if isinstance(n, type) ] def function_scopes(self): return self.scope_filter(ast.Function) def class_scopes(self): return self.scope_filter(ast.Class)
from pychecker2.util import parents from compiler import ast class File: def __init__(self, name): self.name = name self.parseTree = None self.scopes = {} self.root_scope = None self.warnings = [] def __cmp__(self, other): return cmp(self.name, other.name) def warning(self, line, warn, *args): lineno = line try: lineno = line.lineno except AttributeError: pass if not lineno: try: for p in parents(line): if p.lineno: lineno = p.lineno break except AttributeError: pass self.warnings.append( (lineno, warn, args) ) def scope_filter(self, type): return [(n, s) for n, s in self.scopes.iteritems() if isinstance(n, type) ] def function_scopes(self): return self.scope_filter(ast.Function) def class_scopes(self): return self.scope_filter(ast.Class)
Add more ways to suck line numbers from nodes
Add more ways to suck line numbers from nodes
Python
bsd-3-clause
akaihola/PyChecker,thomasvs/pychecker,akaihola/PyChecker,thomasvs/pychecker
--- +++ @@ -1,4 +1,4 @@ -from pychecker2.util import type_filter +from pychecker2.util import parents from compiler import ast @@ -14,11 +14,20 @@ return cmp(self.name, other.name) def warning(self, line, warn, *args): + lineno = line try: - line = line.lineno + lineno = line.lineno except AttributeError: pass - self.warnings.append( (line, warn, args) ) + if not lineno: + try: + for p in parents(line): + if p.lineno: + lineno = p.lineno + break + except AttributeError: + pass + self.warnings.append( (lineno, warn, args) ) def scope_filter(self, type): return [(n, s)
68dee1cfef3a765a82fe7b51395219f8e1270a12
reason/__init__.py
reason/__init__.py
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from datetime import datetime from flask.ext.moment import Moment from flask_debugtoolbar import DebugToolbarExtension basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(60) userDb = 'sqlite:///' + os.path.join(basedir, 'db/reasonUser.db') spdxDb = 'postgresql://spdx:spdx@host:5432/spdx' databases = { 'userDb': userDb, 'spdxDb': spdxDb } app.config['SQLALCHEMY_BINDS'] = databases # Debug configuration app.config['DEBUG'] = False db = SQLAlchemy(app) login_manager = LoginManager() login_manager.session_protection = "strong" login_manager.login_view = "login" login_manager.init_app(app) # Debug Configuration #DEBUG_TB_INTERCEPT_REDIRECTS = False #toolbar = DebugToolbarExtension(app) ALLOWED_EXTENSIONS = set(['xml', 'jar']) moment = Moment(app)
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from datetime import datetime from flask.ext.moment import Moment from flask_debugtoolbar import DebugToolbarExtension basedir = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(60) nvdDb = 'sqlite:///' + os.path.join(basedir, 'db/nvd.vulnerabilities.db') userDb = 'sqlite:///' + os.path.join(basedir, 'db/reasonUser.db') spdxDb = 'postgresql://spdx:spdx@host:5432/spdx' # Initial URI was for searching from NVD Database, Made changes to connect to Users db using binds # App.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'nvd.vulnerabilities.db') databases = { 'nvdDb': nvdDb, 'userDb': userDb, 'spdxDb': spdxDb } app.config['SQLALCHEMY_BINDS'] = databases # Debug configuration app.config['DEBUG'] = False db = SQLAlchemy(app) login_manager = LoginManager() login_manager.session_protection = "strong" login_manager.login_view = "login" login_manager.init_app(app) # Debug Configuration #DEBUG_TB_INTERCEPT_REDIRECTS = False #toolbar = DebugToolbarExtension(app) ALLOWED_EXTENSIONS = set(['xml', 'jar']) moment = Moment(app)
Revert "Removed connections to nvd database"
Revert "Removed connections to nvd database" This reverts commit 4b2edb4bc6d9c525d0d5c825174fbd5dbfac0ac1.
Python
mit
pombredanne/reason,pombredanne/reason,pombredanne/reason
--- +++ @@ -11,12 +11,18 @@ app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(60) +nvdDb = 'sqlite:///' + os.path.join(basedir, 'db/nvd.vulnerabilities.db') userDb = 'sqlite:///' + os.path.join(basedir, 'db/reasonUser.db') spdxDb = 'postgresql://spdx:spdx@host:5432/spdx' +# Initial URI was for searching from NVD Database, Made changes to connect to Users db using binds +# App.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'nvd.vulnerabilities.db') + databases = { + 'nvdDb': nvdDb, 'userDb': userDb, - 'spdxDb': spdxDb + 'spdxDb': spdxDb + }
381bb4e11cf6951d819fa2cf298e2cc558464fc9
utils/nflc-get-categories.py
utils/nflc-get-categories.py
#!/usr/bin/env python3 import argparse import json from urllib.request import urlopen def get_data(domain): response = urlopen('http://{}/media/nflc-playlist-video.json'.format(domain)).read() return json.loads(response.decode('utf-8')) def main(): parser = argparse.ArgumentParser(description='Get the category names and IDs for a NFLC site') parser.add_argument('domain', type=str, nargs=1, help='Domain name to query for') args = parser.parse_args() data = get_data(args.domain[0]) result = {} strip_left = [ 'Podcast - ', 'Video - Show - ', 'Video - Shows - ', 'Video - ', 'Videos - Show - ', 'Videos - ', ] for category_id, category in data.items(): name = category['name'] for strip in strip_left: if name.startswith(strip): name = name[(len(strip)):] result[name.strip()] = category_id for category_name in sorted(result): print('({}, "{}"),'.format(result[category_name], category_name)) if __name__ == '__main__': main()
#!/usr/bin/env python3 import argparse import json from urllib.request import urlopen def get_data(domain): response = urlopen('http://{}/media/nflc-playlist-video.json'.format(domain)).read() return json.loads(response.decode('utf-8')) def main(): parser = argparse.ArgumentParser(description='Get the category names and IDs for a NFLC site') parser.add_argument('domain', type=str, nargs=1, help='Domain name to query for') args = parser.parse_args() data = get_data(args.domain[0]) result = {} strip_left = [ 'Podcast - ', 'Video - ', 'Videos - ', 'Show - ', 'Shows - ', ] for category_id, category in data.items(): name = category['name'] for strip in strip_left: if name.startswith(strip): name = name[(len(strip)):] result[name.strip()] = category_id for category_name in sorted(result, key=str.lower): print('({}, "{}"),'.format(result[category_name], category_name)) if __name__ == '__main__': main()
Simplify NFLC utils script stripping and sort categories case-insensitive
Simplify NFLC utils script stripping and sort categories case-insensitive
Python
mit
Tenzer/plugin.video.nfl-teams
--- +++ @@ -19,11 +19,10 @@ result = {} strip_left = [ 'Podcast - ', - 'Video - Show - ', - 'Video - Shows - ', 'Video - ', - 'Videos - Show - ', 'Videos - ', + 'Show - ', + 'Shows - ', ] for category_id, category in data.items(): @@ -34,7 +33,7 @@ result[name.strip()] = category_id - for category_name in sorted(result): + for category_name in sorted(result, key=str.lower): print('({}, "{}"),'.format(result[category_name], category_name))
a0c2e64c92d89276d73b5e4ca31e10a352ab37f1
analyser/api.py
analyser/api.py
import os import requests from flask import Blueprint from utils.decorators import validate, require from utils.validators import validate_url from .parser import Parser endpoint = Blueprint('analyse_url', __name__) @endpoint.route('analyse/', methods=['POST']) @require('url') @validate({ 'url': validate_url }) def analyse_url(url): name, ext = os.path.splitext(url) parse = Parser(ext=ext[1:]) response = requests.get(url, stream=True) fields = [] for chunk in response.iter_lines(1024): fields = parse(chunk) if fields: break print fields return url
import os import json import requests import rethinkdb as r from flask import Blueprint, current_app from utils.decorators import validate, require from utils.validators import validate_url from krunchr.vendors.rethinkdb import db from .parser import Parser from .tasks import get_file endpoint = Blueprint('analyse_url', __name__) @endpoint.route('analyse/', methods=['POST']) @require('url') @validate({ 'url': validate_url }) def analyse_url(url): name, ext = os.path.splitext(url) parse = Parser(ext=ext[1:]) response = requests.get(url, stream=True) fields = [] for chunk in response.iter_lines(1024): fields = parse(chunk) if fields: break task_id = get_file.delay(url, current_app.config['DISCO_FILES']).task_id r.table('jobs').insert({ 'url': url, 'task_id': task_id, 'state': 'starting' }).run(db.conn) return json.dumps(fields)
Put job id in rethink db
Put job id in rethink db
Python
apache-2.0
vtemian/kruncher
--- +++ @@ -1,12 +1,18 @@ import os +import json + import requests +import rethinkdb as r -from flask import Blueprint +from flask import Blueprint, current_app from utils.decorators import validate, require from utils.validators import validate_url +from krunchr.vendors.rethinkdb import db + from .parser import Parser +from .tasks import get_file endpoint = Blueprint('analyse_url', __name__) @@ -27,6 +33,10 @@ if fields: break - print fields - - return url + task_id = get_file.delay(url, current_app.config['DISCO_FILES']).task_id + r.table('jobs').insert({ + 'url': url, + 'task_id': task_id, + 'state': 'starting' + }).run(db.conn) + return json.dumps(fields)
de69c4048fe8533185a4eca6f98c7d74967618bf
opentreemap/opentreemap/util.py
opentreemap/opentreemap/util.py
from django.views.decorators.csrf import csrf_exempt import json def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, Http404 def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method if method not in kwargs: raise Http404() else: req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped
Return a 404, not a 500 on a verb mismatch
Return a 404, not a 500 on a verb mismatch Fixes #1101
Python
agpl-3.0
maurizi/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core
--- +++ @@ -1,13 +1,24 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +import json + from django.views.decorators.csrf import csrf_exempt -import json +from django.http import HttpResponse, HttpResponseRedirect, Http404 def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method - req_method = kwargs[method] - return req_method(request, *args2, **kwargs2) + + if method not in kwargs: + raise Http404() + else: + req_method = kwargs[method] + return req_method(request, *args2, **kwargs2) return routed
0019cfc3d6bc8b81520e09daa0b84662d76aff93
opps/core/models/publishable.py
opps/core/models/publishable.py
#!/usr/bin/env python from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from opps.core.models.date import Date from datetime import datetime class PublishableMnager(models.Manager): def all_published(self): return super(PublishableMnager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Publishable(Date): user = models.ForeignKey(settings.AUTH_USER_MODEL) site = models.ForeignKey(Site, default=0) date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublishableMnager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
#!/usr/bin/env python from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from opps.core.models.date import Date from datetime import datetime class PublishableManager(models.Manager): def all_published(self): return super(PublishableManager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Publishable(Date): user = models.ForeignKey(settings.AUTH_USER_MODEL) site = models.ForeignKey(Site, default=0) date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublishableManager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
Fix spelling error on core published PublishableMnager to PublishableManager
Fix spelling error on core published PublishableMnager to PublishableManager
Python
mit
jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps
--- +++ @@ -10,9 +10,9 @@ -class PublishableMnager(models.Manager): +class PublishableManager(models.Manager): def all_published(self): - return super(PublishableMnager, self).get_query_set().filter( + return super(PublishableManager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) @@ -24,7 +24,7 @@ default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) - objects = PublishableMnager() + objects = PublishableManager() class Meta: abstract = True
ee33022db50a66b6e2db12972a2ed107276cc666
apps/common/tests/python/mediawords/key_value_store/test_cached_amazon_s3.py
apps/common/tests/python/mediawords/key_value_store/test_cached_amazon_s3.py
from mediawords.key_value_store.cached_amazon_s3 import CachedAmazonS3Store from .amazon_s3_credentials import ( TestAmazonS3CredentialsTestCase, get_test_s3_credentials, ) test_credentials = get_test_s3_credentials() class TestCachedAmazonS3StoreTestCase(TestAmazonS3CredentialsTestCase): def _initialize_store(self) -> CachedAmazonS3Store: return CachedAmazonS3Store( access_key_id=test_credentials.access_key_id(), secret_access_key=test_credentials.secret_access_key(), bucket_name=test_credentials.bucket_name(), directory_name=test_credentials.directory_name(), cache_table='cache.s3_raw_downloads_cache', ) def _expected_path_prefix(self) -> str: return 's3:' def test_key_value_store(self): self._test_key_value_store()
from mediawords.key_value_store.cached_amazon_s3 import CachedAmazonS3Store from mediawords.util.text import random_string from .amazon_s3_credentials import ( TestAmazonS3CredentialsTestCase, get_test_s3_credentials, ) test_credentials = get_test_s3_credentials() class TestCachedAmazonS3StoreTestCase(TestAmazonS3CredentialsTestCase): def _initialize_store(self) -> CachedAmazonS3Store: return CachedAmazonS3Store( access_key_id=test_credentials.access_key_id(), secret_access_key=test_credentials.secret_access_key(), bucket_name=test_credentials.bucket_name(), directory_name=test_credentials.directory_name() + '/' + random_string(16), cache_table='cache.s3_raw_downloads_cache', ) def _expected_path_prefix(self) -> str: return 's3:' def test_key_value_store(self): self._test_key_value_store()
Append random string to S3 test directory name to be able to run parallel tests
Append random string to S3 test directory name to be able to run parallel tests
Python
agpl-3.0
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
--- +++ @@ -1,4 +1,5 @@ from mediawords.key_value_store.cached_amazon_s3 import CachedAmazonS3Store +from mediawords.util.text import random_string from .amazon_s3_credentials import ( TestAmazonS3CredentialsTestCase, get_test_s3_credentials, @@ -13,7 +14,7 @@ access_key_id=test_credentials.access_key_id(), secret_access_key=test_credentials.secret_access_key(), bucket_name=test_credentials.bucket_name(), - directory_name=test_credentials.directory_name(), + directory_name=test_credentials.directory_name() + '/' + random_string(16), cache_table='cache.s3_raw_downloads_cache', )
94197717719b580aa9b8bf7a6cbe28f95000a2dc
gcouchbase/tests/test_api.py
gcouchbase/tests/test_api.py
from couchbase.tests.base import ApiImplementationMixin, SkipTest try: import gevent except ImportError as e: raise SkipTest(e) from gcouchbase.bucket import Bucket, GView from couchbase.tests.importer import get_configured_classes class GEventImplMixin(ApiImplementationMixin): factory = Bucket viewfactor = GView should_check_refcount = False skiplist = ('ConnectionIopsTest', 'LockmodeTest', 'ConnectionPipelineTest') configured_classes = get_configured_classes(GEventImplMixin, skiplist=skiplist) globals().update(configured_classes)
from couchbase.tests.base import ApiImplementationMixin, SkipTest try: import gevent except ImportError as e: raise SkipTest(e) from gcouchbase.bucket import Bucket, GView from couchbase.tests.importer import get_configured_classes class GEventImplMixin(ApiImplementationMixin): factory = Bucket viewfactor = GView should_check_refcount = False skiplist = ('ConnectionIopsTest', 'LockmodeTest', 'ConnectionPipelineTest') configured_classes = get_configured_classes(GEventImplMixin, skiplist=skiplist) # View iterator test no longer works because of missing include_docs def viter_skipfn(*args): raise SkipTest("include_docs not provided on client, " "and no longer supported by server") for n in ('test_include_docs', 'test_row_processor'): setattr(configured_classes['ViewIteratorTest_Bucket'], n, viter_skipfn) globals().update(configured_classes)
Disable include_docs test for GCouchbase
Disable include_docs test for GCouchbase The gevent api cannot cleanly use include_docs here; previously we relied on the server to retrieve this, but the server no longer supports this. Perhaps in some future time we can implement this within libcouchbase itself, but until then, it's left unimplemented. Change-Id: I1dc5cf86b4b063d251363f3d5fa14c8d29e8e6c1 Reviewed-on: http://review.couchbase.org/44149 Tested-by: Mark Nunberg <e7d42768707bf23038325b0b68d4b577e5f6064a@haskalah.org> Reviewed-by: Volker Mische <fb414f8ac0dbbf87663550ae4ef5fc95b1041941@gmail.com>
Python
apache-2.0
couchbase/couchbase-python-client,couchbase/couchbase-python-client,mnunberg/couchbase-python-client,mnunberg/couchbase-python-client
--- +++ @@ -17,4 +17,14 @@ configured_classes = get_configured_classes(GEventImplMixin, skiplist=skiplist) + +# View iterator test no longer works because of missing include_docs +def viter_skipfn(*args): + raise SkipTest("include_docs not provided on client, " + "and no longer supported by server") + + +for n in ('test_include_docs', 'test_row_processor'): + setattr(configured_classes['ViewIteratorTest_Bucket'], n, viter_skipfn) + globals().update(configured_classes)
a33df3c34cf69102831c8878b71266aaa41ac8fb
feed/setup.py
feed/setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the feed Sphinx extension. It creates an RSS feed of recently updated sphinx pages. ''' requires = ['Sphinx>=0.6', 'python-dateutil', 'beautifulsoup>=3.2.0', 'html5lib'] setup( name='feed', version='0.2', url='http://bitbucket.org/birkenfeld/sphinx-contrib', # download_url='http://pypi.python.org/pypi/feed', license='BSD', author='dan mackinlay', author_email='bitbucket@email.possumpalace.org', description='Sphinx extension feed', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the feed Sphinx extension. It creates an RSS feed of recently updated sphinx pages. ''' requires = ['Sphinx>=0.6', 'python-dateutil', 'html5lib'] setup( name='feed', version='0.2', url='http://bitbucket.org/birkenfeld/sphinx-contrib', # download_url='http://pypi.python.org/pypi/feed', license='BSD', author='dan mackinlay', author_email='bitbucket@email.possumpalace.org', description='Sphinx extension feed', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
Remove beautifulsoup from the feed extension's requirements.
Remove beautifulsoup from the feed extension's requirements.
Python
bsd-2-clause
sphinx-contrib/spelling,sphinx-contrib/spelling
--- +++ @@ -8,7 +8,7 @@ It creates an RSS feed of recently updated sphinx pages. ''' -requires = ['Sphinx>=0.6', 'python-dateutil', 'beautifulsoup>=3.2.0', 'html5lib'] +requires = ['Sphinx>=0.6', 'python-dateutil', 'html5lib'] setup( name='feed',
53780b6d16d631a3c0e8859ff9771a1379de16f1
calaccess_raw/admin/tracking.py
calaccess_raw/admin/tracking.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): """ Custom admin for the RawDataVersion model. """ list_display = ( "id", "release_datetime", "pretty_download_size", "download_file_count", "download_record_count", "clean_file_count", "clean_record_count", "pretty_clean_size", "download_file_count", "clean_record_count" ) list_display_links = ('release_datetime',) list_filter = ("release_datetime",) @admin.register(models.RawDataFile) class RawDataFileAdmin(BaseAdmin): """ Custom admin for the RawDataFile model. """ list_display = ( "id", "version", "file_name", "download_records_count", "clean_records_count", "load_records_count", "error_count" ) list_display_links = ('id', 'file_name',) list_filter = ("version__release_datetime",)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Custom administration panels for tracking models. """ from django.contrib import admin from calaccess_raw import models from .base import BaseAdmin @admin.register(models.RawDataVersion) class RawDataVersionAdmin(BaseAdmin): """ Custom admin for the RawDataVersion model. """ list_display = ( "id", "release_datetime", "pretty_download_size", "download_file_count", "download_record_count", "clean_file_count", "clean_record_count", "pretty_clean_size", ) list_display_links = ('release_datetime',) list_filter = ("release_datetime",) @admin.register(models.RawDataFile) class RawDataFileAdmin(BaseAdmin): """ Custom admin for the RawDataFile model. """ list_display = ( "id", "version", "file_name", "download_records_count", "clean_records_count", "load_records_count", "error_count" ) list_display_links = ('id', 'file_name',) list_filter = ("version__release_datetime",)
Cut dupe admin display fields
Cut dupe admin display fields
Python
mit
california-civic-data-coalition/django-calaccess-raw-data
--- +++ @@ -22,8 +22,6 @@ "clean_file_count", "clean_record_count", "pretty_clean_size", - "download_file_count", - "clean_record_count" ) list_display_links = ('release_datetime',) list_filter = ("release_datetime",)
7fc4e7382665cf9eac4d19efcf9641ad57271e87
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') class Meta: ordering = ['name'] def __str__(self): return self.name class Startup(models.Model): name = models.CharField( max_length=31, db_index=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') description = models.TextField() founded_date = models.DateField( 'date founded') contact = models.EmailField() website = models.URLField(max_length=255) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField('date published') link = models.URLField(max_length=255) startup = models.ForeignKey(Startup) def __str__(self): return "{}: {}".format( self.startup, self.title)
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField( max_length=31, unique=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') class Meta: ordering = ['name'] def __str__(self): return self.name class Startup(models.Model): name = models.CharField( max_length=31, db_index=True) slug = models.SlugField( max_length=31, unique=True, help_text='A label for URL config.') description = models.TextField() founded_date = models.DateField( 'date founded') contact = models.EmailField() website = models.URLField(max_length=255) tags = models.ManyToManyField(Tag) class Meta: ordering = ['name'] get_latest_by = 'founded_date' def __str__(self): return self.name class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField('date published') link = models.URLField(max_length=255) startup = models.ForeignKey(Startup) def __str__(self): return "{}: {}".format( self.startup, self.title)
Declare Meta class in Startup model.
Ch03: Declare Meta class in Startup model. [skip ci]
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
--- +++ @@ -34,6 +34,10 @@ website = models.URLField(max_length=255) tags = models.ManyToManyField(Tag) + class Meta: + ordering = ['name'] + get_latest_by = 'founded_date' + def __str__(self): return self.name
bcb4d14e7be413a08ca9c3f98656ff7b2bcb3d7d
test/test_wikilinks.py
test/test_wikilinks.py
from tiddlywebplugins.markdown import render from tiddlyweb.model.tiddler import Tiddler sample = """# Hello This is WikiLink * List * List """ sample_linked = """ This is WikiLink and this is not: [NotLink](http://example.com). This forthcoming in camel case but actually a link [label](http://example.org/CamelCase) This is (HtmlJavascript in parens). This is (parens around HtmlJavascript). """ def test_no_wiki(): tiddler = Tiddler('hello') tiddler.text = sample environ = {} output = render(tiddler, environ) assert '<h1>' in output assert '<li>' in output assert 'href' not in output environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}} output = render(tiddler, environ) assert 'href' in output assert '<a href="WikiLink">' in output assert '>WikiLink</a>' in output tiddler.text = sample_linked output = render(tiddler, environ) assert '"NotLink"' not in output assert '<a href="http://example.org/CamelCase">label</a>' in output print output
from tiddlywebplugins.markdown import render from tiddlyweb.model.tiddler import Tiddler sample = """# Hello This is WikiLink * List * List """ sample_linked = """ This is WikiLink and this is not: [NotLink](http://example.com). This forthcoming in camel case but actually a link [label](http://example.org/CamelCase) This is (HtmlJavascript in parens). This is (parens around HtmlJavascript). """ def test_no_wiki(): tiddler = Tiddler('hello') tiddler.text = sample environ = {} output = render(tiddler, environ) assert '<h1>' in output assert '<li>' in output assert 'href' not in output environ = {'tiddlyweb.config': {'markdown.wiki_link_base': ''}} output = render(tiddler, environ) assert 'href' in output assert '<a href="WikiLink">' in output assert '>WikiLink</a>' in output tiddler.text = sample_linked output = render(tiddler, environ) assert '"NotLink"' not in output assert '<a href="http://example.org/CamelCase">label</a>' in output assert '(<a href="HtmlJavascript">HtmlJavascript</a> in parens)' in output assert '(parens around <a href="HtmlJavascript">HtmlJavascript</a>)' in output
Write forgotten test replace debugging output.
Write forgotten test replace debugging output.
Python
bsd-2-clause
tiddlyweb/tiddlywebplugins.markdown
--- +++ @@ -44,4 +44,6 @@ assert '"NotLink"' not in output assert '<a href="http://example.org/CamelCase">label</a>' in output - print output + assert '(<a href="HtmlJavascript">HtmlJavascript</a> in parens)' in output + assert '(parens around <a href="HtmlJavascript">HtmlJavascript</a>)' in output +
8d50846847852741410463d98de2c4f9e5fea844
zaqar_ui/content/queues/urls.py
zaqar_ui/content/queues/urls.py
# Copyright 2015 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf import urls from zaqar_ui.content.queues import views urlpatterns = urls.patterns( 'zaqar_ui.content.queues', urls.url(r'^$', views.IndexView.as_view(), name='index'), )
# Copyright 2015 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.conf import urls from zaqar_ui.content.queues import views urlpatterns = [ urls.url(r'^$', views.IndexView.as_view(), name='index'), ]
Update URLs to Django 1.8 style
Update URLs to Django 1.8 style django.conf.urls.patterns() is deprecated since 1.8. We should not use patterns(), so this patch updates URLs to 1.8 style. Change-Id: I6f2b6f44d843ca5e0cdb5db9828df94fa4df5f88 Closes-Bug: #1539354
Python
apache-2.0
openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui
--- +++ @@ -17,7 +17,6 @@ from zaqar_ui.content.queues import views -urlpatterns = urls.patterns( - 'zaqar_ui.content.queues', +urlpatterns = [ urls.url(r'^$', views.IndexView.as_view(), name='index'), -) +]
1d2a62b87b98513bd84a0ae1433781157cb45f70
admin.py
admin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from djurk.models import HIT class HIT_Admin(admin.ModelAdmin): list_display = ( 'creation_time', 'hit_id', 'hit_type_id', 'title', 'reward' ) list_filter = ( 'creation_time', 'hit_status', 'hit_review_status', ) search_fields = ( 'hit_id', 'hit_type_id', 'title', 'description', 'keyword', ) admin.site.register(HIT, HIT_Admin)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from djurk.models import HIT class HIT_Admin(admin.ModelAdmin): date_hierarchy = 'creation_time' fieldsets = ( (None, { 'fields': (('hit_id','hit_type_id'), ('creation_time', 'hit_status'), ('title', 'keywords', 'description'), 'reward', 'requester_annotation', ), }), ('HIT Details', { 'classes': ('collapse',), 'fields': ( 'lifetime_in_seconds', 'auto_approval_delay_in_seconds', 'number_of_similar_hits', 'hit_review_status', ) }), ('Assignment Overview', { 'classes': ('collapse',), 'fields': ( 'max_assignments', 'assignment_duration_in_seconds', 'number_of_assignments_pending', 'number_of_assignments_available', 'number_of_assignments_completed', ) }), ) list_display = ( 'creation_time', 'hit_id', 'hit_type_id', 'title', 'reward' ) readonly_fields = ( 'creation_time', 'hit_id', 'hit_type_id', 'hit_status', 'hit_review_status', ) list_display_links = list_display list_filter = ( 'hit_status', 'hit_review_status', 'creation_time', ) read_only_fields = ('creation_time',) search_fields = ( 'hit_id', 'hit_type_id', 'title', 'description', 'keyword', ) admin.site.register(HIT, HIT_Admin)
Customize HIT Admin to "fit your brain"
Customize HIT Admin to "fit your brain"
Python
bsd-3-clause
glenjarvis/djurk
--- +++ @@ -6,6 +6,36 @@ from djurk.models import HIT class HIT_Admin(admin.ModelAdmin): + date_hierarchy = 'creation_time' + fieldsets = ( + (None, { + 'fields': (('hit_id','hit_type_id'), + ('creation_time', 'hit_status'), + ('title', 'keywords', 'description'), + 'reward', + 'requester_annotation', + ), + }), + ('HIT Details', { + 'classes': ('collapse',), + 'fields': ( + 'lifetime_in_seconds', + 'auto_approval_delay_in_seconds', + 'number_of_similar_hits', + 'hit_review_status', + ) + }), + ('Assignment Overview', { + 'classes': ('collapse',), + 'fields': ( + 'max_assignments', + 'assignment_duration_in_seconds', + 'number_of_assignments_pending', + 'number_of_assignments_available', + 'number_of_assignments_completed', + ) + }), + ) list_display = ( 'creation_time', 'hit_id', @@ -13,11 +43,20 @@ 'title', 'reward' ) - list_filter = ( + readonly_fields = ( 'creation_time', + 'hit_id', + 'hit_type_id', 'hit_status', 'hit_review_status', ) + list_display_links = list_display + list_filter = ( + 'hit_status', + 'hit_review_status', + 'creation_time', + ) + read_only_fields = ('creation_time',) search_fields = ( 'hit_id', 'hit_type_id',
053bfa79b54a95d405d6401c86dcce3c6065bf32
appium/conftest.py
appium/conftest.py
import os import pytest from appium import webdriver @pytest.fixture(scope='function') def driver(request): return get_driver(request, default_capabilities()) @pytest.fixture(scope='function') def no_reset_driver(request): desired_caps = default_capabilities() desired_caps['noReset'] = True return get_driver(request, desired_caps) def get_driver(request, desired_caps): _driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps) request.addfinalizer(_driver.quit) return _driver def default_capabilities(): app = os.path.abspath('aws/Build/Products/Release-iphonesimulator/AwesomeProject.app') screenshot_folder = os.getenv('SCREENSHOT_PATH', '') desired_caps = {} if screenshot_folder == '': desired_caps['platformName'] = 'iOS' desired_caps['platformVersion'] = '10.3' desired_caps['deviceName'] = 'iPhone Simulator' desired_caps['app'] = app return desired_caps
import os import pytest from appium import webdriver @pytest.fixture(scope='function') def driver(request): return get_driver(request, default_capabilities()) @pytest.fixture(scope='function') def no_reset_driver(request): desired_caps = default_capabilities() desired_caps['noReset'] = (runs_on_aws() == True and False or True) return get_driver(request, desired_caps) def get_driver(request, desired_caps): _driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps) request.addfinalizer(_driver.quit) return _driver def runs_on_aws(): return os.getenv('SCREENSHOT_PATH', False) != False def default_capabilities(): app = os.path.abspath('aws/Build/Products/Release-iphonesimulator/AwesomeProject.app') desired_caps = {} if runs_on_aws() == False: desired_caps['platformName'] = 'iOS' desired_caps['platformVersion'] = '10.3' desired_caps['deviceName'] = 'iPhone Simulator' desired_caps['app'] = app return desired_caps
Remove no reset for devicefarm
Remove no reset for devicefarm
Python
mit
getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry
--- +++ @@ -11,7 +11,7 @@ @pytest.fixture(scope='function') def no_reset_driver(request): desired_caps = default_capabilities() - desired_caps['noReset'] = True + desired_caps['noReset'] = (runs_on_aws() == True and False or True) return get_driver(request, desired_caps) def get_driver(request, desired_caps): @@ -23,14 +23,15 @@ return _driver +def runs_on_aws(): + return os.getenv('SCREENSHOT_PATH', False) != False + def default_capabilities(): app = os.path.abspath('aws/Build/Products/Release-iphonesimulator/AwesomeProject.app') - screenshot_folder = os.getenv('SCREENSHOT_PATH', '') - desired_caps = {} - if screenshot_folder == '': + if runs_on_aws() == False: desired_caps['platformName'] = 'iOS' desired_caps['platformVersion'] = '10.3' desired_caps['deviceName'] = 'iPhone Simulator'
8b8e206c21d08fee74fd43dc4b7e4d1d95a93060
sconsole/cmdbar.py
sconsole/cmdbar.py
''' Define the command bar ''' # Import third party libs import urwid class CommandBar(object): ''' The object to manage the command bar ''' def __init__(self, opts): self.opts = opts self.tgt_txt = urwid.Text('Target') self.tgt_edit = urwid.Edit() self.fun_txt = urwid.Text('Function') self.fun_edit = urwid.Edit() self.arg_txt = urwid.Text('Arguments') self.arg_edit = urwid.Edit() self.go_button = urwid.Button('GO!') self.grid = urwid.GridFlow( [self.tgt_txt, self.tgt_edit, self.fun_txt, self.fun_edit, self.arg_txt, self.arg_edit, self.go_button], cell_width=10, h_sep=1, v_sep=1, align='left')
''' Define the command bar ''' # Import third party libs import urwid # Import salt libs import salt.client class CommandBar(object): ''' The object to manage the command bar ''' def __init__(self, opts): self.opts = opts self.local = salt.client.LocalClient(mopts=opts) self.tgt_txt = urwid.Text('Target') self.tgt_edit = urwid.Edit() self.fun_txt = urwid.Text('Function') self.fun_edit = urwid.Edit() self.arg_txt = urwid.Text('Arguments') self.arg_edit = urwid.Edit() self.go_button = urwid.Button('GO!', self.run_command) self.grid = urwid.GridFlow( [self.tgt_txt, self.tgt_edit, self.fun_txt, self.fun_edit, self.arg_txt, self.arg_edit, self.go_button], cell_width=10, h_sep=1, v_sep=1, align='left') def run_command(self, button, user_data): ''' Execute the corresponding salt command ''' tgt = self.tgt_edit.get_edit_text() fun = self.fun_edit.get_edit_text() args = self.arg_edit.get_edit_text().split() self.local.cmd_async(tgt, fun, args)
Add functionality to the go button
Add functionality to the go button
Python
apache-2.0
saltstack/salt-console
--- +++ @@ -3,6 +3,9 @@ ''' # Import third party libs import urwid + +# Import salt libs +import salt.client class CommandBar(object): @@ -11,13 +14,14 @@ ''' def __init__(self, opts): self.opts = opts + self.local = salt.client.LocalClient(mopts=opts) self.tgt_txt = urwid.Text('Target') self.tgt_edit = urwid.Edit() self.fun_txt = urwid.Text('Function') self.fun_edit = urwid.Edit() self.arg_txt = urwid.Text('Arguments') self.arg_edit = urwid.Edit() - self.go_button = urwid.Button('GO!') + self.go_button = urwid.Button('GO!', self.run_command) self.grid = urwid.GridFlow( [self.tgt_txt, self.tgt_edit, @@ -30,3 +34,12 @@ h_sep=1, v_sep=1, align='left') + + def run_command(self, button, user_data): + ''' + Execute the corresponding salt command + ''' + tgt = self.tgt_edit.get_edit_text() + fun = self.fun_edit.get_edit_text() + args = self.arg_edit.get_edit_text().split() + self.local.cmd_async(tgt, fun, args)
f4170ec0cff71e8bcce834bbf8f4336410d45e76
klab/cluster/__init__.py
klab/cluster/__init__.py
#!/usr/bin/env python2 def is_this_chef(): from socket import gethostname return gethostname() == 'chef.compbio.ucsf.edu' def require_chef(): if not is_this_chef(): raise SystemExit("This script must be run on chef.") def require_qsub(): import os, subprocess try: command = 'qsub', '-help' devnull = open(os.devnull) subprocess.Popen(command, stdout=devnull, stderr=devnull).communicate() except OSError as e: if e.errno == os.errno.ENOENT: return False return True
#!/usr/bin/env python2 def is_this_chef(): from socket import gethostname return gethostname() == 'chef.compbio.ucsf.edu' def require_chef(): if not is_this_chef(): raise SystemExit("This script must be run on chef.") def require_qsub(): import os, subprocess try: command = 'qsub', '-help' devnull = open(os.devnull) subprocess.Popen(command, stdout=devnull, stderr=devnull).communicate() except OSError as e: if e.errno == os.errno.ENOENT: print "'qsub' not found. Are you logged onto the cluster?" raise SystemExit
Make require_qsub() crash if qsub isn't found.
Make require_qsub() crash if qsub isn't found.
Python
mit
Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab
--- +++ @@ -17,8 +17,7 @@ subprocess.Popen(command, stdout=devnull, stderr=devnull).communicate() except OSError as e: if e.errno == os.errno.ENOENT: - return False - - return True + print "'qsub' not found. Are you logged onto the cluster?" + raise SystemExit
65fb294c17130985e6549702a1df728126de8cb0
addon.py
addon.py
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from xbmctorrent import plugin if __name__ == '__main__': plugin.run()
import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from xbmctorrent import plugin if __name__ == '__main__': plugin.run()
Make sure we use our own vendored packages
Make sure we use our own vendored packages
Python
apache-2.0
neno1978/xbmctorrent
--- +++ @@ -1,5 +1,5 @@ import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) +sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'resources', 'site-packages')) from xbmctorrent import plugin
0cc89fe31729a485a0e055b343acfde3d71745d7
apps/metricsmanager/api.py
apps/metricsmanager/api.py
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response("No formula provided") try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
from rest_framework.views import APIView from rest_framework.reverse import reverse from rest_framework.response import Response from rest_framework import generics, status from django.core.exceptions import ValidationError from .models import * from .serializers import * from .formula import validate_formula class MetricsBase(APIView): def get(self, request, format=None): """ :type request: Request :param request: :return: """ result = { "Metrics": reverse('metrics-create', request=request) } return Response(result) class FormulaValidate(APIView): def get(self, request): if "formula" not in request.QUERY_PARAMS: return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT) except ValidationError as e: return Response({ "formula": e.message }, status=status.HTTP_400_BAD_REQUEST) class MetricsCreate(generics.CreateAPIView): model = Metric serializer_class = MetricSerializer class MetricsDetail(generics.RetrieveAPIView): model = Metric serializer_class = MetricSerializer
Fix error format of check formula endpoint
Fix error format of check formula endpoint
Python
agpl-3.0
mmilaprat/policycompass-services,almey/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services,almey/policycompass-services,policycompass/policycompass-services,almey/policycompass-services,mmilaprat/policycompass-services,policycompass/policycompass-services
--- +++ @@ -25,7 +25,7 @@ def get(self, request): if "formula" not in request.QUERY_PARAMS: - return Response("No formula provided") + return Response({ "formula": "Can not be empty"}, status=status.HTTP_400_BAD_REQUEST) try: validate_formula(request.QUERY_PARAMS["formula"]) return Response(status=status.HTTP_204_NO_CONTENT)
a8601d8a17c9ba8e87b8336870e0d52f79e0ffa2
indra/tests/test_omnipath.py
indra/tests/test_omnipath.py
from __future__ import unicode_literals from builtins import dict, str from indra.statements import Phosphorylation from indra.databases import omnipath as op def test_query_ptms(): stmts = op.get_ptms(['Q13873']) assert len(stmts) == 1 assert isinstance(stmts[0], Phosphorylation) assert stmts[0].enz.name == 'CSNK2A1' assert stmts[0].sub.name == 'BMPR2' assert stmts[0].residue == 'S' assert stmts[0].position == '757'
import requests from indra.sources.omnipath import OmniPathModificationProcessor,\ OmniPathLiganReceptorProcessor from indra.sources.omnipath.api import op_url from indra.statements import Agent, Phosphorylation from indra.preassembler.grounding_mapper import GroundingMapper BRAF_UPID = 'P15056' JAK2_UPID = 'O60674' BRAF_AG = Agent(None, db_refs={'UP': BRAF_UPID}) GroundingMapper.standardize_agent_name(BRAF_AG) JAK2_AG = Agent(None, db_refs={'UP': JAK2_UPID}) GroundingMapper.standardize_agent_name(JAK2_AG) def test_omnipath_web_api(): query_url = '%s/queries' res = requests.get(query_url) assert res.status_code == 200 def test_query_ptms(): stmts = op.get_ptms(['Q13873']) assert len(stmts) == 1 assert isinstance(stmts[0], Phosphorylation) assert stmts[0].enz.name == 'CSNK2A1' assert stmts[0].sub.name == 'BMPR2' assert stmts[0].residue == 'S' assert stmts[0].position == '757'
Update imports, test general web api
Update imports, test general web api
Python
bsd-2-clause
johnbachman/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy
--- +++ @@ -1,7 +1,22 @@ -from __future__ import unicode_literals -from builtins import dict, str -from indra.statements import Phosphorylation -from indra.databases import omnipath as op +import requests +from indra.sources.omnipath import OmniPathModificationProcessor,\ + OmniPathLiganReceptorProcessor +from indra.sources.omnipath.api import op_url +from indra.statements import Agent, Phosphorylation +from indra.preassembler.grounding_mapper import GroundingMapper + +BRAF_UPID = 'P15056' +JAK2_UPID = 'O60674' +BRAF_AG = Agent(None, db_refs={'UP': BRAF_UPID}) +GroundingMapper.standardize_agent_name(BRAF_AG) +JAK2_AG = Agent(None, db_refs={'UP': JAK2_UPID}) +GroundingMapper.standardize_agent_name(JAK2_AG) + + +def test_omnipath_web_api(): + query_url = '%s/queries' + res = requests.get(query_url) + assert res.status_code == 200 def test_query_ptms(): stmts = op.get_ptms(['Q13873'])
2083c0079a70783deff54a7acd6f3ef6bba25302
tests/test_pyglmnet.py
tests/test_pyglmnet.py
import numpy as np import scipy.sparse as sps from sklearn.preprocessing import StandardScaler from numpy.testing import assert_allclose from pyglmnet import GLM def test_glmnet(): """Test glmnet.""" glm = GLM(distr='poisson') scaler = StandardScaler() n_samples, n_features = 10000, 100 density = 0.1 # coefficients beta0 = np.random.rand() beta = sps.rand(n_features, 1, density=density).toarray() X_train = np.random.normal(0.0, 1.0, [n_samples, n_features]) y_train = glm.simulate(beta0, beta, X_train) X_train = scaler.fit_transform(X_train) glm.fit(X_train, y_train) beta_ = glm.fit_params[-2]['beta'][:] assert_allclose(beta[:], beta_, atol=0.1) # check fit density_ = np.sum(beta_ > 0.1) / float(n_features) assert_allclose(density_, density, atol=0.05) # check density
import numpy as np import scipy.sparse as sps from sklearn.preprocessing import StandardScaler from numpy.testing import assert_allclose from pyglmnet import GLM def test_glmnet(): """Test glmnet.""" glm = GLM(distr='poisson') scaler = StandardScaler() n_samples, n_features = 10000, 100 density = 0.1 # coefficients beta0 = np.random.rand() beta = sps.rand(n_features, 1, density=density).toarray() X_train = np.random.normal(0.0, 1.0, [n_samples, n_features]) y_train = glm.simulate(beta0, beta, X_train) X_train = scaler.fit_transform(X_train) glm.fit(X_train, y_train) beta_ = glm.fit_[-2]['beta'][:] assert_allclose(beta[:], beta_, atol=0.1) # check fit density_ = np.sum(beta_ > 0.1) / float(n_features) assert_allclose(density_, density, atol=0.05) # check density def test_multinomial_gradient(): """Gradient of intercept params is different""" glm = GLM(distr='multinomial') X = np.array([[1,2,3], [4,5,6]]) y = np.array([1,2]) beta = np.zeros([4, 2]) grad_beta0, grad_beta = glm.grad_L2loss(beta[0], beta[1:], 0, X, y) assert grad_beta0[0] != grad_beta0[1]
Fix glmnet test and add multinomial gradient test
Fix glmnet test and add multinomial gradient test
Python
mit
the872/pyglmnet,glm-tools/pyglmnet,pavanramkumar/pyglmnet
--- +++ @@ -24,7 +24,16 @@ X_train = scaler.fit_transform(X_train) glm.fit(X_train, y_train) - beta_ = glm.fit_params[-2]['beta'][:] + beta_ = glm.fit_[-2]['beta'][:] assert_allclose(beta[:], beta_, atol=0.1) # check fit density_ = np.sum(beta_ > 0.1) / float(n_features) assert_allclose(density_, density, atol=0.05) # check density + +def test_multinomial_gradient(): + """Gradient of intercept params is different""" + glm = GLM(distr='multinomial') + X = np.array([[1,2,3], [4,5,6]]) + y = np.array([1,2]) + beta = np.zeros([4, 2]) + grad_beta0, grad_beta = glm.grad_L2loss(beta[0], beta[1:], 0, X, y) + assert grad_beta0[0] != grad_beta0[1]
2296ef02345f51666ff6653abe372e7965ef361c
categories_i18n/admin.py
categories_i18n/admin.py
from django.contrib import admin from mptt.admin import MPTTModelAdmin from mptt.forms import MPTTAdminForm from parler.admin import TranslatableAdmin from .models import Category from parler.forms import TranslatableModelForm class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm): """ Form for categories, both MPTT + translatable. """ pass class CategoryAdmin(MPTTModelAdmin, TranslatableAdmin): """ Admin page for categories. """ list_display = ('title', 'slug') search_fields = ('translations__title', 'translations__slug') form = CategoryAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug', 'parent'), }), ) def get_prepopulated_fields(self, request, obj=None): # Needed for django-parler return {'slug': ('title',)} admin.site.register(Category, CategoryAdmin)
from django.contrib import admin from mptt.admin import MPTTModelAdmin from mptt.forms import MPTTAdminForm from parler.admin import TranslatableAdmin from .models import Category from parler.forms import TranslatableModelForm class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm): """ Form for categories, both MPTT + translatable. """ pass class CategoryAdmin(MPTTModelAdmin, TranslatableAdmin): """ Admin page for categories. """ list_display = ('title', 'slug') mptt_indent_field = 'title' # be explicit for MPTT search_fields = ('translations__title', 'translations__slug') form = CategoryAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug', 'parent'), }), ) def get_prepopulated_fields(self, request, obj=None): # Needed for django-parler return {'slug': ('title',)} admin.site.register(Category, CategoryAdmin)
Set `mptt_indent_field` explicitly for proper MPTT list columns
Set `mptt_indent_field` explicitly for proper MPTT list columns
Python
apache-2.0
edoburu/django-categories-i18n,edoburu/django-categories-i18n
--- +++ @@ -18,6 +18,7 @@ Admin page for categories. """ list_display = ('title', 'slug') + mptt_indent_field = 'title' # be explicit for MPTT search_fields = ('translations__title', 'translations__slug') form = CategoryAdminForm
70d3bf1043af965da56339ce1c50b258f184ccb2
lib/bio.py
lib/bio.py
"""Utilities for working with sequences.""" import re from Bio import SeqIO CODON_LEN = 3 COMPLEMENT = str.maketrans('ACGTUWSMKRYBDHVNXacgtuwsmkrybdhvnx', 'TGCAAWSKMYRVHDBNXtgcaawskmyrvhdbnx') IS_PROTEIN = re.compile(r'[EFILPQ]', re.IGNORECASE) def reverse_complement(seq): """Reverse complement a nucleotide sequence. We added some wildcards.""" return seq.translate(COMPLEMENT)[::-1] def is_protein(seq): """Check if the sequence a protein.""" return IS_PROTEIN.search(seq) def fasta_file_has_protein(query_files): """ Search for protein characters in a fasta file. If the user has told us that we have a protein then return that. """ for query_file in query_files: with open(query_file) as in_file: for query in SeqIO.parse(in_file, 'fasta'): if is_protein(str(query.seq)): return True return False
"""Utilities for working with sequences.""" import re from Bio import SeqIO CODON_LEN = 3 COMPLEMENT = str.maketrans('ACGTUWSMKRYBDHVNXacgtuwsmkrybdhvnx-', 'TGCAAWSKMYRVHDBNXtgcaawskmyrvhdbnx-') IS_PROTEIN = re.compile(r'[EFILPQ]', re.IGNORECASE) def reverse_complement(seq): """Reverse complement a nucleotide sequence. We added some wildcards.""" return seq.translate(COMPLEMENT)[::-1] def is_protein(seq): """Check if the sequence a protein.""" return IS_PROTEIN.search(seq) def fasta_file_has_protein(query_files): """ Search for protein characters in a fasta file. If the user has told us that we have a protein then return that. """ for query_file in query_files: with open(query_file) as in_file: for query in SeqIO.parse(in_file, 'fasta'): if is_protein(str(query.seq)): return True return False
Add gaps "-" to reverse complement function
Add gaps "-" to reverse complement function
Python
bsd-3-clause
juliema/aTRAM
--- +++ @@ -5,8 +5,8 @@ CODON_LEN = 3 -COMPLEMENT = str.maketrans('ACGTUWSMKRYBDHVNXacgtuwsmkrybdhvnx', - 'TGCAAWSKMYRVHDBNXtgcaawskmyrvhdbnx') +COMPLEMENT = str.maketrans('ACGTUWSMKRYBDHVNXacgtuwsmkrybdhvnx-', + 'TGCAAWSKMYRVHDBNXtgcaawskmyrvhdbnx-') IS_PROTEIN = re.compile(r'[EFILPQ]', re.IGNORECASE)
c0dc0c644fd8912d58deb416955e85259d22618e
tests/github_controller/test_request_parsing.py
tests/github_controller/test_request_parsing.py
import pytest from app.controllers.github_controller import GithubController pytestmark = pytest.mark.asyncio async def test_get_req_json(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_json(mock_request) == 'json' async def test_get_req_event_header(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_event_header(mock_request) == 'event'
import pytest from app.controllers.github_controller import GithubController pytestmark = pytest.mark.asyncio async def test_get_req_json(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_json(mock_request) == {'json': 'json'} async def test_get_req_event_header(gh_sut: GithubController, mock_request): assert await gh_sut.get_request_event_header(mock_request) == 'event'
Fix test in request parsing
Fix test in request parsing
Python
mit
futuresimple/triggear
--- +++ @@ -6,7 +6,7 @@ async def test_get_req_json(gh_sut: GithubController, mock_request): - assert await gh_sut.get_request_json(mock_request) == 'json' + assert await gh_sut.get_request_json(mock_request) == {'json': 'json'} async def test_get_req_event_header(gh_sut: GithubController, mock_request):
8982d3f5ea40b688ec7e1da18403d89ab2994a95
comics/comics/yamac.py
comics/comics/yamac.py
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date): pass
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "you and me and cats" language = "en" url = "http://strawberry-pie.net/SA/" start_date = "2009-07-01" rights = "bubble" active = False class Crawler(CrawlerBase): time_zone = "US/Pacific" def crawl(self, pub_date): pass
Remove history capable date for "you and me and cats"
Remove history capable date for "you and me and cats"
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics
--- +++ @@ -12,7 +12,6 @@ class Crawler(CrawlerBase): - history_capable_days = 365 time_zone = "US/Pacific" def crawl(self, pub_date):
26861b183085e8fe2c7c21f4e3631ddd7d30e5e8
csibe.py
csibe.py
#!/usr/bin/env python import os import subprocess import unittest csibe_path = os.path.dirname(os.path.realpath(__file__)) build_directory = "build" if not os.path.isdir(build_directory): os.makedirs(build_directory) os.chdir(build_directory) subprocess.call(["cmake", csibe_path])
#!/usr/bin/env python import argparse import os import subprocess import sys parser = argparse.ArgumentParser() parser.add_argument("-j", "--jobs", type=int, default=1, help="number of jobs for make") args = parser.parse_args() make_jobs = args.jobs csibe_path = os.path.dirname(os.path.realpath(__file__)) build_directory = "build" if not os.path.isdir(build_directory): os.makedirs(build_directory) os.chdir(build_directory) cmake_return_value = subprocess.call(["cmake", csibe_path]) if cmake_return_value: sys.exit(cmake_return_value) make_return_value = subprocess.call(["make", "-j{}".format(make_jobs)]) if make_return_value: sys.exit(make_return_value) make_size_return_value = subprocess.call(["make", "size"]) if make_size_return_value: sys.exit(make_size_return_value)
Add logic and error-handling for CMake and make invocations
Add logic and error-handling for CMake and make invocations
Python
bsd-3-clause
szeged/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,bgabor666/csibe,loki04/csibe,loki04/csibe,loki04/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,bgabor666/csibe,loki04/csibe,loki04/csibe,szeged/csibe,szeged/csibe,loki04/csibe,loki04/csibe,szeged/csibe
--- +++ @@ -1,8 +1,15 @@ #!/usr/bin/env python +import argparse import os import subprocess -import unittest +import sys + +parser = argparse.ArgumentParser() +parser.add_argument("-j", "--jobs", type=int, default=1, help="number of jobs for make") +args = parser.parse_args() + +make_jobs = args.jobs csibe_path = os.path.dirname(os.path.realpath(__file__)) build_directory = "build" @@ -12,5 +19,15 @@ os.chdir(build_directory) -subprocess.call(["cmake", csibe_path]) +cmake_return_value = subprocess.call(["cmake", csibe_path]) +if cmake_return_value: + sys.exit(cmake_return_value) +make_return_value = subprocess.call(["make", "-j{}".format(make_jobs)]) +if make_return_value: + sys.exit(make_return_value) + +make_size_return_value = subprocess.call(["make", "size"]) +if make_size_return_value: + sys.exit(make_size_return_value) +
f87bab8a808e4bda3b3b7482633eaca069682b9e
build.py
build.py
# -*- coding: utf-8 -*- import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.1', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1'}}, )
# -*- coding: utf-8 -*- import sys from cx_Freeze import setup, Executable base = None if sys.platform == "win32": base = "Win32GUI" executables = [ Executable('blockcheck.py', base=base) ] setup(name='blockcheck', version='0.0.5', description='BlockCheck', executables=executables, options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, )
Include all the files from dns module and bump version
Include all the files from dns module and bump version
Python
mit
Acharvak/blockcheck,Renji/blockcheck,ValdikSS/blockcheck
--- +++ @@ -11,8 +11,8 @@ ] setup(name='blockcheck', - version='0.1', + version='0.0.5', description='BlockCheck', executables=executables, - options = {'build_exe': {'init_script':'Console', 'compressed':'1'}}, + options = {'build_exe': {'init_script':'Console', 'compressed':'1', 'packages':'dns'}}, )
89c005e2fd7d7f7727ba225cc20789fea992b1d4
backend/scripts/mktemplate.py
backend/scripts/mktemplate.py
#!/usr/bin/env python import json import rethinkdb as r import sys import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) parser.add_option("-f", "--file", dest="filename", help="json file", type="string") (options, args) = parser.parse_args() if options.filename is None: print "You must specify json file" sys.exit(1) conn = r.connect('localhost', int(options.port), db='materialscommons') json_data = open(options.filename) data = json.load(json_data) existing = r.table('templates').get(data['id']).run(conn) if existing: r.table('templates').get(data['id']).delete().run(conn) r.table('templates').insert(data).run(conn) print 'template deleted and re-inserted into the database' else: r.table('templates').insert(data).run(conn) print 'template inserted into the database'
#!/usr/bin/env python import json import rethinkdb as r import sys import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", help="rethinkdb port", default=30815) parser.add_option("-f", "--file", dest="filename", help="json file", type="string") (options, args) = parser.parse_args() if options.filename is None: print "You must specify json file" sys.exit(1) conn = r.connect('localhost', int(options.port), db='materialscommons') json_data = open(options.filename) print "Loading template file: %s" % (options.filename) data = json.load(json_data) existing = r.table('templates').get(data['id']).run(conn) if existing: r.table('templates').get(data['id']).delete().run(conn) r.table('templates').insert(data).run(conn) print 'template deleted and re-inserted into the database' else: r.table('templates').insert(data).run(conn) print 'template inserted into the database'
Update script to show which file it is loading.
Update script to show which file it is loading.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
--- +++ @@ -17,6 +17,7 @@ sys.exit(1) conn = r.connect('localhost', int(options.port), db='materialscommons') json_data = open(options.filename) + print "Loading template file: %s" % (options.filename) data = json.load(json_data) existing = r.table('templates').get(data['id']).run(conn) if existing:
6ac4764790526f435ffc6337145439d710dd455f
virtualenv/__init__.py
virtualenv/__init__.py
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) from virtualenv.core import create __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", "create", ]
from __future__ import absolute_import, division, print_function from virtualenv.__about__ import ( __author__, __copyright__, __email__, __license__, __summary__, __title__, __uri__, __version__ ) from virtualenv.core import create def create_environment( home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, never_download=False, no_setuptools=False, no_pip=False, symlink=True ): create( home_dir, system_site_packages=site_packages, clear=clear, prompt=prompt or "", extra_search_dirs=search_dirs, setuptools=not no_setuptools, pip=not no_pip ) __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", "create", ]
Add a backwards compatible create_environment.
Add a backwards compatible create_environment.
Python
mit
ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv
--- +++ @@ -7,6 +7,23 @@ from virtualenv.core import create +def create_environment( + home_dir, + site_packages=False, clear=False, + unzip_setuptools=False, + prompt=None, search_dirs=None, never_download=False, + no_setuptools=False, no_pip=False, symlink=True +): + create( + home_dir, + system_site_packages=site_packages, + clear=clear, + prompt=prompt or "", + extra_search_dirs=search_dirs, + setuptools=not no_setuptools, + pip=not no_pip + ) + __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__",
7822687bb78cbe422af0d707a1ed7fc94011628d
castor/tasks.py
castor/tasks.py
from celery import Celery from settings import SETTINGS import requests HOOKS = SETTINGS.get('hooks', []) CELERY_SETTINGS = SETTINGS.get('celery', {}) app = Celery() app.conf.update(**CELERY_SETTINGS) @app.task def dispatch_event(event): event_repr = '%s:%s' % (event['id'][:10], event['status']) for url in HOOKS: dispatch_tuple = (event_repr, url) print '[DISPATCH START] Dispatching event %s --> %s' % dispatch_tuple try: response = requests.post(url, data=event) response_tuple = (response.status_code, response.reason) if response.status_code >= 400: print ' [FAILURE] %s: %s' % response_tuple else: print ' [SUCCESS] %s: %s' % response_tuple except Exception as e: print ' [ERROR] Exception: %s' % e print '[DISPATCH END] %s --> %s' % dispatch_tuple
from celery import Celery from settings import SETTINGS import requests HOOKS = SETTINGS.get('hooks', []) CELERY_SETTINGS = SETTINGS.get('celery', {}) app = Celery() app.conf.update(**CELERY_SETTINGS) @app.task def dispatch_event(event): event_repr = '%s:%s' % (event['id'][:10], event['status']) for url in HOOKS: dispatch_tuple = (event_repr, url) print '[DISPATCH START] Dispatching event %s --> %s' % dispatch_tuple try: response = requests.post(url, data=event) response_tuple = (response.status_code, response.reason) if response.status_code >= 400: print ' [FAILURE] %s: %s' % response_tuple else: print ' [SUCCESS] %s: %s' % response_tuple except Exception as e: print ' [ERROR] Exception: %s' % e print '[DISPATCH END] %s --> %s' % dispatch_tuple return event
Return event dictionary at the end of the task.
Return event dictionary at the end of the task.
Python
mit
sourcelair/castor
--- +++ @@ -27,3 +27,4 @@ except Exception as e: print ' [ERROR] Exception: %s' % e print '[DISPATCH END] %s --> %s' % dispatch_tuple + return event
84d743476261d30b352e3bfc103d76e7e8350b4c
tests/test_urls.py
tests/test_urls.py
""" Testing of project level URLs. """ from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase from urltools import compare class TestURLs(TestCase): """Verify project level URL configuration.""" def test_cas_enabled(self): """Verify that CAS is wired up properly when enabled""" with self.settings( CAS_ENABLED=True, CAS_SERVER_URL='http://example.com/login', ): # Because this won't actually work, we get in a redirect # loop, or at least, best as I can tell. response = self.client.get(reverse('cas_login')) self.assertTrue(compare( 'http://example.com/login?' 'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F', response['location'] )) def test_cas_disable(self): """Verify that when CAS is disabled, login is default""" with self.settings( CAS_ENABLED=False ): response = self.client.get('/login', follow=True) self.assertEqual(404, response.status_code)
""" Testing of project level URLs. """ from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase import ssl if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access from urltools import compare # noqa class TestURLs(TestCase): """Verify project level URL configuration.""" def test_cas_enabled(self): """Verify that CAS is wired up properly when enabled""" with self.settings( CAS_ENABLED=True, CAS_SERVER_URL='http://example.com/login', ): # Because this won't actually work, we get in a redirect # loop, or at least, best as I can tell. response = self.client.get(reverse('cas_login')) self.assertTrue(compare( 'http://example.com/login?' 'service=http%3A%2F%2Ftestserver%2Fcas%2Flogin%3Fnext%3D%252F', response['location'] )) def test_cas_disable(self): """Verify that when CAS is disabled, login is default""" with self.settings( CAS_ENABLED=False ): response = self.client.get('/login', follow=True) self.assertEqual(404, response.status_code)
Disable SSL validation for a test which uses urltools
Disable SSL validation for a test which uses urltools This is currently a common problem with python >= 2.7.9: http://stackoverflow.com/questions/27835619/ssl-certificate-verify-failed-error
Python
agpl-3.0
mitodl/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,amir-qayyum-khan/lore,mitodl/lore,mitodl/lore,mitodl/lore,amir-qayyum-khan/lore,mitodl/lore
--- +++ @@ -6,7 +6,13 @@ from django.core.urlresolvers import reverse from django.test import TestCase -from urltools import compare + +import ssl + +if hasattr(ssl, '_create_unverified_context'): + ssl._create_default_https_context = ssl._create_unverified_context # noqa pylint: disable=protected-access + +from urltools import compare # noqa class TestURLs(TestCase):
8b0c08962d18536b87a948c96f7ec7daabd8b4e1
NEO_flyby.py
NEO_flyby.py
import time import datetime import requests import json def get_NEO_flyby(): neo_data = [] unix = time.time() datestamp = datetime.datetime.fromtimestamp(unix).strftime("%Y-%b-%d") json_data_url = requests.get("https://ssd-api.jpl.nasa.gov/cad.api?body=Earth&dist-max=20LD") json_data = json.loads(json_data_url.text) for i in range(len(json_data["data"])): neo_date = json_data["data"][i][3][:11] neo_time = json_data["data"][i][3][11:] if neo_date == datestamp: neo_data.append((json_data["data"][i][0],)) # sorte lieber per magnitude und nimm nur das größte objekt, sonst ist der tweet zu lang get_NEO_flyby() # TODO: Add api indicator of numbers # TODO: Iterate over data and return tuple
import time import datetime import requests import json def get_NEO_flyby(): neo_data = [] des = 0 orbit_id = 1 jd = 2 cd = 3 dist = 4 dist_min = 5 dist_max = 6 v_rel = 7 v_inf = 8 t_signma_F = 9 body = 10 h = 11 unix = time.time() datestamp = datetime.datetime.fromtimestamp(unix).strftime("%Y-%b-%d") json_data_url = requests.get("https://ssd-api.jpl.nasa.gov/cad.api?body=Earth&dist-max=20LD") json_data = json.loads(json_data_url.text) for i in range(len(json_data["data"])): neo_date = json_data["data"][i][cd][:11] neo_time = json_data["data"][i][cd][11:] if neo_date == datestamp: neo_data.append((json_data["data"][i][des],)) # sorte lieber per magnitude und nimm nur das größte objekt, sonst ist der tweet zu lang get_NEO_flyby() # TODO: Iterate over data and return tuple
Update 0.1.1 - Added api number reference
Update 0.1.1 - Added api number reference
Python
mit
FXelix/space_facts_bot
--- +++ @@ -4,10 +4,23 @@ import requests import json + def get_NEO_flyby(): neo_data = [] + des = 0 + orbit_id = 1 + jd = 2 + cd = 3 + dist = 4 + dist_min = 5 + dist_max = 6 + v_rel = 7 + v_inf = 8 + t_signma_F = 9 + body = 10 + h = 11 unix = time.time() datestamp = datetime.datetime.fromtimestamp(unix).strftime("%Y-%b-%d") @@ -15,11 +28,11 @@ json_data_url = requests.get("https://ssd-api.jpl.nasa.gov/cad.api?body=Earth&dist-max=20LD") json_data = json.loads(json_data_url.text) for i in range(len(json_data["data"])): - neo_date = json_data["data"][i][3][:11] - neo_time = json_data["data"][i][3][11:] + neo_date = json_data["data"][i][cd][:11] + neo_time = json_data["data"][i][cd][11:] if neo_date == datestamp: - neo_data.append((json_data["data"][i][0],)) + neo_data.append((json_data["data"][i][des],)) @@ -32,7 +45,6 @@ get_NEO_flyby() -# TODO: Add api indicator of numbers # TODO: Iterate over data and return tuple
9e5b6ea80dd1039952bb5ff821ae15555ad591be
iterm2_tools/images.py
iterm2_tools/images.py
import sys import os import base64 # See https://iterm2.com/images.html IMAGE_CODE= '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a' def iterm2_image_bytes(b, filename=None, inline=1): data = { 'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'), 'inline': inline, 'size': len(b), 'base64_img': base64.b64encode(b).decode('ascii'), } return (IMAGE_CODE.format(**data)) def iterm2_display_image_file(fn): """ Display an image in the terminal. A newline is not printed. """ with open(os.path.realpath(os.path.expanduser(fn)), 'br') as f: sys.stdout.write(iterm2_image_bytes(f.read(), filename=fn))
import sys import os import base64 # See https://iterm2.com/images.html IMAGE_CODE= '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a' def iterm2_image_bytes(b, filename=None, inline=1): data = { 'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'), 'inline': inline, 'size': len(b), 'base64_img': base64.b64encode(b).decode('ascii'), } return (IMAGE_CODE.format(**data)) def iterm2_display_image_file(fn): """ Display an image in the terminal. A newline is not printed. """ with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f: sys.stdout.write(iterm2_image_bytes(f.read(), filename=fn))
Fix Python 2 compatibility issue
Fix Python 2 compatibility issue
Python
mit
asmeurer/iterm2-tools
--- +++ @@ -20,5 +20,5 @@ A newline is not printed. """ - with open(os.path.realpath(os.path.expanduser(fn)), 'br') as f: + with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f: sys.stdout.write(iterm2_image_bytes(f.read(), filename=fn))
7570b9dd8fada221e5059a00e107ce6665b9c563
nailgun/nailgun/db/sqlalchemy/models/base.py
nailgun/nailgun/db/sqlalchemy/models/base.py
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from datetime import datetime from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import Integer from sqlalchemy.ext.declarative import declarative_base from nailgun.db.sqlalchemy.models.fields import JSON from nailgun.openstack.common.db.sqlalchemy import models Base = declarative_base(cls=models.ModelBase) class CapacityLog(Base): __tablename__ = 'capacity_log' id = Column(Integer, primary_key=True) report = Column(JSON) datetime = Column(DateTime, default=datetime.now())
# -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from datetime import datetime from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import Integer from sqlalchemy.ext.declarative import declarative_base from nailgun.db.sqlalchemy.models.fields import JSON from nailgun.openstack.common.db.sqlalchemy import models Base = declarative_base(cls=models.ModelBase) class CapacityLog(Base): __tablename__ = 'capacity_log' id = Column(Integer, primary_key=True) report = Column(JSON) datetime = Column(DateTime, default=lambda: datetime.now())
Fix select order for Capacity Log
Fix select order for Capacity Log Change-Id: I0db3de15e65bb300d75741e5c86e164b1966ac89 Closes: bug #1281986
Python
apache-2.0
nebril/fuel-web,SmartInfrastructures/fuel-web-dev,stackforge/fuel-web,nebril/fuel-web,huntxu/fuel-web,nebril/fuel-web,eayunstack/fuel-web,zhaochao/fuel-web,huntxu/fuel-web,koder-ua/nailgun-fcert,zhaochao/fuel-web,huntxu/fuel-web,stackforge/fuel-web,koder-ua/nailgun-fcert,prmtl/fuel-web,SmartInfrastructures/fuel-web-dev,koder-ua/nailgun-fcert,zhaochao/fuel-web,nebril/fuel-web,huntxu/fuel-web,zhaochao/fuel-web,nebril/fuel-web,koder-ua/nailgun-fcert,eayunstack/fuel-web,stackforge/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,prmtl/fuel-web,prmtl/fuel-web,SmartInfrastructures/fuel-web-dev,prmtl/fuel-web,prmtl/fuel-web,huntxu/fuel-web,SmartInfrastructures/fuel-web-dev,eayunstack/fuel-web,eayunstack/fuel-web,zhaochao/fuel-web
--- +++ @@ -35,4 +35,4 @@ id = Column(Integer, primary_key=True) report = Column(JSON) - datetime = Column(DateTime, default=datetime.now()) + datetime = Column(DateTime, default=lambda: datetime.now())
dd8d4515f5e39dcc3f23db5a5acf3478c9c16ae2
codebox/conf.py
codebox/conf.py
""" codebox.conf ~~~~~~~~~~~ :copyright: (c) 2011 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ import os, os.path import urlparse class Config(object): DEBUG = True TESTING = False SECRET_KEY = '\x89\x1d\xec\x8eJ\xda=C`\xf3<X\x81\xff\x1e\r{+\x1b\xe1\xd1@ku' REDIS_DB = 0 JANRAIN_API_KEY = '288a1ca2fedb4e1d1780c320fa4082ae69640a52' PODIO_CLIENT_ID = "dcramer@gmail.com" PODIO_KEY = "f7qFIBcPTfTBLOd8ondkO9UGqU6uN1iG" DOMAIN_BLACKLIST = ['gmail.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'googlemail.com', 'facebookmail.com'] if os.environ.has_key('REDISTOGO_URL'): # 'redis://username:password@my.host:6789' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(os.environ['REDISTOGO_URL']) Config.REDIS_USER = url.username Config.REDIS_PASSWORD = url.password Config.REDIS_HOST = url.hostname Config.REDIS_PORT = url.port class TestingConfig(Config): REDIS_DB = 9 TESTING = True
""" codebox.conf ~~~~~~~~~~~ :copyright: (c) 2011 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ import os, os.path import urlparse class Config(object): DEBUG = True TESTING = False SECRET_KEY = os.environ.get('SECRET_KEY', '\x89\x1d\xec\x8eJ\xda=C`\xf3<X\x81\xff\x1e\r{+\x1b\xe1\xd1@ku') REDIS_DB = 0 JANRAIN_API_KEY = os.environ.get('JANRAIN_API_KEY') DOMAIN_BLACKLIST = ['gmail.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'googlemail.com', 'facebookmail.com'] if os.environ.has_key('REDISTOGO_URL'): # 'redis://username:password@my.host:6789' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(os.environ['REDISTOGO_URL']) Config.REDIS_USER = url.username Config.REDIS_PASSWORD = url.password Config.REDIS_HOST = url.hostname Config.REDIS_PORT = url.port class TestingConfig(Config): REDIS_DB = 9 TESTING = True
Read janrain/secret key from env
Read janrain/secret key from env
Python
apache-2.0
disqus/codebox,disqus/codebox
--- +++ @@ -12,11 +12,9 @@ class Config(object): DEBUG = True TESTING = False - SECRET_KEY = '\x89\x1d\xec\x8eJ\xda=C`\xf3<X\x81\xff\x1e\r{+\x1b\xe1\xd1@ku' + SECRET_KEY = os.environ.get('SECRET_KEY', '\x89\x1d\xec\x8eJ\xda=C`\xf3<X\x81\xff\x1e\r{+\x1b\xe1\xd1@ku') REDIS_DB = 0 - JANRAIN_API_KEY = '288a1ca2fedb4e1d1780c320fa4082ae69640a52' - PODIO_CLIENT_ID = "dcramer@gmail.com" - PODIO_KEY = "f7qFIBcPTfTBLOd8ondkO9UGqU6uN1iG" + JANRAIN_API_KEY = os.environ.get('JANRAIN_API_KEY') DOMAIN_BLACKLIST = ['gmail.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'googlemail.com', 'facebookmail.com'] if os.environ.has_key('REDISTOGO_URL'):
a17d3fbf19b25e1da568266b17abe575071e3f80
server/lib/utils.py
server/lib/utils.py
import yaml import json import os import uuid def loadFromFile(path, bytes=False): from config import PATH if not os.path.isabs(path): path = os.path.join(PATH, path) readType = 'r' if not bytes else 'rb' with open(path, readType) as file: fileContents = file.read() file.close() return fileContents def loadYaml(fileName): return yaml.load(loadFromFile(fileName)) def loadJson(fileName): return json.loads(loadFromFile(fileName)) def writeFile(fileName, content): path = '/'.join(os.path.dirname(__file__).split('/')[0:-1]) with open((os.path.join(path,fileName)), 'w') as file: file.write(content) file.close() def getPath(path): from config import PATH return os.path.join(PATH, path) def addUniqueIdToFile(filename): splitFilename = filename.split('.') splitFilename[0] = '{filename}-{id}'.format(filename=splitFilename[0], id=str(uuid.uuid4())[:6]) return '.'.join(splitFilename) def removeValueFromDict(k, value): for key in k: del k[key][value] return k def additionalDeliveryInfo(delivery): if delivery == 'express': return 'express dodání(+30% ceny)' else: return delivery
import yaml import json import os import uuid def loadFromFile(path, bytes=False): from config import PATH if not os.path.isabs(path): path = os.path.join(PATH, path) readType = 'r' if not bytes else 'rb' with open(path, readType, encoding='utf-8') as file: fileContents = file.read() file.close() return fileContents def loadYaml(fileName): return yaml.load(loadFromFile(fileName)) def loadJson(fileName): return json.loads(loadFromFile(fileName)) def writeFile(fileName, content): path = '/'.join(os.path.dirname(__file__).split('/')[0:-1]) with open((os.path.join(path,fileName)), 'w') as file: file.write(content) file.close() def getPath(path): from config import PATH return os.path.join(PATH, path) def addUniqueIdToFile(filename): splitFilename = filename.split('.') splitFilename[0] = '{filename}-{id}'.format(filename=splitFilename[0], id=str(uuid.uuid4())[:6]) return '.'.join(splitFilename) def removeValueFromDict(k, value): for key in k: del k[key][value] return k def additionalDeliveryInfo(delivery): if delivery == 'express': return 'express dodání(+30% ceny)' else: return delivery
Fix not being able to parse diacritics
Fix not being able to parse diacritics
Python
agpl-3.0
MakersLab/custom-print
--- +++ @@ -8,7 +8,7 @@ if not os.path.isabs(path): path = os.path.join(PATH, path) readType = 'r' if not bytes else 'rb' - with open(path, readType) as file: + with open(path, readType, encoding='utf-8') as file: fileContents = file.read() file.close() return fileContents
09572d5f24c33b6a604cc038c4e1c13ddb977af6
db/db.py
db/db.py
#!/usr/bin/python import sys import copy import json import getpass import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir, self.username), self.password) def save(self): aesjsonfile.dump("%s/%s.json"%(config.dbdir, self.username), self.db, self.password) def accountstodo(self): return self.db["accounts"] def accounts(self): ret = copy.deepcopy(self.db["accounts"]) for acct in ret: acct.pop("password",None) return ret if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) password = getpass.getpass() db = DB(sys.argv[1],password) print "accountstodo" print json.dumps(db.accountstodo(),indent=2) print "accounts" print json.dumps(db.accounts(),indent=2)
#!/usr/bin/python import sys import copy import json import getpass import aesjsonfile sys.path.append("../") import config class DB(object): def __init__(self, username, password): self.username = username self.password = password self.db = aesjsonfile.load("%s/%s.json"%(config.dbdir, self.username), self.password) def save(self): aesjsonfile.dump("%s/%s.json"%(config.dbdir, self.username), self.db, self.password) def accountstodo(self): return self.db["accounts"] def accounts(self): ret = copy.deepcopy(self.db["accounts"]) for acct in ret: acct.pop("password",None) acct["subaccounts"] = [] for sub in self.db.get("balances",{}).get(acct["name"],{}): acct["subaccounts"].append({"name": sub, "amount": self.db["balances"][acct["name"]][sub][0]["amount"], "date": self.db["balances"][acct["name"]][sub][0]["lastdate"]}) return ret if __name__ == "__main__": if len(sys.argv) < 2: sys.exit(1) password = getpass.getpass() db = DB(sys.argv[1],password) print "accountstodo" print json.dumps(db.accountstodo(),indent=2) print "accounts" print json.dumps(db.accounts(),indent=2)
Return subaccounts with their balances on account query.
Return subaccounts with their balances on account query.
Python
agpl-3.0
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
--- +++ @@ -25,6 +25,10 @@ ret = copy.deepcopy(self.db["accounts"]) for acct in ret: acct.pop("password",None) + acct["subaccounts"] = [] + for sub in self.db.get("balances",{}).get(acct["name"],{}): + acct["subaccounts"].append({"name": sub, "amount": self.db["balances"][acct["name"]][sub][0]["amount"], + "date": self.db["balances"][acct["name"]][sub][0]["lastdate"]}) return ret if __name__ == "__main__":
79e22a810638fbf2098f87525fa5a68d3c3b8c49
hitcount/management/commands/hitcount_cleanup.py
hitcount/management/commands/hitcount_cleanup.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand from hitcount.models import Hit class Command(BaseCommand): help = "Can be run as a cronjob or directly to clean out old Hits objects from the database." def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def handle(self, *args, **kwargs): self.handle_noargs() def handle_noargs(self, **options): grace = getattr(settings, 'HITCOUNT_KEEP_HIT_IN_DATABASE', {'days': 30}) period = timezone.now() - timedelta(**grace) qs = Hit.objects.filter(created__lt=period) number_removed = len(qs) qs.delete() self.stdout.write('Successfully removed %s Hits' % number_removed)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from django.utils import timezone try: from django.core.management.base import BaseCommand except ImportError: from django.core.management.base import NoArgsCommand as BaseCommand from hitcount.models import Hit class Command(BaseCommand): help = "Can be run as a cronjob or directly to clean out old Hits objects from the database." def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def handle(self, *args, **kwargs): self.handle_noargs() def handle_noargs(self, **options): grace = getattr(settings, 'HITCOUNT_KEEP_HIT_IN_DATABASE', {'days': 30}) period = timezone.now() - timedelta(**grace) qs = Hit.objects.filter(created__lt=period) number_removed = qs.count() qs.delete() self.stdout.write('Successfully removed %s Hits' % number_removed)
Use count() on queryset instead of len()
Use count() on queryset instead of len() Ensure a fast query even for millions of rows.
Python
mit
thornomad/django-hitcount,thornomad/django-hitcount,thornomad/django-hitcount
--- +++ @@ -27,6 +27,6 @@ grace = getattr(settings, 'HITCOUNT_KEEP_HIT_IN_DATABASE', {'days': 30}) period = timezone.now() - timedelta(**grace) qs = Hit.objects.filter(created__lt=period) - number_removed = len(qs) + number_removed = qs.count() qs.delete() self.stdout.write('Successfully removed %s Hits' % number_removed)
da193c2606daac82d0693cc10decdbf2d3162fa5
lib/markdown_deux/conf/settings.py
lib/markdown_deux/conf/settings.py
# Copyright (c) 2010 ActiveState Software Inc. from django.conf import settings MARKDOWN_DEUX_HELP_URL = getattr(settings, "MARKDOWN_DEUX_HELP_URL", "http://daringfireball.net/projects/markdown/syntax") MARKDOWN_DEUX_DEFAULT_STYLE = { "extras": { "code-friendly": None, }, "safe_mode": "escape", } MARKDOWN_DEUX_STYLES = getattr(settings, "MARKDOWN_DEUX_STYLES", {"default": MARKDOWN_DEUX_DEFAULT_STYLE})
# Copyright (c) 2010 ActiveState Software Inc. from django.conf import settings MARKDOWN_DEUX_HELP_URL = getattr(settings, "MARKDOWN_DEUX_HELP_URL", "http://daringfireball.net/projects/markdown/syntax") MARKDOWN_DEUX_DEFAULT_STYLE = { "extras": { "code-friendly": None, }, "safe_mode": "escape", } MARKDOWN_DEUX_STYLES = getattr(settings, "MARKDOWN_DEUX_STYLES", {"default": MARKDOWN_DEUX_DEFAULT_STYLE}) DEBUG = settings.DEBUG
Fix debug flag import error
Fix debug flag import error
Python
mit
gogobook/django-markdown-deux,gogobook/django-markdown-deux,trentm/django-markdown-deux,douzepouze/django-markdown-tag
--- +++ @@ -15,3 +15,4 @@ MARKDOWN_DEUX_STYLES = getattr(settings, "MARKDOWN_DEUX_STYLES", {"default": MARKDOWN_DEUX_DEFAULT_STYLE}) +DEBUG = settings.DEBUG
57b1dbc45e7b78f7aa272fd5b7d4bd022850beb9
lametro/migrations/0007_update_packet_links.py
lametro/migrations/0007_update_packet_links.py
# Generated by Django 2.2.24 on 2021-10-22 19:54 from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' for packet in ('BillPacket', 'EventPacket'): packet_model = apps.get_model('lametro', packet) for p in packet_model.objects.all(): p.save(merge=False) class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ]
# Generated by Django 2.2.24 on 2021-10-22 19:54 from django.db import migrations def resave_packets(apps, schema_editor): ''' Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' # for packet in ('BillPacket', 'EventPacket'): # packet_model = apps.get_model('lametro', packet) # for p in packet_model.objects.all(): # p.save(merge=False) return class Migration(migrations.Migration): dependencies = [ ('lametro', '0006_add_plan_program_policy'), ] operations = [ migrations.RunPython(resave_packets), ]
Disable data migration for deployment
Disable data migration for deployment
Python
mit
datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic
--- +++ @@ -8,10 +8,11 @@ Re-save all existing packets to update their URLs based on the new value of MERGE_HOST. ''' - for packet in ('BillPacket', 'EventPacket'): - packet_model = apps.get_model('lametro', packet) - for p in packet_model.objects.all(): - p.save(merge=False) +# for packet in ('BillPacket', 'EventPacket'): +# packet_model = apps.get_model('lametro', packet) +# for p in packet_model.objects.all(): +# p.save(merge=False) + return class Migration(migrations.Migration):
ce36dd825635c8487fcd9f83bd686a2dce7c318c
hello.py
hello.py
from flask import Flask from flask import request import os from dogapi import dog_http_api as api app = Flask(__name__) api.api_key = os.environ.get('DD_API_KEY') action_url = "/" + os.environ.get('BASE_URL') + "/" @app.route(action_url, methods=['POST', 'GET']) def hello(): api.metric('mailgun.event', (request.args.post('timestamp'), 1), tags=["event_name:" + request.args.post('event')]) return "200" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
from flask import Flask from flask import request import os from dogapi import dog_http_api as api app = Flask(__name__) api.api_key = os.environ.get('DD_API_KEY') action_url = "/" + os.environ.get('BASE_URL') + "/" @app.route(action_url, methods=['POST', 'GET']) def hello(): api.metric('mailgun.event', (request.form('timestamp'), 1), tags=["event_name:" + request.form('event')]) return "200" if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
Use the right style of request.
Use the right style of request.
Python
apache-2.0
darron/mailgun_datadog
--- +++ @@ -11,7 +11,7 @@ @app.route(action_url, methods=['POST', 'GET']) def hello(): - api.metric('mailgun.event', (request.args.post('timestamp'), 1), tags=["event_name:" + request.args.post('event')]) + api.metric('mailgun.event', (request.form('timestamp'), 1), tags=["event_name:" + request.form('event')]) return "200" if __name__ == "__main__":
c711d5e2dbca4b95bebc0eed4d48a35eb3c7a998
website/addons/dropbox/settings/local-dist.py
website/addons/dropbox/settings/local-dist.py
# -*- coding: utf-8 -*- """Example Dropbox local settings file. Copy this file to local.py and change these settings. """ # Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'changeme' DROPBOX_SECRET = 'changeme'
# -*- coding: utf-8 -*- """Example Dropbox local settings file. Copy this file to local.py and change these settings. """ # Get an app key and secret at https://www.dropbox.com/developers/apps DROPBOX_KEY = 'jnpncg5s2fc7cj8' DROPBOX_SECRET = 'sjqv1hrk7sonhu1'
Add dropbox credentials for testing.
Add dropbox credentials for testing.
Python
apache-2.0
crcresearch/osf.io,acshi/osf.io,felliott/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,jnayak1/osf.io,baylee-d/osf.io,TomBaxter/osf.io,mluke93/osf.io,mluo613/osf.io,pattisdr/osf.io,samchrisinger/osf.io,wearpants/osf.io,mfraezz/osf.io,kch8qx/osf.io,Nesiehr/osf.io,adlius/osf.io,RomanZWang/osf.io,abought/osf.io,felliott/osf.io,jnayak1/osf.io,caseyrollins/osf.io,doublebits/osf.io,cslzchen/osf.io,kwierman/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,icereval/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,jnayak1/osf.io,cwisecarver/osf.io,SSJohns/osf.io,icereval/osf.io,monikagrabowska/osf.io,wearpants/osf.io,chrisseto/osf.io,binoculars/osf.io,monikagrabowska/osf.io,mluo613/osf.io,adlius/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,asanfilippo7/osf.io,icereval/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,crcresearch/osf.io,kch8qx/osf.io,SSJohns/osf.io,abought/osf.io,crcresearch/osf.io,laurenrevere/osf.io,mluo613/osf.io,baylee-d/osf.io,alexschiller/osf.io,zachjanicki/osf.io,aaxelb/osf.io,rdhyee/osf.io,doublebits/osf.io,amyshi188/osf.io,Nesiehr/osf.io,sloria/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,kch8qx/osf.io,chrisseto/osf.io,TomBaxter/osf.io,aaxelb/osf.io,DanielSBrown/osf.io,mattclark/osf.io,emetsger/osf.io,emetsger/osf.io,binoculars/osf.io,zachjanicki/osf.io,kwierman/osf.io,kwierman/osf.io,kwierman/osf.io,sloria/osf.io,mfraezz/osf.io,kch8qx/osf.io,acshi/osf.io,chennan47/osf.io,caneruguz/osf.io,doublebits/osf.io,mluke93/osf.io,erinspace/osf.io,alexschiller/osf.io,mluo613/osf.io,zamattiac/osf.io,alexschiller/osf.io,caseyrollins/osf.io,zachjanicki/osf.io,cwisecarver/osf.io,samchrisinger/osf.io,TomBaxter/osf.io,wearpants/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,HalcyonChimera/osf.io,laurenrevere/osf.io,cslzchen/osf.io,SSJohns/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,abought/osf.io,jnayak1/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,samchrisinger/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,leb2dg/osf.io,acshi/osf.io,mattclark/osf.io,chrisseto/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,mluke93/osf.io,binoculars/osf.io,asanfilippo7/osf.io,felliott/osf.io,DanielSBrown/osf.io,TomHeatwole/osf.io,hmoco/osf.io,kch8qx/osf.io,caneruguz/osf.io,saradbowman/osf.io,felliott/osf.io,adlius/osf.io,doublebits/osf.io,caneruguz/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,emetsger/osf.io,mluo613/osf.io,hmoco/osf.io,hmoco/osf.io,RomanZWang/osf.io,emetsger/osf.io,rdhyee/osf.io,mluke93/osf.io,acshi/osf.io,leb2dg/osf.io,zamattiac/osf.io,saradbowman/osf.io,leb2dg/osf.io,pattisdr/osf.io,chennan47/osf.io,acshi/osf.io,cslzchen/osf.io,alexschiller/osf.io,SSJohns/osf.io,chennan47/osf.io,erinspace/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,Nesiehr/osf.io,amyshi188/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,abought/osf.io,wearpants/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,adlius/osf.io,TomHeatwole/osf.io,pattisdr/osf.io,cwisecarver/osf.io,mfraezz/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,doublebits/osf.io,sloria/osf.io
--- +++ @@ -3,5 +3,5 @@ these settings. """ # Get an app key and secret at https://www.dropbox.com/developers/apps -DROPBOX_KEY = 'changeme' -DROPBOX_SECRET = 'changeme' +DROPBOX_KEY = 'jnpncg5s2fc7cj8' +DROPBOX_SECRET = 'sjqv1hrk7sonhu1'
df3bbdcf08dafbf2fd6997638a575fb4e47ac61f
factory/tools/cat_StarterLog.py
factory/tools/cat_StarterLog.py
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(): if sys.argv[1]=='-monitor': fname=sys.argv[2] condor_log_id="((StarterLog.monitor)|(StarterLog.vm1))" else: fname=sys.argv[1] condor_log_id="((StarterLog)|(StarterLog.vm2))" try: print gWftLogParser.get_CondorLog(fname,condor_log_id) except: sys.stderr.write("%s\n"%USAGE) sys.exit(1) if __name__ == '__main__': main()
Add support for monitor starterlog
Add support for monitor starterlog
Python
bsd-3-clause
holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS
--- +++ @@ -24,7 +24,7 @@ condor_log_id="((StarterLog)|(StarterLog.vm2))" try: - print gWftLogParser.get_CondorLog(sys.argv[1],"((StarterLog)|(StarterLog.vm2))") + print gWftLogParser.get_CondorLog(fname,condor_log_id) except: sys.stderr.write("%s\n"%USAGE) sys.exit(1)
dd6c3abcfc01b22528440e5dd62a1d3d3453b8b3
djangopress/templatetags/djangopress_tags.py
djangopress/templatetags/djangopress_tags.py
"""Templatetags for djangopress.""" from datetime import date from collections import defaultdict from django import template from djangopress.models import Post, Category register = template.Library() @register.inclusion_tag('djangopress/tags/archive_list.html') def archive_list(): """List post by date""" posts = Post.objects.all() years_dictionary = defaultdict(set) for post in posts: year = post.creation_date.year month = post.creation_date.month years_dictionary[year].add(month) years = {} for year, months in years_dictionary.items(): year = str(year) years[year] = [] for month in months: years[year].append(date(int(year), month, 1)) return {'years': years} @register.inclusion_tag('djangopress/tags/category_list.html') def category_list(): """List the categories in the blog.""" categories = Category.objects.all() return {'categories': categories}
"""Templatetags for djangopress.""" from datetime import date from collections import defaultdict from django import template from djangopress.models import Post, Category register = template.Library() @register.inclusion_tag('djangopress/tags/archive_list.html') def archive_list(): """List post by date""" posts = Post.objects.all() years_dictionary = defaultdict(set) for post in posts: year = post.creation_date.year month = post.creation_date.month years_dictionary[year].add(month) years = {} for year, months in years_dictionary.items(): year = str(year) years[year] = [] for month in months: years[year].append(date(int(year), month, 1)) for year in years: years[year].sort(reverse=True) return {'years': years} @register.inclusion_tag('djangopress/tags/category_list.html') def category_list(): """List the categories in the blog.""" categories = Category.objects.all() return {'categories': categories}
Sort the months in archive_templatetag
Sort the months in archive_templatetag
Python
mit
gilmrjc/djangopress,gilmrjc/djangopress,gilmrjc/djangopress
--- +++ @@ -25,6 +25,8 @@ years[year] = [] for month in months: years[year].append(date(int(year), month, 1)) + for year in years: + years[year].sort(reverse=True) return {'years': years}
226cb45ba39d13c4bf2b40f3998b2631f9f461a6
Lib/cluster/__init__.py
Lib/cluster/__init__.py
# # cluster - Vector Quantization / Kmeans # from info import __doc__ __all__ = ['vq'] import vq
# # cluster - Vector Quantization / Kmeans # from info import __doc__ __all__ = ['vq'] import vq from numpy.testing import NumpyTest test = NumpyTest().test
Add missing test definition in scipy.cluster
Add missing test definition in scipy.cluster git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@2941 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
--- +++ @@ -7,3 +7,5 @@ __all__ = ['vq'] import vq +from numpy.testing import NumpyTest +test = NumpyTest().test
1317d645092d94c95bcaf7a0341ac18208f9df0d
patient/admin.py
patient/admin.py
from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin)
from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient exclude = [] def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin)
Fix deprecated warning in CustomPatientForm
Fix deprecated warning in CustomPatientForm
Python
mit
sigurdsa/angelika-api
--- +++ @@ -6,6 +6,7 @@ class CustomPatientForm(forms.ModelForm): class Meta: model = Patient + exclude = [] def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs)
39461a97ef6e6b988466f41ddfee17687dd59ee1
notifications/match_score.py
notifications/match_score.py
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class MatchScoreNotification(BaseNotification): def __init__(self, match): self.match = match self.event = match.event.get() self._event_feed = self.event.key_name self._district_feed = self.event.event_district_enum @property def _type(self): return NotificationType.MATCH_SCORE def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[self._type] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['match'] = ModelToDict.matchConverter(self.match) return data
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class MatchScoreNotification(BaseNotification): def __init__(self, match): self.match = match self.event = match.event.get() self._event_feed = self.event.key_name self._district_feed = self.event.event_district_enum @property def _type(self): return NotificationType.MATCH_SCORE def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[self._type] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['event_key'] = self.event.key_name data['message_data']['match'] = ModelToDict.matchConverter(self.match) return data
Add event key to match score notification
Add event key to match score notification
Python
mit
bdaroz/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance
--- +++ @@ -20,5 +20,6 @@ data['message_type'] = NotificationType.type_names[self._type] data['message_data'] = {} data['message_data']['event_name'] = self.event.name + data['message_data']['event_key'] = self.event.key_name data['message_data']['match'] = ModelToDict.matchConverter(self.match) return data
aca68618e5f1549faa1adfc1a1351a472ba0246d
gettingstarted/urls.py
gettingstarted/urls.py
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^$', include('rog.urls')), url(r'^admin/', include(admin.site.urls)), ]
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^', include('rog.urls')), url(r'^admin/', include(admin.site.urls)), ]
Remove the dollar from the regex to avoid problems including URLs.
Remove the dollar from the regex to avoid problems including URLs.
Python
bsd-2-clause
kenyansongithub/django-rog,kenyansongithub/django-rog,kenyansongithub/django-rog
--- +++ @@ -10,7 +10,7 @@ urlpatterns = [ - url(r'^$', include('rog.urls')), + url(r'^', include('rog.urls')), url(r'^admin/', include(admin.site.urls)), ]
6623d5679eef2c3db70edce7334582b5d524786d
micro.py
micro.py
#!/usr/bin/env python from sys import argv from operator import add, sub, mul, div functions = { \ '+': (2, add), \ '-': (2, sub), \ '*': (2, mul), \ '/': (2, div) \ } def get_code(): return argv[1] def get_tokens(code): return code.split(' ') def evaluate(tokens): name = tokens[0] tokens = tokens[1:] if name not in functions: return int(name), tokens function = functions[name] arguments = [] for _ in xrange(function[0]): value, tokens = evaluate(tokens) arguments.append(value) value = function[1](*arguments) return value, tokens if __name__ == '__main__': code = get_code() tokens = get_tokens(code) value, _ = evaluate(tokens) print(value)
#!/usr/bin/env python from sys import argv from operator import add, sub, mul, div functions = { \ '+': (2, add), \ '-': (2, sub), \ '*': (2, mul), \ '/': (2, div) \ } def get_code(): return argv[1] def get_tokens(code): return code.split(' ') def parse_function(tokens): return 'test', (23, None), tokens[-1:] def evaluate(tokens): name = tokens[0] tokens = tokens[1:] if name == 'fn': name, function, tokens = parse_function(tokens) functions[name] = function return 0, tokens if name not in functions: return int(name), tokens function = functions[name] arguments = [] for _ in xrange(function[0]): value, tokens = evaluate(tokens) arguments.append(value) value = function[1](*arguments) return value, tokens if __name__ == '__main__': code = get_code() tokens = get_tokens(code) value, _ = evaluate(tokens) print(value) print(functions)
Add a detection of a function definition.
Add a detection of a function definition.
Python
mit
thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro
--- +++ @@ -16,9 +16,17 @@ def get_tokens(code): return code.split(' ') +def parse_function(tokens): + return 'test', (23, None), tokens[-1:] + def evaluate(tokens): name = tokens[0] tokens = tokens[1:] + if name == 'fn': + name, function, tokens = parse_function(tokens) + functions[name] = function + + return 0, tokens if name not in functions: return int(name), tokens @@ -36,3 +44,4 @@ tokens = get_tokens(code) value, _ = evaluate(tokens) print(value) + print(functions)
46afcd0e5e958e22647ef9c708918489027277e2
modeltranslation/tests/settings.py
modeltranslation/tests/settings.py
# -*- coding: utf-8 -*- """ Settings overrided for test time """ import os from django.conf import settings DIRNAME = os.path.dirname(__file__) INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'modeltranslation.tests', ) # IMO this is unimportant #if django.VERSION[0] >= 1 and django.VERSION[1] >= 3: #INSTALLED_APPS += ('django.contrib.staticfiles',) #STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(DIRNAME, 'media/') LANGUAGES = (('de', 'Deutsch'), ('en', 'English')) LANGUAGE_CODE = 'de' MODELTRANSLATION_DEFAULT_LANGUAGE = 'de' USE_I18N = True MODELTRANSLATION_AUTO_POPULATE = False MODELTRANSLATION_FALLBACK_LANGUAGES = ()
# -*- coding: utf-8 -*- """ Settings overrided for test time """ import os from django.conf import settings DIRNAME = os.path.dirname(__file__) INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'modeltranslation.tests', ) # IMO this is unimportant #if django.VERSION[0] >= 1 and django.VERSION[1] >= 3: #INSTALLED_APPS += ('django.contrib.staticfiles',) #STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(DIRNAME, 'media/') LANGUAGES = (('de', 'Deutsch'), ('en', 'English')) LANGUAGE_CODE = 'de' MODELTRANSLATION_DEFAULT_LANGUAGE = 'de' USE_I18N = True USE_TZ = False MODELTRANSLATION_AUTO_POPULATE = False MODELTRANSLATION_FALLBACK_LANGUAGES = ()
Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled.
Disable timezone support for tests, as the date / time fields' tests use naive datatime objects and fail if it's enabled.
Python
bsd-3-clause
extertioner/django-modeltranslation,marctc/django-modeltranslation,yoza/django-modeltranslation,nanuxbe/django-modeltranslation,akheron/django-modeltranslation,vstoykov/django-modeltranslation,SideStudios/django-modeltranslation,yoza/django-modeltranslation,marctc/django-modeltranslation,deschler/django-modeltranslation,akheron/django-modeltranslation,nanuxbe/django-modeltranslation,extertioner/django-modeltranslation,deschler/django-modeltranslation,SideStudios/django-modeltranslation,vstoykov/django-modeltranslation
--- +++ @@ -26,6 +26,7 @@ MODELTRANSLATION_DEFAULT_LANGUAGE = 'de' USE_I18N = True +USE_TZ = False MODELTRANSLATION_AUTO_POPULATE = False MODELTRANSLATION_FALLBACK_LANGUAGES = ()
f0b96aa0d4921e161eee9bb1a83846442f7f63b2
likelihood.py
likelihood.py
import math #Log-likelihood def ll(ciphertext,perm,mat,k=2): s=0.0 for i in range(len(ciphertext)-(k-1)): kmer = tuple([perm[c] for c in ciphertext[i:i+k]]) s = s + math.log(mat[kmer]) return s
import math #Log-likelihood def ll(ciphertext,perm,mat): s=0.0 for i in range(len(ciphertext)-(k-1)): kmer = tuple([perm[c] for c in ciphertext[i:i+k]]) s = s + math.log(mat[kmer]) return s
Remove default value for k - this should never be necessary for this function
Remove default value for k - this should never be necessary for this function
Python
mit
gputzel/decode
--- +++ @@ -1,6 +1,6 @@ import math #Log-likelihood -def ll(ciphertext,perm,mat,k=2): +def ll(ciphertext,perm,mat): s=0.0 for i in range(len(ciphertext)-(k-1)): kmer = tuple([perm[c] for c in ciphertext[i:i+k]])
6b868e9bbb88dadbf27b7f1f6a4ab5fedc6c23e5
foolbox/tests/test_attacks_carlini_wagner.py
foolbox/tests/test_attacks_carlini_wagner.py
import numpy as np from foolbox.attacks import CarliniWagnerAttack as Attack def test_targeted_attack(bn_targeted_adversarial): adv = bn_targeted_adversarial attack = Attack() attack(adv) assert adv.image is not None assert adv.distance.value < np.inf def test_attack_impossible(bn_impossible): adv = bn_impossible attack = Attack() attack(adv) assert adv.image is None assert adv.distance.value == np.inf def test_attack_gl(gl_bn_adversarial): adv = gl_bn_adversarial attack = Attack() attack(adv) assert adv.image is None assert adv.distance.value == np.inf
import numpy as np from foolbox.attacks import CarliniWagnerAttack as Attack def test_targeted_attack(bn_targeted_adversarial): adv = bn_targeted_adversarial attack = Attack() attack(adv) assert adv.image is not None assert adv.distance.value < np.inf def test_attack_impossible(bn_impossible): adv = bn_impossible attack = Attack() attack(adv) assert adv.image is None assert adv.distance.value == np.inf def test_attack_gl(gl_bn_adversarial): adv = gl_bn_adversarial attack = Attack() attack(adv) assert adv.image is None assert adv.distance.value == np.inf
Revert "added new line at end of file to please flake8"
Revert "added new line at end of file to please flake8" This reverts commit 65fbfbc9117ba2ff06b4360faa8dddbf1ef8faa6.
Python
mit
bethgelab/foolbox,bethgelab/foolbox
9e27c8f803c42e65ec333ed1679ea70a5618f3c6
dunya/test_settings.py
dunya/test_settings.py
from settings import * if "motif" in DATABASES: del DATABASES["motif"] TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner" TEST_OUTPUT_VERBOSE = True TEST_OUTPUT_DESCRIPTIONS = True TEST_OUTPUT_DIR = "xmlrunner"
from settings import * if "motif" in DATABASES: del DATABASES["motif"] from xmlrunner.extra.djangotestrunner import XMLTestRunner from django.test.runner import DiscoverRunner from django.db import connections, DEFAULT_DB_ALIAS # We use the XMLTestRunner on CI class DunyaTestRunner(XMLTestRunner): #class DunyaTestRunner(DiscoverRunner): def setup_databases(self): result = super(DunyaTestRunner, self).setup_databases() connection = connections[DEFAULT_DB_ALIAS] cursor = connection.cursor() cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT') return result TEST_RUNNER = "dunya.test_settings.DunyaTestRunner" TEST_OUTPUT_VERBOSE = True TEST_OUTPUT_DESCRIPTIONS = True TEST_OUTPUT_DIR = "xmlrunner"
Update test settings to create the unaccent ext if needed
Update test settings to create the unaccent ext if needed
Python
agpl-3.0
MTG/dunya,MTG/dunya,MTG/dunya,MTG/dunya
--- +++ @@ -3,7 +3,21 @@ if "motif" in DATABASES: del DATABASES["motif"] -TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner" +from xmlrunner.extra.djangotestrunner import XMLTestRunner +from django.test.runner import DiscoverRunner +from django.db import connections, DEFAULT_DB_ALIAS + +# We use the XMLTestRunner on CI +class DunyaTestRunner(XMLTestRunner): +#class DunyaTestRunner(DiscoverRunner): + def setup_databases(self): + result = super(DunyaTestRunner, self).setup_databases() + connection = connections[DEFAULT_DB_ALIAS] + cursor = connection.cursor() + cursor.execute('CREATE EXTENSION IF NOT EXISTS UNACCENT') + return result + +TEST_RUNNER = "dunya.test_settings.DunyaTestRunner" TEST_OUTPUT_VERBOSE = True TEST_OUTPUT_DESCRIPTIONS = True TEST_OUTPUT_DIR = "xmlrunner"
ad415f26eec5c6a20c26123ccb6ce3e320ea9a69
zou/app/blueprints/crud/asset_instance.py
zou/app/blueprints/crud/asset_instance.py
from zou.app.models.asset_instance import AssetInstance from zou.app.services import assets_service, user_service from zou.app.utils import permissions from .base import BaseModelResource, BaseModelsResource class AssetInstancesResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, AssetInstance) class AssetInstanceResource(BaseModelResource): def __init__(self): BaseModelResource.__init__(self, AssetInstance) def check_read_permissions(self, instance): if permissions.has_manager_permissions(): return True else: asset_instance = self.get_model_or_404(instance["id"]) asset = assets_service.get_asset(asset_instance.asset_id) return user_service.check_has_task_related(asset["project_id"]) def check_update_permissions(self, asset_instance, data): if permissions.has_manager_permissions(): return True else: return user_service.check_working_on_entity( asset_instance["entity_id"] )
from zou.app.models.asset_instance import AssetInstance from zou.app.services import assets_service, user_service from zou.app.utils import permissions from .base import BaseModelResource, BaseModelsResource class AssetInstancesResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, AssetInstance) class AssetInstanceResource(BaseModelResource): def __init__(self): BaseModelResource.__init__(self, AssetInstance) self.protected_fields.append(["number"]) def check_read_permissions(self, instance): if permissions.has_manager_permissions(): return True else: asset_instance = self.get_model_or_404(instance["id"]) asset = assets_service.get_asset(asset_instance.asset_id) return user_service.check_has_task_related(asset["project_id"]) def check_update_permissions(self, asset_instance, data): if permissions.has_manager_permissions(): return True else: asset = assets_service.get_asset(asset_instance["asset_id"]) return user_service.check_has_task_related(asset["project_id"])
Change asset instance update permissions
Change asset instance update permissions * Do not allow to change instance number * Allow to change instance name by a CG artist
Python
agpl-3.0
cgwire/zou
--- +++ @@ -16,6 +16,7 @@ def __init__(self): BaseModelResource.__init__(self, AssetInstance) + self.protected_fields.append(["number"]) def check_read_permissions(self, instance): if permissions.has_manager_permissions(): @@ -29,6 +30,5 @@ if permissions.has_manager_permissions(): return True else: - return user_service.check_working_on_entity( - asset_instance["entity_id"] - ) + asset = assets_service.get_asset(asset_instance["asset_id"]) + return user_service.check_has_task_related(asset["project_id"])
1cdcc3ada4096a8352acc7f7c3e7825a7f44e0ac
examples/structures.py
examples/structures.py
from numba import struct, jit, double import numpy as np record_type = struct([('x', double), ('y', double)]) record_dtype = record_type.get_dtype() a = np.array([(1.0, 2.0), (3.0, 4.0)], dtype=record_dtype) @jit(argtypes=[record_type[:]]) def hypot(data): # return types of numpy functions are inferred result = np.empty_like(data, dtype=np.float64) # notice access to structure elements 'x' and 'y' via attribute access # You can also index by field name or field index: # data[i].x == data[i]['x'] == data[i][0] for i in range(data.shape[0]): result[i] = np.sqrt(data[i].x * data[i].x + data[i].y * data[i].y) return result print hypot(a) # Notice inferred return type print hypot.signature # Notice native sqrt calls and for.body direct access to memory... print hypot.lfunc
from numba import struct, jit, double import numpy as np record_type = struct([('x', double), ('y', double)]) record_dtype = record_type.get_dtype() a = np.array([(1.0, 2.0), (3.0, 4.0)], dtype=record_dtype) @jit(argtypes=[record_type[:]]) def hypot(data): # return types of numpy functions are inferred result = np.empty_like(data, dtype=np.float64) # notice access to structure elements 'x' and 'y' via attribute access # You can also index by field name or field index: # data[i].x == data[i]['x'] == data[i][0] for i in range(data.shape[0]): result[i] = np.sqrt(data[i].x * data[i].x + data[i].y * data[i].y) return result print hypot(a) # Notice inferred return type print hypot.signature # Notice native sqrt calls and for.body direct access to memory... #print hypot.lfunc
Comment out printing of function.
Comment out printing of function.
Python
bsd-2-clause
numba/numba,seibert/numba,stonebig/numba,jriehl/numba,sklam/numba,GaZ3ll3/numba,ssarangi/numba,shiquanwang/numba,cpcloud/numba,stuartarchibald/numba,pitrou/numba,GaZ3ll3/numba,pitrou/numba,cpcloud/numba,IntelLabs/numba,pitrou/numba,sklam/numba,cpcloud/numba,gdementen/numba,seibert/numba,jriehl/numba,gmarkall/numba,seibert/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,gdementen/numba,stonebig/numba,stuartarchibald/numba,stuartarchibald/numba,cpcloud/numba,pombredanne/numba,stonebig/numba,stefanseefeld/numba,stefanseefeld/numba,stuartarchibald/numba,numba/numba,GaZ3ll3/numba,stefanseefeld/numba,pitrou/numba,GaZ3ll3/numba,gdementen/numba,stefanseefeld/numba,jriehl/numba,gmarkall/numba,jriehl/numba,numba/numba,shiquanwang/numba,pitrou/numba,IntelLabs/numba,ssarangi/numba,gdementen/numba,sklam/numba,stonebig/numba,ssarangi/numba,IntelLabs/numba,pombredanne/numba,sklam/numba,gmarkall/numba,gmarkall/numba,pombredanne/numba,seibert/numba,stefanseefeld/numba,GaZ3ll3/numba,gdementen/numba,pombredanne/numba,stuartarchibald/numba,seibert/numba,numba/numba,ssarangi/numba,IntelLabs/numba,numba/numba,IntelLabs/numba,shiquanwang/numba,pombredanne/numba,ssarangi/numba,sklam/numba,jriehl/numba
--- +++ @@ -22,4 +22,4 @@ # Notice inferred return type print hypot.signature # Notice native sqrt calls and for.body direct access to memory... -print hypot.lfunc +#print hypot.lfunc
b78aebed4771015e6292638ac1980e3acaed4db9
heufybot/connection.py
heufybot/connection.py
from twisted.words.protocols import irc class HeufyBotConnection(irc.IRC): def __init__(self, protocol): self.protocol = protocol self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some point self.gecos = "PyHeufyBot IRC Bot" # TODO This will be set by a configuration at some point def connectionMade(self): self.cmdNICK(self.nick) self.cmdUSER(self.ident, self.gecos) def connectionLost(self, reason=""): print reason def dataReceived(self, data): print data def sendMessage(self, command, *parameter_list, **prefix): print command, " ".join(parameter_list) irc.IRC.sendMessage(self, command, *parameter_list, **prefix) def cmdNICK(self, nick): self.sendMessage("NICK", nick) def cmdUSER(self, ident, gecos): # RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all. # Pass 0 for usermodes instead. self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
from twisted.words.protocols import irc class HeufyBotConnection(irc.IRC): def __init__(self, protocol): self.protocol = protocol self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some point self.gecos = "PyHeufyBot IRC Bot" # TODO This will be set by a configuration at some point self.channels = {} self.usermodes = {} def connectionMade(self): self.cmdNICK(self.nick) self.cmdUSER(self.ident, self.gecos) def connectionLost(self, reason=""): print reason def dataReceived(self, data): print data def sendMessage(self, command, *parameter_list, **prefix): print command, " ".join(parameter_list) irc.IRC.sendMessage(self, command, *parameter_list, **prefix) def cmdNICK(self, nick): self.sendMessage("NICK", nick) def cmdUSER(self, ident, gecos): # RFC2812 allows usermodes to be set, but this isn't implemented much in IRCds at all. # Pass 0 for usermodes instead. self.sendMessage("USER", ident, "0", "*", ":{}".format(gecos))
Add dictionaries for channels and usermodes
Add dictionaries for channels and usermodes
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
--- +++ @@ -7,6 +7,8 @@ self.nick = "PyHeufyBot" # TODO This will be set by a configuration at some point self.ident = "PyHeufyBot" # TODO This will be set by a configuration at some point self.gecos = "PyHeufyBot IRC Bot" # TODO This will be set by a configuration at some point + self.channels = {} + self.usermodes = {} def connectionMade(self): self.cmdNICK(self.nick)
2afe09bcbcc728e98ec8da39b68ea65f4c270fdb
html5lib/trie/_base.py
html5lib/trie/_base.py
from __future__ import absolute_import, division, unicode_literals from collections import Mapping class Trie(Mapping): """Abstract base class for tries""" def keys(self, prefix=None): keys = super().keys() if prefix is None: return set(keys) # Python 2.6: no set comprehensions return set([x for x in keys if x.startswith(prefix)]) def has_keys_with_prefix(self, prefix): for key in self.keys(): if key.startswith(prefix): return True return False def longest_prefix(self, prefix): if prefix in self: return prefix for i in range(1, len(prefix) + 1): if prefix[:-i] in self: return prefix[:-i] raise KeyError(prefix) def longest_prefix_item(self, prefix): lprefix = self.longest_prefix(prefix) return (lprefix, self[lprefix])
from __future__ import absolute_import, division, unicode_literals from collections import Mapping class Trie(Mapping): """Abstract base class for tries""" def keys(self, prefix=None): keys = super(Trie, self).keys() if prefix is None: return set(keys) # Python 2.6: no set comprehensions return set([x for x in keys if x.startswith(prefix)]) def has_keys_with_prefix(self, prefix): for key in self.keys(): if key.startswith(prefix): return True return False def longest_prefix(self, prefix): if prefix in self: return prefix for i in range(1, len(prefix) + 1): if prefix[:-i] in self: return prefix[:-i] raise KeyError(prefix) def longest_prefix_item(self, prefix): lprefix = self.longest_prefix(prefix) return (lprefix, self[lprefix])
Make this in practice unreachable code work on Py2
Make this in practice unreachable code work on Py2
Python
mit
html5lib/html5lib-python,html5lib/html5lib-python,html5lib/html5lib-python
--- +++ @@ -7,7 +7,7 @@ """Abstract base class for tries""" def keys(self, prefix=None): - keys = super().keys() + keys = super(Trie, self).keys() if prefix is None: return set(keys)
2de06cda19c2d50c1362c9babd7c4bce735fb44a
product_configurator_mrp/__manifest__.py
product_configurator_mrp/__manifest__.py
{ 'name': 'Product Configurator Manufacturing', 'version': '11.0.1.0.0', 'category': 'Manufacturing', 'summary': 'BOM Support for configurable products', 'author': 'Pledra', 'license': 'AGPL-3', 'website': 'http://www.pledra.com/', 'depends': ['mrp', 'product_configurator'], "data": [ 'security/configurator_security.xml', 'security/ir.model.access.csv', 'views/product_view.xml', 'views/product_config_view.xml', 'views/mrp_view.xml', ], 'demo': [], 'test': [], 'installable': True, 'auto_install': False, }
{ 'name': 'Product Configurator Manufacturing', 'version': '11.0.1.0.0', 'category': 'Manufacturing', 'summary': 'BOM Support for configurable products', 'author': 'Pledra', 'license': 'AGPL-3', 'website': 'http://www.pledra.com/', 'depends': ['mrp', 'product_configurator'], "data": [ 'security/configurator_security.xml', 'security/ir.model.access.csv', 'views/product_view.xml', 'views/product_config_view.xml', 'views/mrp_view.xml', ], 'demo': [], 'test': [], 'installable': False, 'auto_install': False, }
Set product_configurator_mrp to uninstallable until fixing / refactoring
Set product_configurator_mrp to uninstallable until fixing / refactoring
Python
agpl-3.0
pledra/odoo-product-configurator,pledra/odoo-product-configurator,pledra/odoo-product-configurator
--- +++ @@ -16,6 +16,6 @@ ], 'demo': [], 'test': [], - 'installable': True, + 'installable': False, 'auto_install': False, }