commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
34463dc84b4a277a962335a8f350267d18444401 | ovp_projects/serializers/apply.py | ovp_projects/serializers/apply.py | from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(requ... | from ovp_projects import models
from ovp_projects.models.apply import apply_status_choices
from ovp_users.serializers import UserPublicRetrieveSerializer, UserApplyRetrieveSerializer
from rest_framework import serializers
class ApplyCreateSerializer(serializers.ModelSerializer):
email = serializers.EmailField(requ... | Add username, email and phone on Apply serializer | Add username, email and phone on Apply serializer
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-projects,OpenVolunteeringPlatform/django-ovp-projects |
333c5131f8e85bb5b545e18f3642b3c94148708d | tweet_s3_images.py | tweet_s3_images.py | import exifread
import os
class TweetS3Images(object):
def __init__(self, twitter, s3_client):
self._twitter = twitter
self._s3_client = s3_client
self._file = None
def send_image(self, bucket, image_name, cleanup=False):
temp_file = './{}'.format(image_name)
self._s3_... | import exifread
import os
class TweetS3Images(object):
def __init__(self, twitter, s3_client):
self._twitter = twitter
self._s3_client = s3_client
self._file = None
def send_image(self, bucket, image_name, cleanup=False):
temp_file = '/tmp/{}'.format(image_name)
self._... | Change temp directory and update tweet message. | Change temp directory and update tweet message.
| Python | mit | onema/lambda-tweet |
a8de8ebdfb31fd6fee78cfcdd4ef921ed54bf6f1 | currencies/context_processors.py | currencies/context_processors.py | from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['c... | from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'CURRENCY': request.session['c... | Remove the deprecated 'currency' context | Remove the deprecated 'currency' context
| Python | bsd-3-clause | bashu/django-simple-currencies,pathakamit88/django-currencies,panosl/django-currencies,pathakamit88/django-currencies,mysociety/django-currencies,bashu/django-simple-currencies,ydaniv/django-currencies,racitup/django-currencies,marcosalcazar/django-currencies,panosl/django-currencies,jmp0xf/django-currencies,ydaniv/dja... |
9b0dea78611dbaba468345d09613764cd81e6fd0 | ruuvitag_sensor/ruuvi.py | ruuvitag_sensor/ruuvi.py | import logging
import re
import sys
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win'):
from ruuvitag_sensor.ble_communication import BleCommunicationWin
... | import logging
import re
import sys
import os
from ruuvitag_sensor.url_decoder import UrlDecoder
_LOGGER = logging.getLogger(__name__)
macRegex = '[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$'
ruuviStart = 'ruuvi_'
if sys.platform.startswith('win') or os.environ.get('CI') == 'True':
# Use BleCommunicationWi... | Use BleCommunicationWin on CI tests | Use BleCommunicationWin on CI tests
| Python | mit | ttu/ruuvitag-sensor,ttu/ruuvitag-sensor |
804471657da0b97c46ce2d3d66948a70ca401b65 | scholrroles/behaviour.py | scholrroles/behaviour.py | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, ob... | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, ob... | Validate Model function to allow permission | Validate Model function to allow permission
| Python | bsd-3-clause | Scholr/scholr-roles |
1b95ca396b79cab73849c86c6e8cb14f21eeb9a5 | src/txkube/_compat.py | src/txkube/_compat.py | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode)... | # Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Helpers for Python 2/3 compatibility.
"""
from json import dumps
from twisted.python.compat import unicode
def dumps_bytes(obj):
"""
Serialize ``obj`` to JSON formatted ``bytes``.
"""
b = dumps(obj)
if isinstance(b, unicode)... | Add helper methods: 1. for converting from native string to bytes 2. for converting from native string to unicode | Add helper methods:
1. for converting from native string to bytes
2. for converting from native string to unicode
| Python | mit | LeastAuthority/txkube |
342cbd0f3ed0c6c03ba6c12614f5b991773ff751 | stash_test_case.py | stash_test_case.py | import os
import shutil
import subprocess
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = '.patches... | import os
import shutil
import unittest
from stash import Stash
class StashTestCase(unittest.TestCase):
"""Base class for test cases that test stash functionality.
This base class makes sure that all unit tests are executed in a sandbox
environment.
"""
PATCHES_PATH = os.path.join('test', '.patc... | Store temporary test directories in test path. | Store temporary test directories in test path.
| Python | bsd-3-clause | ton/stash,ton/stash |
d28c968088934f2aace7722ead000e8be56813ec | alg_sum_list.py | alg_sum_list.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def sum_list(num_ls):
"""Sum number list by recursion."""
if len(num_ls) == 1:
return num_ls[0]
else:
return num_ls[0] + sum_list(num_ls[1:])
def main():
num_ls = [0, 1, 2, 3, 4, 5]
p... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def sum_list_for(num_ls):
"""Sum number list by for loop."""
_sum = 0
for num in num_ls:
_sum += num
return _sum
def sum_list_recur(num_ls):
"""Sum number list by recursion."""
... | Complete benchmarking: for vs. recur | Complete benchmarking: for vs. recur
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
ec6c47796697ca26c12e2ca8269812442473dcd5 | pynuts/filters.py | pynuts/filters.py | """Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import QuerySelectField, QuerySelectMultipleField
def data(field):
"""Return data according to a specific field."""
if isinstance(field, QuerySelectMultipleField):
if field.data:
return escape(
... | # -*- coding: utf-8 -*-
"""Jinja environment filters for Pynuts."""
from flask import escape
from flask.ext.wtf import (
QuerySelectField, QuerySelectMultipleField, BooleanField)
def data(field):
"""Return data according to a specific field."""
if isinstance(field, QuerySelectMultipleField):
if ... | Add a read filter for boolean fields | Add a read filter for boolean fields
| Python | bsd-3-clause | Kozea/Pynuts,Kozea/Pynuts,Kozea/Pynuts |
91ee7fe40d345b71a39d4c07ecbdf23eb144f902 | pydarkstar/auction/auctionbase.py | pydarkstar/auction/auctionbase.py | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, *args, **kwargs):
sup... | """
.. moduleauthor:: Adam Gagorik <adam.gagorik@gmail.com>
"""
import pydarkstar.darkobject
import pydarkstar.database
class AuctionBase(pydarkstar.darkobject.DarkObject):
"""
Base class for Auction House objects.
:param db: database object
"""
def __init__(self, db, rollback=True, fail=False, *a... | Add AuctionBase fail and rollback properties. | Add AuctionBase fail and rollback properties.
| Python | mit | AdamGagorik/pydarkstar,LegionXI/pydarkstar |
5195a9baae1a87632c55adf390ecc5f32d1a44cb | dict_to_file.py | dict_to_file.py | #!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# ... | #!/usr/bin/python
import json
def storeJSON(dict, file_string):
with open(file_string, 'w') as fp:
json.dump(dict, fp, indent=4)
def storeTEX(dict, file_string):
with open(file_string, 'w') as fp:
fp.write("\\begin{tabular}\n")
fp.write(" \\hline\n")
fp.write(" ")
# ... | Fix latex output for splitted up/down values | Fix latex output for splitted up/down values
| Python | mit | knutzk/parse_latex_table |
e81cf35231e77d64f619169fc0625c0ae7d0edc8 | AWSLambdas/vote.py | AWSLambdas/vote.py | """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def vote_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
for record in event['Records']:
... | """
Watch Votes stream and update Sample ups and downs
"""
import json
import boto3
import time
import decimal
from boto3.dynamodb.conditions import Key, Attr
def vote_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Samples')
ratings = dict()
for record... | Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key. | Determine rating dispositions noted by the data changes and store them in a dictionary with the sample identification as the key.
| Python | mit | SandcastleApps/partyup,SandcastleApps/partyup,SandcastleApps/partyup |
a4f1fa704692894bcd568d02b23595e11910f791 | apps/searchv2/tests/test_utils.py | apps/searchv2/tests/test_utils.py | from datetime import datetime
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def test_remove_prefix(self):
values = ["django-me","django.me","django/me","django_me"]
f... | from datetime import datetime
from django.conf import settings
from django.test import TestCase
from package.tests import data, initial_data
from searchv2.utils import remove_prefix, clean_title
class UtilFunctionTest(TestCase):
def setUp(self):
self.values = []
for value in ["-me",".me",... | Fix to make site packages more generic in tests | Fix to make site packages more generic in tests
| Python | mit | pydanny/djangopackages,audreyr/opencomparison,miketheman/opencomparison,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages,miketheman/opencomparison,audreyr/opencomparison,benracine/opencomparison,nanuxbe/djangopackages,benracine/opencomparison,QLGu/djangopackages,nanuxbe/djangopac... |
cf4945e86de8f8365745afa3c3064dc093d25df8 | hunter/assigner.py | hunter/assigner.py | from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languag... | from .reviewsapi import ReviewsAPI
class Assigner:
def __init__(self):
self.reviewsapi = ReviewsAPI()
def certifications(self):
response = self.reviewsapi.certifications()
return [item['project_id'] for item in response if item['status'] == 'certified']
def projects_with_languag... | Improve names to reduce line size | Improve names to reduce line size
| Python | mit | anapaulagomes/reviews-assigner |
16ffb59ea744a95c7420fd8f4212d0c9a414f314 | tests/constants.py | tests/constants.py | TEST_TOKEN = 'abcdef'
TEST_USER = 'ubcdef'
TEST_DEVICE = 'my-phone'
| TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_DEVICE = 'droid2'
| Switch to using Pushover's example tokens and such | Switch to using Pushover's example tokens and such
| Python | mit | scolby33/pushover_complete |
e105b44e4c07b43c36290a8f5d703f4ff0b26953 | sqlshare_rest/util/query_queue.py | sqlshare_rest/util/query_queue.py | from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backe... | from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Query
from django.utils import timezone
def process_queue():
filtered = Query.objects.filter(is_finished=False)
try:
oldest_query = filtered.order_by('id')[:1].get()
except Query.DoesNotExist:
return
backe... | Remove a print statement that was dumb and breaking python3 | Remove a print statement that was dumb and breaking python3
| Python | apache-2.0 | uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest,uw-it-aca/sqlshare-rest |
78df776f31e5a23213b7f9d162a71954a667950a | opps/views/tests/__init__.py | opps/views/tests/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.views.tests.test_generic_detail import *
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from opps.views.tests.test_generic_detail import *
from opps.views.tests.test_generic_list import *
| Add test_generic_list on tests views | Add test_generic_list on tests views
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps |
76b40a801b69023f5983dcfa4ecd5e904792f131 | paypal/standard/pdt/forms.py | paypal/standard/pdt/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from paypal.standard.forms import PayPalStandardBaseForm
from paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayPalPDT
if django.VERSI... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
from paypal.standard.forms import PayPalStandardBaseForm
from paypal.standard.pdt.models import PayPalPDT
class PayPalPDTForm(PayPalStandardBaseForm):
class Meta:
model = PayPalPDT
if django.VERSI... | Add non-PayPal fields to exclude | Add non-PayPal fields to exclude
All the non-paypal fields are blanked if you don't exclude them from the form.
| Python | mit | spookylukey/django-paypal,rsalmaso/django-paypal,spookylukey/django-paypal,rsalmaso/django-paypal,rsalmaso/django-paypal,GamesDoneQuick/django-paypal,spookylukey/django-paypal,GamesDoneQuick/django-paypal |
68625abd9bce7411aa27375a2668d960ad2021f4 | cell/results.py | cell/results.py | """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket... | """cell.result"""
from __future__ import absolute_import
from __future__ import with_statement
from kombu.pools import producers
from .exceptions import CellError, NoReplyError
__all__ = ['AsyncResult']
class AsyncResult(object):
Error = CellError
NoReplyError = NoReplyError
def __init__(self, ticket... | Add result property to AsyncResult (it blocks if the result has not been previously retrieved, or return the result otherwise) | Add result property to AsyncResult
(it blocks if the result has not been previously retrieved, or return the
result otherwise)
| Python | bsd-3-clause | celery/cell,celery/cell |
9e2db322eed4a684ac9d7fe8944d9a8aff114929 | problib/example1/__init__.py | problib/example1/__init__.py | from sympy import symbols, cos, sin
from mathdeck import rand
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# # choose three random integers between 0 an... | from sympy import symbols, cos, sin
from mathdeck import rand
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# # choose three random integers between 0 an... | Change answers attribute to dictionary | Change answers attribute to dictionary
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck |
39a0094f87bf03229eacb81c5bc86b55c8893ceb | serving.py | serving.py | # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
... | # -*- coding: utf-8 -*-
"""Extend werkzeug request handler to suit our needs."""
import time
from werkzeug.serving import BaseRequestHandler
class ShRequestHandler(BaseRequestHandler):
"""Extend werkzeug request handler to suit our needs."""
def handle(self):
self.shRequestStarted = time.time()
... | Handle logging when a '%' character is in the URL. | Handle logging when a '%' character is in the URL.
| Python | bsd-3-clause | Sendhub/flashk_util |
379bec30964d34cde01b3a3cd9875efdaad5fc41 | create_task.py | create_task.py | #!/usr/bin/env python
import TheHitList
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--list", dest="list", help="List tasks in Inbox", default=False,action="store_true")
(opts,args) = parser.parse_args()
thl = TheHitList.Application()
if(opts.list):
... | #!/usr/bin/env python
import TheHitList
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("--show", dest="show", help="Show tasks in a list", default=None)
parser.add_option("--list", dest="list", help="Add task to a specific list", default=None)
(opts,args) = p... | Add support for adding a task to a specific list Add support for listing all tasks in a specific list | Add support for adding a task to a specific list
Add support for listing all tasks in a specific list | Python | mit | vasyvas/thehitlist,kfdm-archive/thehitlist |
c38261a4b04e7d64c662a6787f3ef07fc4686b74 | pybossa/sentinel/__init__.py | pybossa/sentinel/__init__.py | from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connec... | from redis import sentinel, StrictRedis
class Sentinel(object):
def __init__(self, app=None):
self.app = app
self.master = StrictRedis()
self.slave = self.master
if app is not None: # pragma: no cover
self.init_app(app)
def init_app(self, app):
self.connec... | Add socket connect timeout option to sentinel connection | Add socket connect timeout option to sentinel connection
| Python | agpl-3.0 | PyBossa/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,inteligencia-coletiva-lsd/pybossa,Scifabric/pybossa,Scifabric/pybossa,PyBossa/pybossa,OpenNewsLabs/pybossa,jean/pybossa,OpenNewsLabs/pybossa,geotagx/pybossa,geotagx/pybossa |
7666a29aafe22a51abfd5aee21b62c71055aea78 | tests/test_account.py | tests/test_account.py | # Filename: test_account.py
"""
Test the lendingclub2.accountmodule
"""
# PyTest
import pytest
# lendingclub2
from lendingclub2.account import InvestorAccount
from lendingclub2.error import LCError
class TestInvestorAccount(object):
def test_properties(self):
investor = InvestorAccount()
try:
... | # Filename: test_account.py
"""
Test the lendingclub2.accountmodule
"""
# PyTest
import pytest
# lendingclub2
from lendingclub2.account import InvestorAccount
from lendingclub2.error import LCError
class TestInvestorAccount(object):
def test_properties(self):
try:
investor = InvestorAccount... | Fix error in the case when no ID is provided | Fix error in the case when no ID is provided
| Python | mit | ahartoto/lendingclub2 |
4a1cf52683b782b76fb75fa9254a37a804dda1ea | mywebsite/tests.py | mywebsite/tests.py | from django.test import TestCase
from django.core.urlresolvers import reverse
class ViewsTestCase(TestCase):
def test_about_view(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "About")
| from django.test import TestCase
from django.core.urlresolvers import reverse
class ViewsTestCase(TestCase):
def test_about_view(self):
response = self.client.get(reverse('about'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "About")
def test_contact_p... | Add test for contact page | Add test for contact page
| Python | mit | TomGijselinck/mywebsite,TomGijselinck/mywebsite |
9f3abe5077fce0a2d7323a769fc063fca5b7aca8 | tests/test_bawlerd.py | tests/test_bawlerd.py | import os
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.conf.DEFAULT_CONFIG_FILENAME)
... | import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.c... | Add simple test for _load_file | Add simple test for _load_file
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler |
4b845f085c0a010c6de5f444dca0d57c0b3da3fa | wikipendium/jitishcron/models.py | wikipendium/jitishcron/models.py | from django.db import models
from django.utils import timezone
class TaskExecution(models.Model):
time = models.DateTimeField(default=timezone.now)
key = models.CharField(max_length=256)
execution_number = models.IntegerField()
class Meta:
unique_together = ('key', 'execution_number')
de... | from django.db import models
from django.utils import timezone
class TaskExecution(models.Model):
time = models.DateTimeField(default=timezone.now)
key = models.CharField(max_length=256)
execution_number = models.IntegerField()
class Meta:
unique_together = ('key', 'execution_number')
... | Add app_label to jitishcron TaskExecution model | Add app_label to jitishcron TaskExecution model
The TaskExecution model is loaded before apps are done loading, which in
Django 1.9 will no longer be permitted unless the model explicitly
specifies an app_label.
| Python | apache-2.0 | stianjensen/wikipendium.no,stianjensen/wikipendium.no,stianjensen/wikipendium.no |
bd07980d9545de5ae82d6bdc87eab23060b0e859 | sqflint.py | sqflint.py | import sys
import argparse
from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError
def analyze(code, writer=sys.stdout):
try:
result = parse(code)
except SQFParserError as e:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
... | import sys
import argparse
from sqf.parser import parse
import sqf.analyser
from sqf.exceptions import SQFParserError
def analyze(code, writer=sys.stdout):
try:
result = parse(code)
except SQFParserError as e:
writer.write('[%d,%d]:%s\n' % (e.position[0], e.position[1] - 1, e.message))
... | Fix parsing file - FileType already read | Fix parsing file - FileType already read
| Python | bsd-3-clause | LordGolias/sqf |
eaea19daa9ccb01b0dbef999c1f897fb9c4c19ee | Sketches/MH/pymedia/test_Input.py | Sketches/MH/pymedia/test_Input.py | #!/usr/bin/env python
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public Lic... | #!/usr/bin/env python
#
# (C) 2004 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public Lic... | Fix so both input and output are the same format! | Fix so both input and output are the same format!
Matt
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia |
c890112827c88680c7306f5c90e04cdd0575911a | refactoring/simplify_expr.py | refactoring/simplify_expr.py | """Simplify Expression"""
from transf import parse
import ir.match
import ir.path
parse.Transfs(r'''
simplify =
Binary(Eq(Int(_,_)),Binary(Minus(Int(_,_)),x,y),Lit(Int(_,_),0))
-> Binary(Eq(t),x,y) |
Unary(Not(Bool),Binary(Eq(t),x,y))
-> Binary(NotEq(t),x,y) |
Binary(And(_),x,x)
-> x
applicable =
ir.pat... | """Simplify Expression"""
from transf import parse
import ir.match
import ir.path
parse.Transfs(r'''
simplify =
Binary(Eq(t),Binary(Minus(t),x,y),Lit(t,0))
-> Binary(Eq(t),x,y) |
Unary(Not(Bool),Binary(Eq(t),x,y))
-> Binary(NotEq(t),x,y) |
Binary(And(_),x,x)
-> x
applicable =
ir.path.Applicable(
ir.pa... | Fix bug in simplify expression transformation. | Fix bug in simplify expression transformation.
| Python | lgpl-2.1 | mewbak/idc,mewbak/idc |
c2be2bbd4dc6766eca004253b66eae556950b7bd | mccurse/cli.py | mccurse/cli.py | """Package command line interface."""
import click
from .curse import Game, Mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
@cli.command()
@click.option(
'--refresh', is_flag=True, default=False,
help='Force refreshing of sea... | """Package command line interface."""
import curses
import click
from .curse import Game, Mod
from .tui import select_mod
# Static data
MINECRAFT = {'id': 432, 'name': 'Minecraft'}
@click.group()
def cli():
"""Minecraft Curse CLI client."""
# Initialize terminal for querying
curses.setupterm()
@cl... | Add mod selection to the search command | Add mod selection to the search command
| Python | agpl-3.0 | khardix/mccurse |
d21f32b8e5e069b79853724c3383af3beabc3686 | app/wine/admin.py | app/wine/admin.py | from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ... | from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "wine_type", "in_cellar",]
fieldsets = (
('Bottle', {
... | Add wine type to the list. | Add wine type to the list.
| Python | mit | ctbarna/cellar,ctbarna/cellar |
761b9935d0aa9361cef4093b633c54a3ab8e132a | anchore_engine/common/__init__.py | anchore_engine/common/__init__.py | """
Common utilities/lib for use by multiple services
"""
subscription_types = ['policy_eval', 'tag_update', 'vuln_update', 'repo_update', 'analysis_update']
resource_types = ['registries', 'users', 'images', 'policies', 'evaluations', 'subscriptions', 'archive']
bucket_types = ["analysis_data", "policy_bundles", "pol... | """
Common utilities/lib for use by multiple services
"""
subscription_types = ['policy_eval', 'tag_update', 'vuln_update', 'repo_update', 'analysis_update']
resource_types = ['registries', 'users', 'images', 'policies', 'evaluations', 'subscriptions', 'archive']
bucket_types = ["analysis_data", "policy_bundles", "pol... | Add some package and feed group types for api handling | Add some package and feed group types for api handling
Signed-off-by: Zach Hill <9de8c4480303b5335cd2a33eefe814615ba3612a@anchore.com>
| Python | apache-2.0 | anchore/anchore-engine,anchore/anchore-engine,anchore/anchore-engine |
641434ef0d1056fecdedbe7dacfe2d915b89408b | undecorated.py | undecorated.py | # -*- coding: utf-8 -*-
# Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu>
# 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... | # -*- coding: utf-8 -*-
# Copyright 2016 Ionuț Arțăriși <ionut@artarisi.eu>
# 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... | Remove module docstring as we have it on the func | Remove module docstring as we have it on the func
| Python | apache-2.0 | mapleoin/undecorated |
e8935189659e882f534f5605086dc76ce7ce881b | rdrf/rdrf/admin.py | rdrf/rdrf/admin.py | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
... | from django.contrib import admin
from models import *
from registry.groups.models import User
class SectionAdmin(admin.ModelAdmin):
list_display = ('code', 'display_name')
class RegistryFormAdmin(admin.ModelAdmin):
list_display = ('registry', 'name', 'sections')
class RegistryAdmin(admin.ModelAdmin):
... | Disable adding registries for non-superusers | Disable adding registries for non-superusers
| Python | agpl-3.0 | muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf,muccg/rdrf |
b393c41bf73a492bbd4a7bc50d16dd74c126c3db | grab.py | grab.py | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
# Putting this in front of expensive imports
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argum... | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_ids', help = 'IDs of runs to analyze... | Allow pulling batch of runs for analysis | Allow pulling batch of runs for analysis
| Python | mit | othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel |
cbf788d734f3a93b7f6b85269ba8f32e9be50a81 | p3p/urls.py | p3p/urls.py | from django.conf.urls.defaults import patterns, url
from p3p.views import XmlView, P3PView
urlpatterns = patterns('p3p.views',
url(r'^p3p.xml$', XmlView.as_view(), name='p3p'),
url(r'^policy.p3p$', P3PView.as_view(), name='policy'),
)
| from django.conf.urls import patterns, url
from p3p.views import XmlView, P3PView
urlpatterns = patterns('p3p.views',
url(r'^p3p.xml$', XmlView.as_view(), name='p3p'),
url(r'^policy.p3p$', P3PView.as_view(), name='policy'),
)
| Fix compatibility problems with django. | Fix compatibility problems with django.
| Python | apache-2.0 | jjanssen/django-p3p |
370809a6715675aee98b05bdd3c4d0c26a5d156a | meals/models.py | meals/models.py | from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')... | from django.db import models
class Wbw_list(models.Model):
list_id = models.IntegerField(unique=True)
name = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name
class Participant(models.Model):
wbw_list = models.ManyToManyField(Wbw_list, through='Participation')... | Allow meals with unknown payer | Allow meals with unknown payer
| Python | cc0-1.0 | joostrijneveld/eetvoudig,joostrijneveld/eetvoudig,joostrijneveld/eetvoudig |
a8115391de5a4490929cacc606282852b59f54c9 | IPython/html/widgets/widget_image.py | IPython/html/widgets/widget_image.py | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#... | """ButtonWidget class.
Represents a button in the frontend using a widget. Allows user to listen for
click events on the button and trigger backend code when the clicks are fired.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#... | Use CUnicode for width and height in ImageWidget | Use CUnicode for width and height in ImageWidget
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
bfdf65558e2f9b5b4e8d385b2911db374ffbfe03 | qipipe/qiprofile/update.py | qipipe/qiprofile/update.py | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, filename):
"""
Updates the qiprofile database from the clinical... | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clini... | Rename the filename argument to spreadsheet. | Rename the filename argument to spreadsheet.
| Python | bsd-2-clause | ohsu-qin/qipipe |
99f7b0edf2b84658e0a03149eb3e999293aa5e95 | src/model/train_xgb_model.py | src/model/train_xgb_model.py | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_to... | import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
import xgboost as xgb
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
train = joblib.load(utils.processed_data_path + 'train_is_booking_all_to... | Fix bugs in rf and xgb models | Fix bugs in rf and xgb models
| Python | bsd-3-clause | parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia |
6c4343837fb3b92e0cc5db83f124a31658359c47 | pymake/builtins.py | pymake/builtins.py | """
Implicit variables; perhaps in the future this will also include some implicit
rules, at least match-anything cancellation rules.
"""
variables = {
'RM': 'rm -f',
'.LIBPATTERNS': 'lib%.so lib%.a',
}
| """
Implicit variables; perhaps in the future this will also include some implicit
rules, at least match-anything cancellation rules.
"""
variables = {
'RM': 'rm -f',
'.LIBPATTERNS': 'lib%.so lib%.a',
'.PYMAKE': '1',
}
| Set .PYMAKE so we can distinguish pymake from gmake | Set .PYMAKE so we can distinguish pymake from gmake
| Python | mit | indygreg/pymake,mozilla/pymake,mozilla/pymake,mozilla/pymake |
fea5497e615b0b952d76c665284d4090d223fe96 | hoomd/md/pytest/test_table_pressure.py | hoomd/md/pytest/test_table_pressure.py | import hoomd
import io
import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank... | import hoomd
import io
import numpy
def test_table_pressure(simulation_factory, two_particle_snapshot_factory):
"""Test that write.table can log MD pressure values."""
thermo = hoomd.md.compute.ThermodynamicQuantities(hoomd.filter.All())
snap = two_particle_snapshot_factory()
if snap.communicator.rank... | Fix test failure in MPI | Fix test failure in MPI
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue |
af8e871eb2752f0fe75ccd7b2a12f81a5ef19d04 | tests/test_np.py | tests/test_np.py | from parser_tool import parse, get_parser
def test_np():
grammar = get_parser("grammars/test_np.fcfg", trace=0)
f = open("grammars/nounphrase.sample")
for line in f:
# remove newline
actual_line = line[:-1]
trees = parse(grammar, actual_line)
assert len(trees) > 0, "Failed... | from parser_tool import parse, get_parser
from utils import go_over_file
grammar = get_parser("grammars/test_np.fcfg", trace=0)
def test_np_positive():
def is_ok(sentence):
trees = parse(grammar, sentence)
assert len(trees) > 0, "Failed: %s" % sentence
go_over_file("grammars/nounphrase.sa... | Test both correct and wrong samples of noun phrase | Test both correct and wrong samples of noun phrase
Extended noun phrase test to check for the grammar refusing wrong
samples of noun phrases. Also added a utility module called
utils.py
| Python | mit | caninemwenja/marker,kmwenja/marker |
e32d470ba47973f3827a5f85e701826bbb08b621 | setup.py | setup.py | from distutils.core import setup
setup(
name='lcinvestor',
version=open('lcinvestor/VERSION').read(),
author='Jeremy Gillick',
author_email='none@none.com',
packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'],
package_data={
'lcinvestor': ['VERSION'],
'lcinvestor.... | from distutils.core import setup
setup(
name='lcinvestor',
version=open('lcinvestor/VERSION').read(),
author='Jeremy Gillick',
author_email='none@none.com',
packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'],
package_data={
'lcinvestor': ['VERSION'],
'lcinvestor.... | Update requirements. Add bat file | Update requirements. Add bat file
| Python | mit | jgillick/LendingClubAutoInvestor,ilyakatz/LendingClubAutoInvestor,ilyakatz/LendingClubAutoInvestor |
3cc90bb8ccce7b2feefe95173f095a71996d2633 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.execut... | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.execut... | Update to version 0.2 and some trove classifiers | Update to version 0.2 and some trove classifiers
| Python | bsd-3-clause | gulopine/steel |
48539fdd2a244218a1ee2a59d026d3759b9e3475 | setup.py | setup.py | from distutils.core import setup
import pkg_resources
import sys
requires = None
if sys.version_info < (2, 7):
requires = ['argparse']
version = pkg_resources.require("fitparse")[0].version
setup(
name='fitparse',
version=version,
description='Python library to parse ANT/Garmin .FIT files',
auth... | from distutils.core import setup
import pkg_resources
import sys
requires = ['six']
if sys.version_info < (2, 7):
requires.append('argparse')
version = pkg_resources.require("fitparse")[0].version
setup(
name='fitparse',
version=version,
description='Python library to parse ANT/Garmin .FIT files',
... | Add six as a dependency | Add six as a dependency
six is imported, but not listed as a dependency in setup.py. Add it.
| Python | isc | K-Phoen/python-fitparse |
e11c58495dfebf18763db308f55c75564a52c195 | sight.py | sight.py | #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 30... | #!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 30... | Stop use of almanac() and altazimuth() functions for now. | Stop use of almanac() and altazimuth() functions for now.
| Python | mit | zimolzak/Sight-reduction-problems |
83718336f5260e94cea32611fd7080966329ee2b | prompt_toolkit/filters/utils.py | prompt_toolkit/filters/utils.py | from __future__ import unicode_literals
from .base import Always, Never
from .types import SimpleFilter, CLIFilter
__all__ = (
'to_cli_filter',
'to_simple_filter',
)
def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
... | from __future__ import unicode_literals
from .base import Always, Never
from .types import SimpleFilter, CLIFilter
__all__ = (
'to_cli_filter',
'to_simple_filter',
)
_always = Always()
_never = Never()
def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
tur... | Reduce amount of Always/Never instances. (The are stateless.) | Reduce amount of Always/Never instances. (The are stateless.)
| Python | bsd-3-clause | melund/python-prompt-toolkit,jonathanslenders/python-prompt-toolkit,niklasf/python-prompt-toolkit |
fe296c62c1a75f89f206a0105591a274a7782b4e | factory/tools/cat_StartdLog.py | factory/tools/cat_StartdLog.py | #!/bin/env python
#
# cat_StartdLog.py
#
# Print out the StartdLog for a glidein output file
#
# Usage: cat_StartdLog.py logname
#
import sys
sys.path.append("lib")
import gWftLogParser
USAGE="Usage: cat_StartdLog.py <logname>"
def main():
try:
print gWftLogParser.get_CondorLog(sys.argv[1],"StartdLog")
... | #!/bin/env python
#
# cat_StartdLog.py
#
# Print out the StartdLog for a glidein output file
#
# Usage: cat_StartdLog.py logname
#
import sys
STARTUP_DIR=sys.path[0]
sys.path.append(os.path.join(STARTUP_DIR,"lib"))
import gWftLogParser
USAGE="Usage: cat_StartdLog.py <logname>"
def main():
try:
print gWft... | Allow for startup in a differend dir | Allow for startup in a differend dir
| Python | bsd-3-clause | holzman/glideinwms-old,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS |
3ac41e8b32aff3cf28590c8ab1a7abeae2b563f5 | shipper/helpers.py | shipper/helpers.py | # -*- coding: utf-8 -*-
import getpass
import random
class RandomSeed(object):
"""Creates a context with a temporarily used seed for the random
library. The state for the random functions is not modified
outside this context. Example usage::
with RandomSeed('reproducible seed'):
val... | # -*- coding: utf-8 -*-
import getpass
import random
import click
class RandomSeed(object):
"""Creates a context with a temporarily used seed for the random
library. The state for the random functions is not modified
outside this context. Example usage::
with RandomSeed('reproducible seed'):
... | Fix bug where print would be sent to stdout | Fix bug where print would be sent to stdout
| Python | mit | redodo/shipper |
b494a5b2ed94c1def6fb8bbbab5df5612ef30aa7 | tests/test_api.py | tests/test_api.py | from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def te... | import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-v... | Test a manifest with multiple files. | Test a manifest with multiple files.
| Python | mit | csdms/bmi-tester |
de84be15c4c519a680121e15c26d6eed6d091cd2 | toolbox/models.py | toolbox/models.py | from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(nb_filter=n1, nb_ro... | from keras.layers import Conv2D
from keras.models import Sequential
from toolbox.metrics import psnr
def compile_srcnn(input_shape, c=1, f1=9, f2=1, f3=5, n1=64, n2=32):
"""Compile an SRCNN model.
See https://arxiv.org/abs/1501.00092.
"""
model = Sequential()
model.add(Conv2D(n1, f1, kernel_init... | Upgrade to Keras 2 API | Upgrade to Keras 2 API
| Python | mit | qobilidop/srcnn,qobilidop/srcnn |
d2a0c23766cfd80f32b406503f47a5c5355bf6db | test_module_b/test_feat_3.py | test_module_b/test_feat_3.py | import unittest
import time
class TestE(unittest.TestCase):
def test_many_lines(self):
for i in xrange(100):
print 'Many lines', i
def test_feat_1_case_1(self):
time.sleep(0.5)
def test_feat_1_case_2(self):
time.sleep(0.5)
def test_feat_1_case_3(self):
time.sleep(0... | import unittest
import time
class TestE(unittest.TestCase):
def test_many_lines(self):
for i in xrange(100):
print 'Many lines', i
def test_feat_1_case_1(self):
time.sleep(0.5)
self.fail('Artificial fail one')
def test_feat_1_case_2(self):
time.sleep(0.5)
self.f... | Make some slow tests fail | Make some slow tests fail
| Python | mit | martinsmid/pytest-ui |
fcee154a123c7f9db81c92efce6d4a425dc0a3b1 | src/sentry/models/savedsearch.py | src/sentry/models/savedsearch.py | from __future__ import absolute_import, print_function
from django.db import models
from django.utils import timezone
from sentry.db.models import FlexibleForeignKey, Model, sane_repr
class SavedSearch(Model):
"""
A saved search query.
"""
__core__ = True
project = FlexibleForeignKey('sentry.Pr... | from __future__ import absolute_import, print_function
from django.db import models
from django.utils import timezone
from sentry.db.models import FlexibleForeignKey, Model, sane_repr
class SavedSearch(Model):
"""
A saved search query.
"""
__core__ = True
project = FlexibleForeignKey('sentry.Pr... | Add SavedSarch to project defaults | Add SavedSarch to project defaults
| Python | bsd-3-clause | mvaled/sentry,jean/sentry,mvaled/sentry,nicholasserra/sentry,BuildingLink/sentry,gencer/sentry,JackDanger/sentry,beeftornado/sentry,mvaled/sentry,zenefits/sentry,nicholasserra/sentry,daevaorn/sentry,gencer/sentry,beeftornado/sentry,fotinakis/sentry,JamesMura/sentry,JackDanger/sentry,fotinakis/sentry,looker/sentry,JackD... |
2eb8dfdfdc31c5315546ff7c89cd59f8d6cb4727 | tacker/__init__.py | tacker/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | Fix gettext wrong argument error in py34 | Fix gettext wrong argument error in py34
Closes-Bug: #1550202
Change-Id: I468bef7a8c0a9fa93576744e7869dfa5f2569fa0
| Python | apache-2.0 | priya-pp/Tacker,openstack/tacker,zeinsteinz/tacker,trozet/tacker,priya-pp/Tacker,stackforge/tacker,openstack/tacker,trozet/tacker,openstack/tacker,stackforge/tacker,zeinsteinz/tacker |
f79b8834ff88b9f4517d464407240f2bce6c7f5a | tests/test_parse.py | tests/test_parse.py | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements... | from hypothesis_auto import auto_pytest_magic
from isort import parse
from isort.settings import Config
TEST_CONTENTS = """
import xyz
import abc
def function():
pass
"""
def test_file_contents():
(
in_lines,
out_lines,
import_index,
place_imports,
import_placements... | Fix signature of test case | Fix signature of test case
| Python | mit | PyCQA/isort,PyCQA/isort |
cca387dc889b12457c1b1d8bb7b61ad3d2bbd57a | tests/test_room.py | tests/test_room.py | import unittest
from classes.room import Room
class RoomClassTest(unittest.TestCase):
pass
# def test_create_room_successfully(self):
# my_class_instance = Room()
# initial_room_count = len(my_class_instance.all_rooms)
# blue_office = my_class_instance.create_room("Blue", "office")
... | import unittest
from classes.room import Room
from classes.dojo import Dojo
class RoomClassTest(unittest.TestCase):
def test_add_occupant(self):
my_class_instance = Room("Blue", "office", 6)
my_dojo_instance = Dojo()
new_fellow = my_dojo_instance.add_person("fellow", "Peter", "Musonye", "Y... | Add tests for class Room | Add tests for class Room
| Python | mit | peterpaints/room-allocator |
4c765b0765b8c5eb43b5850d9c3877d37d40ed5b | qr_code/urls.py | qr_code/urls.py | from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path('images/serve-qr-code-image/', views.serve_qr_code_image, name='serve_qr_code_image')
]
| from django.conf import settings
from django.urls import path
from qr_code import views
app_name = 'qr_code'
urlpatterns = [
path(getattr(settings, 'SERVE_QR_CODE_IMAGE_PATH', 'images/serve-qr-code-image/'), views.serve_qr_code_image, name='serve_qr_code_image')
]
| Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served. | Introduce setting `SERVE_QR_CODE_IMAGE_PATH` to configure the path under which QR Code images are served.
| Python | bsd-3-clause | dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code,dprog-philippe-docourt/django-qr-code |
21b8c54d564fb48d9982e8377e0f2a8c0effb96e | rasa/nlu/run.py | rasa/nlu/run.py | import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_str... | import logging
import typing
from typing import Optional, Text
from rasa.shared.utils.cli import print_info, print_success
from rasa.shared.nlu.interpreter import RegexInterpreter
from rasa.shared.constants import INTENT_MESSAGE_PREFIX
from rasa.nlu.model import Interpreter
from rasa.shared.utils.io import json_to_str... | Swap parse call for synchronous_parse | Swap parse call for synchronous_parse
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu |
ebc7aa75d871929220ee0197aaf92a24efc3f9da | PVGeo/__main__.py | PVGeo/__main__.py | import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://cdn.rawgit.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in platform.syst... | import os
import sys
import platform
def GetInstallationPaths():
path = os.path.dirname(os.path.dirname(__file__))
PYTHONPATH = path
PV_PLUGIN_PATH = '%s/%s' % (path, 'PVPlugins')
script = 'curl -s https://raw.githubusercontent.com/OpenGeoVis/PVGeo/master/installMac.sh | sh -s'
if 'darwin' in pl... | Use non-cached sever for mac install script | Use non-cached sever for mac install script
| Python | bsd-3-clause | banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics |
1fbea5f1a10613eba97ef3ff66d7ba197837b1e9 | tsv2md/__init__.py | tsv2md/__init__.py | import fileinput
import textwrap
import sys
class Table(object):
def __init__(self):
self.lines = []
self.width = 20
def feed(self,line):
self.lines.append(line.split("\t"))
def print_sep(self):
for _ in range(len(self.lines[0])):
print "-"*self.width,
... | import fileinput
import textwrap
import sys
class Table(object):
def __init__(self):
self.lines = []
self.width = 20
def feed(self,line):
self.lines.append(line.split("\t"))
def print_sep(self):
for _ in range(len(self.lines[0])):
print "-"*self.width,
... | Remove superfluous option from print_row. | Remove superfluous option from print_row.
| Python | mit | wouteroostervld/tsv2md |
8b34daa2a61422c79fef2afd9137bf2f1c2a5b12 | project3/webscale/synthesizer/admin.py | project3/webscale/synthesizer/admin.py | from django.contrib import admin
from .models import ApplicationTable,OldUser,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
# Register your models here.
admin.site.register(ApplicationTable)
admin.site.register(OldUser)
admin.site.register(Snippit)
admin.site.register(SnippitData)
admin.site.register(HolesTable)
ad... | from django.contrib import admin
from .models import ApplicationTable,Snippit,SnippitData,HolesTable,GoogleAuth,Comment
# Register your models here.
admin.site.register(ApplicationTable)
admin.site.register(Snippit)
admin.site.register(SnippitData)
admin.site.register(HolesTable)
admin.site.register(GoogleAuth)
admin.s... | Delete calls to Old User model | Delete calls to Old User model
| Python | mit | 326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer,326-WEBSCALE/webscale-synthesizer |
b5fbaafddf41f4efc1a4841a8a35f2fda094e60a | js2py/prototypes/jsfunction.py | js2py/prototypes/jsfunction.py | # python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
# todo fix apply and bind
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__cod... | # python 3 support
import six
if six.PY3:
basestring = str
long = int
xrange = range
unicode = str
class FunctionPrototype:
def toString():
if not this.is_callable():
raise TypeError('toString is not generic!')
args = ', '.join(this.code.__code__.co_varnames[:this.argco... | Fix injected local 'arguments' not working in list comprehension in bind. | Fix injected local 'arguments' not working in list comprehension in bind.
| Python | mit | PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py,PiotrDabkowski/Js2Py |
aa966c1a208f2c3f4b2a2a196c39b1df5a0b67c8 | basics/candidate.py | basics/candidate.py |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
sel... |
import numpy as np
class Bubble2D(object):
"""
Class for candidate bubble portions from 2D planes.
"""
def __init__(self, props):
super(Bubble2D, self).__init__()
self._channel = props[0]
self._y = props[1]
self._x = props[2]
self._major = props[3]
sel... | Add methods that need to be implemented | Add methods that need to be implemented
| Python | mit | e-koch/BaSiCs |
fbe05b7e2fe97724cb126f0a5b5dd656591d41d7 | apps/polls/tests.py | apps/polls/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | import datetime
from django.utils import timezone
from django.test import TestCase
from apps.polls.models import Poll
class PollMethodTests(TestCase):
def test_was_published_recently_with_future_poll(self):
"""
was_published_recently_with_future_poll() should return False for for polls whose
... | Create a test to expose the bug | Create a test to expose the bug
| Python | bsd-3-clause | datphan/teracy-tutorial,teracyhq/django-tutorial |
5b735dff075cb4fb2e9fd89dc4d872281210964d | config/regenerate_launch_files.py | config/regenerate_launch_files.py | #!/usr/bin/env python3
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package: str) -> str:
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path: str) -> str:
"""
>>> get_file_ro... | #!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
... | Make compatible with Python 2 and 3. | Make compatible with Python 2 and 3.
| Python | mit | masasin/spirit,masasin/spirit |
07b6484b33d687a7c32f91b5c2274d54c1e106ff | stormtracks/settings/default_stormtracks_settings.py | stormtracks/settings/default_stormtracks_settings.py | # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtr... | # *** DON'T MODIFY THIS FILE! ***
#
# Instead copy it to stormtracks_settings.py
#
# Default settings for project
# This will get copied to $HOME/.stormtracks/
# on install.
import os
SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
# expandvars expands e.g. $HOME
DATA_DIR = os.path.expandvars('$HOME/stormtr... | Change the location of stormtracks data. | Change the location of stormtracks data.
| Python | mit | markmuetz/stormtracks,markmuetz/stormtracks |
faf861e53c1d4f554da82cd66b6b8de4fa7a2ab7 | src/main/python/infra_buddy/notifier/datadog.py | src/main/python/infra_buddy/notifier/datadog.py | from infra_buddy.context.deploy_ctx import DeployContext
import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=k... | import datadog as dd
class DataDogNotifier(object):
def __init__(self, key, deploy_context):
# type: (DeployContext) -> None
super(DataDogNotifier, self).__init__()
self.deploy_context = deploy_context
dd.initialize(api_key=key)
def notify_event(self, title, type, message):
... | Remove import for type annotation | Remove import for type annotation
| Python | apache-2.0 | AlienVault-Engineering/infra-buddy |
34e0934d2f62a98728601a18126fa21eb50cf5a5 | doubles/testing.py | doubles/testing.py | class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
return 'class method'
def __init__(self, name, age):
self.name = name
self.ag... | class User(object):
"""An importable dummy class used for testing purposes."""
class_attribute = 'foo'
@staticmethod
def static_method():
return 'static_method return value'
@classmethod
def class_method(cls):
return 'class_method return value'
def __init__(self, name, ag... | Return easily identifiable values from User methods. | Return easily identifiable values from User methods.
| Python | mit | uber/doubles |
a5b70775d106d07acfb54ce0b3998a03ed195de7 | test/uritemplate_test.py | test/uritemplate_test.py | import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = t... | import uritemplate
import simplejson
import sys
filename = sys.argv[1]
print "Running", filename
f = file(filename)
testdata = simplejson.load(f)
try:
desired_level = int(sys.argv[2])
except IndexError:
desired_level = 4
for name, testsuite in testdata.iteritems():
vars = testsuite['variables']
testcases = t... | Handle lists of possibilities in tests | Handle lists of possibilities in tests
| Python | apache-2.0 | uri-templates/uritemplate-py |
48362fa70ab20f66f4f398c68ab252dfd36c6117 | crust/fields.py | crust/fields.py | class Field(object):
"""
Base class for all field types
"""
# This tracks each time a Field instance is created. Used to retain order.
creation_counter = 0
def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs):
super(Field, self).__init__(*args, **kwargs)
... | class Field(object):
"""
Base class for all field types
"""
# This tracks each time a Field instance is created. Used to retain order.
creation_counter = 0
def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs):
super(Field, self).__init__(*args, **kwargs)
... | Make provisions for dehydrating a field | Make provisions for dehydrating a field
| Python | bsd-2-clause | dstufft/crust |
24538a6e91983974c729a559ab24ee90ad529d7e | engines/string_template_engine.py | engines/string_template_engine.py | #!/usr/bin/env python3
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, **kwargs):
... | #!/usr/bin/env python3
"""Provide the standard Python string.Template engine."""
from __future__ import print_function
from string import Template
from . import Engine
class StringTemplate(Engine):
"""String.Template engine."""
handle = 'string.Template'
def __init__(self, template, tolerant=False,... | Implement tolerant handling in string.Template engine. | Implement tolerant handling in string.Template engine.
| Python | mit | blubberdiblub/eztemplate |
73d2c1e1675ed9e7fe2bc389ec0079c5c6ce73ee | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from .. import e, inf, nan, pi
| from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| Make the array API constants into dimension 0 arrays | Make the array API constants into dimension 0 arrays
The spec does not actually specify whether these should be dimension 0 arrays
or Python floats (which they are in NumPy). However, making them dimension 0
arrays is cleaner, and ensures they also have all the methods and attributes
that are implemented on the ndarra... | Python | bsd-3-clause | jakirkham/numpy,simongibbons/numpy,seberg/numpy,mattip/numpy,mhvk/numpy,mattip/numpy,anntzer/numpy,endolith/numpy,jakirkham/numpy,charris/numpy,seberg/numpy,mattip/numpy,anntzer/numpy,simongibbons/numpy,numpy/numpy,simongibbons/numpy,mhvk/numpy,simongibbons/numpy,charris/numpy,rgommers/numpy,jakirkham/numpy,rgommers/nu... |
0933e4c671ca1297378b2ad388933e11265321d0 | traptor/dd_monitoring.py | traptor/dd_monitoring.py | ###############################################################################
# This is a very strange handler setup, but this is how it's documented.
# See https://github.com/DataDog/datadogpy#quick-start-guide
###############################################################################
import os
from datadog imp... | ###############################################################################
# This is a very strange handler setup, but this is how it's documented.
# See https://github.com/DataDog/datadogpy#quick-start-guide
###############################################################################
import os
from datadog imp... | Use getenv instead of environment dict | Use getenv instead of environment dict
| Python | mit | istresearch/traptor,istresearch/traptor |
264075d9b313f5c2677e32fcf5d340bba73f0b0e | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py | # Generated by Django 2.2.24 on 2021-09-13 21:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
... | # Generated by Django 2.2.24 on 2021-09-14 17:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_manager', '0018_migrate_case_search_labels'),
]
operations = [
migrations.AddField(
model_name='exchangeapplication',
... | Fix migration with help text | Fix migration with help text
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
a1e7cade8fb5e4a301244a8a0cef382b49399d46 | us_ignite/awards/admin.py | us_ignite/awards/admin.py | from django.contrib import admin
from us_ignite.awards.models import Award
class AwardAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
admin.site.register(Award, AwardAdmin)
| from django.contrib import admin
from us_ignite.awards.models import Award, ApplicationAward
class AwardAdmin(admin.ModelAdmin):
list_display = ('name', 'slug')
class ApplicationAwardAdmin(admin.ModelAdmin):
list_display = ('award', 'application', 'created')
date_hierarchy = 'created'
list_filter = ... | Add mechanics to award applications. | Add mechanics to award applications.
https://github.com/madewithbytes/us_ignite/issues/77
The awards can be given in the admin section.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite |
e2b382a69473dcfa6d93442f3ad3bc21ee6c90a0 | examples/tic_ql_tabular_selfplay_all.py | examples/tic_ql_tabular_selfplay_all.py | '''
In this example the Q-learning algorithm is used via self-play
to learn the state-action values for all Tic-Tac-Toe positions.
'''
from capstone.game.games import TicTacToe
from capstone.game.utils import tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
from ca... | '''
The Q-learning algorithm is used to learn the state-action values for all
Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
from capstone.game.players import GreedyQF, RandPlayer
from capstone.game.utils import play_series, tic2pdf
from capstone.rl impo... | Fix Tic-Tac-Toe Q-learning tabular self-play example | Fix Tic-Tac-Toe Q-learning tabular self-play example
| Python | mit | davidrobles/mlnd-capstone-code |
b09c7d7c8a0949e6c0a370e7608e51b1060b1ee8 | meinberlin/apps/mapideas/forms.py | meinberlin/apps/mapideas/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
def __init__(self, *args, **kwar... | from django import forms
from django.utils.translation import ugettext_lazy as _
from adhocracy4.categories.forms import CategorizableFieldMixin
from adhocracy4.maps import widgets as maps_widgets
from . import models
class MapIdeaForm(CategorizableFieldMixin, forms.ModelForm):
class Media:
js = ('js/se... | Initialize select dropdown for categories with maps | Initialize select dropdown for categories with maps
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin |
b5e13cb92f539545873d59553c03e1523eac1dbb | recipes/kaleido-core/run_test.py | recipes/kaleido-core/run_test.py | from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' ... | from subprocess import Popen, PIPE
import json
import platform
# Remove "sys.exit" after feedstock creation when running
# on linux-anvil-cos7-x86_64 image
if platform.system() == "Linux":
import sys
sys.exit(0)
if platform.system() == "Windows":
ext = ".cmd"
else:
ext = ""
p = Popen(
['kaleido' ... | Fix hanging test on MacOS | Fix hanging test on MacOS
| Python | bsd-3-clause | kwilcox/staged-recipes,ocefpaf/staged-recipes,stuertz/staged-recipes,johanneskoester/staged-recipes,jochym/staged-recipes,SylvainCorlay/staged-recipes,goanpeca/staged-recipes,igortg/staged-recipes,mariusvniekerk/staged-recipes,conda-forge/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,johanneskoeste... |
c3de0c71a8392a884f8fd08dbee8f337ba7833c7 | src/ggrc/migrations/versions/20130724021606_2bf7c04016c9_person_email_must_be.py | src/ggrc/migrations/versions/20130724021606_2bf7c04016c9_person_email_must_be.py | """Person.email must be unique
Revision ID: 2bf7c04016c9
Revises: 2b709b655bf
Create Date: 2013-07-24 02:16:06.282258
"""
# revision identifiers, used by Alembic.
revision = '2bf7c04016c9'
down_revision = '2b709b655bf'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade... | """Person.email must be unique
Revision ID: 2bf7c04016c9
Revises: d3af6d071ef
Create Date: 2013-07-24 02:16:06.282258
"""
# revision identifiers, used by Alembic.
revision = '2bf7c04016c9'
down_revision = 'd3af6d071ef'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade... | Update 'down' version in migration due to merge | Update 'down' version in migration due to merge
| Python | apache-2.0 | AleksNeStu/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,uskudnik/ggrc-core,josthkko/ggrc-core,edofic/ggrc-core,j0gurt/ggrc-core,uskudnik/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,vladan-m/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,uskudnik/ggrc-core,hasanalom/ggrc... |
ac9ee17f93b90a79b629d222d8c2846debed6f04 | chalice/__init__.py | chalice/__init__.py | from chalice.app import Chalice
from chalice.app import (
ChaliceViewError, BadRequestError, UnauthorizedError, ForbiddenError,
NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig
)
__version__ = '0.8.0'
| from chalice.app import Chalice
from chalice.app import (
ChaliceViewError, BadRequestError, UnauthorizedError, ForbiddenError,
NotFoundError, ConflictError, TooManyRequestsError, Response, CORSConfig,
CustomAuthorizer, CognitoUserPoolAuthorizer
)
__version__ = '0.8.0'
| Add authorizers as top level import | Add authorizers as top level import
| Python | apache-2.0 | awslabs/chalice |
9b18cc62dc0338a9dff6ae7dd448a4dca960c941 | accounts/forms.py | accounts/forms.py | """forms for accounts app
"""
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from accounts.tokens import LoginTokenGenerator
USER = get_user_model()
class LoginForm(forms.Form):... | """forms for accounts app
"""
from django import forms
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse_lazy
from accounts.tokens import LoginTokenGenerator
USER = get_user_m... | Add the token as a get parameter | Add the token as a get parameter
| Python | mit | randomic/aniauth-tdd,randomic/aniauth-tdd |
b92c75e1145915892723206a77593b9701e608bf | webapp/hello.py | webapp/hello.py | from flask import Flask, render_template, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from scipy import misc
import numpy as np
from VGG16_gs_model import *
# sett opp nevralt nettverk:
model = VGG_16()
fpath = '../models/vgg16_sg.h5';
model.load_weights(fpath)
# Sett opp webapp
app... | from flask import Flask, render_template, request
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from scipy import misc
import numpy as np
from VGG16_gs_model import *
# sett opp nevralt nettverk:
model = VGG_16()
fpath = '../models/vgg16_sg.h5';
model.load_weights(fpath)
# Sett opp webapp
app... | Add port on flask app | Add port on flask app
| Python | apache-2.0 | jchalvorsen/ConsultantOrNot,jchalvorsen/ConsultantOrNot,jchalvorsen/ConsultantOrNot |
c671adabcae728fb6992bb91001838b3b9cbfd8a | wrappers/python/setup.py | wrappers/python/setup.py | from distutils.core import setup
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
setup(
name='python3-indy',
version=PKG_VERSION,
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache-2.0',
author='Vyacheslav Gudkov',
author_email='vyach... | from distutils.core import setup
import os
PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0'
TEST_DEPS = [
'pytest<3.7', 'pytest-asyncio', 'base58'
]
setup(
name='python3-indy',
version=PKG_VERSION,
packages=['indy'],
url='https://github.com/hyperledger/indy-sdk',
license='MIT/Apache... | Make test dependencies installable as an extra | Make test dependencies installable as an extra
Signed-off-by: Daniel Bluhm <6df8625bb799b640110458f819853f591a9910cb@sovrin.org>
| Python | apache-2.0 | Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/i... |
62f8c68165f7f519b5769c99db00ef8822e9f534 | yatsm/log_yatsm.py | yatsm/log_yatsm.py | import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT)
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logger = logging.getLogger('yatsm')
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
| import logging
_FORMAT = '%(asctime)s:%(levelname)s:%(module)s.%(funcName)s:%(message)s'
_formatter = logging.Formatter(_FORMAT, '%H:%M:%S')
_handler = logging.StreamHandler()
_handler.setFormatter(_formatter)
logger = logging.getLogger('yatsm')
logger.addHandler(_handler)
logger.setLevel(logging.INFO)
| Change time format in logs | Change time format in logs
| Python | mit | c11/yatsm,valpasq/yatsm,c11/yatsm,ceholden/yatsm,valpasq/yatsm,ceholden/yatsm |
2d85ea5594cf1395fef6caafccc690ed9a5db472 | crabigator/tests/test_wanikani.py | crabigator/tests/test_wanikani.py | """Tests for crabigator.wanikani."""
from __future__ import print_function
from crabigator.wanikani import WaniKani, WaniKaniError
import os
from unittest import TestCase
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestCa... | """Tests for crabigator.wanikani."""
from __future__ import print_function
import os
from unittest import TestCase
from crabigator.wanikani import WaniKani, WaniKaniError
# TestCase exposes too many public methods. Disable the pylint warning for it.
# pylint: disable=too-many-public-methods
class TestWaniKani(TestC... | Change import order to satisfy pylint. | Change import order to satisfy pylint.
| Python | mit | jonesinator/crabigator |
835aa149e4bccd7bcf94390d1a878133b79b768f | yaacl/models.py | yaacl/models.py | # -*- coding: utf-8 -*-
from datetime import datetime
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class ACL(models.Model):
acl_list = {}
resource = models.CharField(
_("R... | # -*- coding: utf-8 -*-
from datetime import datetime
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class ACL(models.Model):
acl_list = {}
resource = models.CharField(
_("R... | Use `auto_now_add` to make ACL.created_at timezone aware | Use `auto_now_add` to make ACL.created_at timezone aware
| Python | mit | Alkemic/yaACL,Alkemic/yaACL |
9685ab2793ad9dc79df5c6f1bd1c22b302769b2c | py/garage/garage/asyncs/utils.py | py/garage/garage/asyncs/utils.py | __all__ = [
'CircuitBreaker',
'timer',
]
import asyncio
import collections
import time
class CircuitBreaker:
"""Break (disconnect) when no less than `count` errors happened
within last `period` seconds.
"""
class Disconnected(Exception):
pass
def __init__(self, *, count, peri... | __all__ = [
'CircuitBreaker',
'timer',
]
import asyncio
import collections
import time
class CircuitBreaker:
"""Break (disconnect) when no less than `count` errors happened
within last `period` seconds.
"""
class Disconnected(Exception):
pass
def __init__(self, *, count, peri... | Make CircuitBreaker.count return connection status | Make CircuitBreaker.count return connection status
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage |
fee9504387319dd406eb5131281c6344a427fad7 | insanity/layers.py | insanity/layers.py | import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.nnet import softmax
from theano.tensor import shared_randomstreams
from theano.tensor.signal import downsample
class FullyConnectedLayer(object):
def __init__(self, previousLayer, numNeurons, activation... | import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.nnet import softmax
from theano.tensor import shared_randomstreams
from theano.tensor.signal import downsample
class FullyConnectedLayer(object):
def __init__(self, previousLayer, numNeurons, activation... | Add processing procedure to FullyConnectedLayer. | Add processing procedure to FullyConnectedLayer.
| Python | cc0-1.0 | cn04/insanity |
4425aa1170a1acd3ed69c32ba5e3885301593524 | salt/returners/redis_return.py | salt/returners/redis_return.py | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... | Restructure redis returner, since it did notwork before anyway | Restructure redis returner, since it did notwork before anyway
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
b2d9b56ceb96718d1f3edc8ec019ca7218e33e7d | src/rnaseq_lib/math/__init__.py | src/rnaseq_lib/math/__init__.py | import numpy as np
# Outlier
def iqr_bounds(ys):
"""
Return upper and lower bound for an array of values
Lower bound: Q1 - (IQR * 1.5)
Upper bound: Q3 + (IQR * 1.5)
:param list ys: List of values to calculate IQR
:return: Upper and lower bound
:rtype: tuple(float, float)
"""
quar... | import numpy as np
# Outlier
def iqr_bounds(ys):
"""
Return upper and lower bound for an array of values
Lower bound: Q1 - (IQR * 1.5)
Upper bound: Q3 + (IQR * 1.5)
:param list ys: List of values to calculate IQR
:return: Upper and lower bound
:rtype: tuple(float, float)
"""
quar... | Add docstring for softmax normalization function | Add docstring for softmax normalization function
| Python | mit | jvivian/rnaseq-lib,jvivian/rnaseq-lib |
78a9ee621e20bf1fe930bd0d2046715c5737df03 | web/patlms-web/web/urls.py | web/patlms-web/web/urls.py | """web URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... | """web URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... | Add general module to general namespace in web module | Add general module to general namespace in web module
| Python | mit | chyla/slas,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/pat-lms,chyla/slas,chyla/slas,chyla/slas,chyla/slas,chyla/pat-lms,chyla/slas,chyla/slas |
4dbe38996e5bfd6b3f12be1f9cde8de379108934 | keysmith.py | keysmith.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import random
import sys
def natural_int(x):
x = int(x)
if x < 0:
raise argparse.ArgumentTypeError(str(x) + ' is not a natural number.')
return x
def random_word(words):
""" Generate a random word. """
r... | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import random
import sys
def natural_int(x):
x = int(x)
if x < 0:
raise argparse.ArgumentTypeError(str(x) + ' is not a natural number.')
return x
def random_word(words):
""" Generate a random word. """
r... | Add a description to the argparser. | Add a description to the argparser.
| Python | bsd-3-clause | dmtucker/keysmith |
f5a5f185958ed3088518f3a2fca15ff7b57e982c | manage.py | manage.py | # manage.py
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
ma... | # manage.py
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Command
from app import create_app, db
from app.models import Users, Agencies, Requests, Responses, Events, Reasons, Permissions, Roles
app = create_app(os.getenv('FLASK_CONFIG') or 'def... | Fix a problem with the celery cli commoand Allows runserver to be used separately from celery. | Fix a problem with the celery cli commoand
Allows runserver to be used separately from celery.
| Python | apache-2.0 | CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords,CityOfNewYork/NYCOpenRecords |
f511eb39aef5005df6ac5d234d1da7ae829983f9 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
from website.app import init_app
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
init_app(set_backends=True, routes=False, attach_request_handlers=False... | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings')
from django.core.management import execute_from_command_line
from website.app import init_app
init_app(set_backends=True, routes=False, attach_request_handlers=... | Move init_app after DJANGO_SETTINGS_MODULE set up | Move init_app after DJANGO_SETTINGS_MODULE set up
| Python | apache-2.0 | GageGaskins/osf.io,njantrania/osf.io,kch8qx/osf.io,njantrania/osf.io,zachjanicki/osf.io,felliott/osf.io,ZobairAlijan/osf.io,DanielSBrown/osf.io,adlius/osf.io,felliott/osf.io,rdhyee/osf.io,haoyuchen1992/osf.io,zamattiac/osf.io,crcresearch/osf.io,alexschiller/osf.io,doublebits/osf.io,baylee-d/osf.io,acshi/osf.io,emetsger... |
2bd14f768ce7d82f7ef84d1e67d61afda5044581 | st2common/st2common/constants/logging.py | st2common/st2common/constants/logging.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Use the correct base path. | Use the correct base path.
| Python | apache-2.0 | punalpatel/st2,lakshmi-kannan/st2,Plexxi/st2,jtopjian/st2,Plexxi/st2,grengojbo/st2,emedvedev/st2,punalpatel/st2,peak6/st2,dennybaa/st2,alfasin/st2,Plexxi/st2,Itxaka/st2,pinterb/st2,StackStorm/st2,nzlosh/st2,grengojbo/st2,nzlosh/st2,Itxaka/st2,pixelrebel/st2,Plexxi/st2,tonybaloney/st2,peak6/st2,StackStorm/st2,jtopjian/s... |
0a5e0935782bdd4c8669a39566d619aa4816ab60 | custom/aaa/utils.py | custom/aaa/utils.py | from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.apps.locations.models import LocationType, SQLLocation
def build_location_filters(location_id):
try:
location = SQLLocation.objects.get(location_id=location_id)
except SQLLocation.DoesNotExist:
return {... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.db import connections
from corehq.apps.locations.models import LocationType, SQLLocation
from custom.aaa.models import AggAwc, AggVillage, CcsRecord, Child, Woman
def build_location_filters(location_id):
try:
loca... | Create easy explanations for aggregation queries | Create easy explanations for aggregation queries
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
ec771b7186065443e282be84fbeda5897caba913 | buildbot_travis/steps/base.py | buildbot_travis/steps/base.py | from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step whic... | from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step whic... | Revert "Save .travis.yml into build properties" | Revert "Save .travis.yml into build properties"
The data is > 1024 so no dice.
This reverts commit 10960fd1465afb8de92e8fd35b1affca4f950e27.
| Python | unknown | tardyp/buildbot_travis,tardyp/buildbot_travis,isotoma/buildbot_travis,tardyp/buildbot_travis,buildbot/buildbot_travis,buildbot/buildbot_travis,buildbot/buildbot_travis,tardyp/buildbot_travis,isotoma/buildbot_travis |
4069a7017d0bbda2aa4d436741619304df3f654f | flaskiwsapp/snippets/customApi.py | flaskiwsapp/snippets/customApi.py | '''
Created on Sep 16, 2016
@author: rtorres
'''
from flask_restful import Api
from flask_jwt import JWTError
from flask import jsonify
import collections
class CustomApi(Api):
"""A simple class to keep the default Errors behaviour."""
def handle_error(self, e):
if isinstance(e, JWTError):
... | '''
Created on Sep 16, 2016
@author: rtorres
'''
from flask_restful import Api
from flask_jwt import JWTError
from flask import jsonify
import collections
from flask_api.status import HTTP_501_NOT_IMPLEMENTED
DUMMY_ERROR_CODE = '1000'
class CustomApi(Api):
"""A simple class to keep the default Errors behaviour.... | Customize handle error to JsonApi standard | Customize handle error to JsonApi standard | Python | mit | rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.