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 |
|---|---|---|---|---|---|---|---|---|---|
cb3312419f20b10d92cff4ec06606a2b7ee91950 | metaopt/__init__.py | metaopt/__init__.py | # -*- coding:utf-8 -*-
"""
Root package of MetaOpt.
"""
__author__ = 'Renke Grunwald, Bengt Lüers, Jendrik Poloczek'
__author_email__ = 'info@metaopt.org'
__license__ = '3-Clause BSD'
#__maintainer__ = "first last"
#__maintainer_email__ = "first.last@example.com"
__url__ = 'http://organic-es.tumblr.com/'
__version__ = ... | # -*- coding:utf-8 -*-
"""
Root package of MetaOpt.
"""
__author__ = 'Renke Grunwald, Bengt Lüers, Jendrik Poloczek, Justin Heinermann'
__author_email__ = 'info@metaopt.org'
__license__ = '3-Clause BSD'
# __maintainer__ = "first last"
# __maintainer_email__ = "first.last@example.com"
__url__ = 'http://organic-es.tumblr... | Add Justin to authors, fix comments | Add Justin to authors, fix comments
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt |
a09cf17583ca558d3e4c77a1682ed01c223f182d | ceph_deploy/util/arg_validators.py | ceph_deploy/util/arg_validators.py | import socket
import argparse
import re
class RegexMatch(object):
"""
Performs regular expression match on value.
If the regular expression pattern matches it will it will return an error
message that will work with argparse.
"""
def __init__(self, pattern, statement=None):
self.strin... | import socket
import argparse
import re
class RegexMatch(object):
"""
Performs regular expression match on value.
If the regular expression pattern matches it will it will return an error
message that will work with argparse.
"""
def __init__(self, pattern, statement=None):
self.strin... | Support hostname that resolve to IPv6-only address | Support hostname that resolve to IPv6-only address
The current hostname validation does not cope with IPv6-only hostnames. Use getaddrinfo instead of gethostbyname to fix this. getaddrinfo raises the same exceptions and should work like a drop-in-replacement in this scenario.
We should also address the IPv4-only ch... | Python | mit | rtulke/ceph-deploy,ceph/ceph-deploy,codenrhoden/ceph-deploy,imzhulei/ceph-deploy,codenrhoden/ceph-deploy,isyippee/ceph-deploy,alfredodeza/ceph-deploy,ktdreyer/ceph-deploy,branto1/ceph-deploy,SUSE/ceph-deploy,zhouyuan/ceph-deploy,Vicente-Cheng/ceph-deploy,trhoden/ceph-deploy,ceph/ceph-deploy,branto1/ceph-deploy,zhouyuan... |
c082edf34a51fd0e587a8fbc7bcf4cf18838462d | modules/libmagic.py | modules/libmagic.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
try:
import m... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
try:
import m... | Fix for python 2.6 support | Fix for python 2.6 support
| Python | mpl-2.0 | jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,mitre/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,mitre/multiscanner,awest1339/multiscanner |
d9cf7b736416f942a7bb9c164d99fdb3b4de1b08 | leapday/templatetags/leapday_extras.py | leapday/templatetags/leapday_extras.py | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which us... | '''
James D. Zoll
4/15/2013
Purpose: Defines template tags for the Leapday Recipedia application.
License: This is a public work.
'''
from django import template
register = template.Library()
@register.filter()
def good_css_name(value):
'''
Returns the lower-case hyphen-replaced display name,
which us... | Fix reordering due to removal of Other | Fix reordering due to removal of Other
| Python | mit | Zerack/zoll.me,Zerack/zoll.me |
bc50210afc3cfb43441fe431e34e04db612f87c7 | importkit/yaml/schema.py | importkit/yaml/schema.py | import subprocess
class YamlValidationError(Exception): pass
class Base(object):
schema_file = ''
@classmethod
def validate(cls, filename):
kwalify = subprocess.Popen(['kwalify', '-lf', cls.schema_file, filename],
stdout=subprocess.PIPE,
... | import subprocess
class YamlValidationError(Exception): pass
class Base(object):
schema_file = ''
@classmethod
def validate(cls, meta):
if 'marshalled' in meta and meta['marshalled']:
return
cls.validatefile(meta['filename'])
@classmethod
def validatefile(cls, filenam... | Implement YAML file compilation into 'bytecode' | import: Implement YAML file compilation into 'bytecode'
Store serialized Python structures resulted from loading YAML source in
the .ymlc files, a-la .pyc
| Python | mit | sprymix/importkit |
e0109cdb52f02f1e8963849adeb42311cef2aa6c | gratipay/renderers/jinja2_htmlescaped.py | gratipay/renderers/jinja2_htmlescaped.py | import aspen_jinja2_renderer as base
from markupsafe import escape as htmlescape
class HTMLRenderer(base.Renderer):
def render_content(self, context):
# Extend to inject an HTML-escaping function. Since autoescape is on,
# template authors shouldn't normally need to use this function, but
... | import aspen_jinja2_renderer as base
from markupsafe import escape as htmlescape
class HTMLRenderer(base.Renderer):
def render_content(self, context):
# Extend to inject an HTML-escaping function. Since autoescape is on,
# template authors shouldn't normally need to use this function, but
... | Make htmlescape function available in templates | Make htmlescape function available in templates
For when we explicitly call it.
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/g... |
1da4245cbc25a609b006254714ae273b6a6824e0 | retools/__init__.py | retools/__init__.py | #
| """retools
This module holds a default Redis instance, which can be
configured process-wide::
from retools import Connection
Connection.set_default(host='127.0.0.1', db=0, **kwargs)
"""
from redis import Redis
from retools.redconn import Connection
__all__ = ['Connection']
class Connection(objec... | Update global lock, default connection | Update global lock, default connection
| Python | mit | mozilla-services/retools,bbangert/retools,0x1997/retools |
0b89da2ea93051ffdd47498bc047cc07885c2957 | opps/boxes/models.py | opps/boxes/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
... | Add field channel on QuerySet boxes | Add field channel on QuerySet boxes
| Python | mit | YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps |
66604e749349e37eb1e59168d00f52ed7da23029 | dragonflow/db/neutron/models.py | dragonflow/db/neutron/models.py | # Copyright (c) 2015 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.apache.org/licenses/LICENSE-2.0
#
# Unless ... | # Copyright (c) 2015 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.apache.org/licenses/LICENSE-2.0
#
# Unless ... | Implement utc_timeout for PGSQL and MSSQL | Implement utc_timeout for PGSQL and MSSQL
UTC_TIMESTAMP is a MySQL specific function. Use SQLAlchemy to implement it
also in MSSQL and PGSQL.
Change-Id: If8673b543da2a89a2bad87daff2429cb09c735aa
Closes-Bug: #1700873
| Python | apache-2.0 | openstack/dragonflow,openstack/dragonflow,openstack/dragonflow |
d2971af14f57e925e1500da9ede42adb34d0dc62 | tastycrust/authentication.py | tastycrust/authentication.py | #!/usr/bin/env python
# -*- coding: utf-8
class AnonymousAuthentication(object):
anonymous_allowed_methods = ['GET']
def __init__(self, allowed=None):
if allowed is not None:
self.anonymous_allowed_methods = allowed
def is_authenticated(self, request, **kwargs):
allowed_metho... | #!/usr/bin/env python
# -*- coding: utf-8
class AnonymousAuthentication(object):
allowed_methods = ['GET']
def __init__(self, allowed=None):
if allowed is not None:
self.allowed_methods = allowed
def is_authenticated(self, request, **kwargs):
return (request.method in [s.uppe... | Change some naming in AnonymousAuthentication | Change some naming in AnonymousAuthentication
| Python | bsd-3-clause | uranusjr/django-tastypie-crust |
fa885b929f8323c88228dbc4d40ca286d49ee286 | test_project/blog/api.py | test_project/blog/api.py | from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api.EntryReso... | from tastypie.resources import ModelResource
from tastypie.api import Api
from tastypie import fields
from models import Entry, Comment, SmartTag
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
class CommentResource(ModelResource):
entry = fields.ForeignKey("blog.api... | Create corresponding SmartTag resource with explicitly defined 'resource_name' attribute that will be used for its TastyFactory key. | Create corresponding SmartTag resource with explicitly defined 'resource_name' attribute that will be used for its TastyFactory key.
| Python | bsd-3-clause | juanique/django-chocolate,juanique/django-chocolate,juanique/django-chocolate |
185dcb9db26bd3dc5f76faebb4d56c7abb87f87f | test/parseJaguar.py | test/parseJaguar.py | import os
from cclib.parser import Jaguar
os.chdir(os.path.join("..","data","Jaguar","basicJaguar"))
os.chdir("eg01")
for file in ["dvb_gopt.out"]:
t = Jaguar(file)
t.parse()
print t.moenergies[0,:]
print t.homos[0]
print t.moenergies[0,t.homos[0]]
| import os
from cclib.parser import Jaguar
os.chdir(os.path.join("..","data","Jaguar","basicJaguar"))
files = [ ["eg01","dvb_gopt.out"],
["eg02","dvb_sp.out"],
["eg03","dvb_ir.out"],
["eg06","dvb_un_sp.out"] ]
for f in files:
t = Jaguar(os.path.join(f[0],f[1]))
t.pars... | Test the parsing of all of the uploaded Jaguar files | Test the parsing of all of the uploaded Jaguar files
git-svn-id: d468cea6ffe92bc1eb1f3bde47ad7e70b065426a@75 5acbf244-8a03-4a8b-a19b-0d601add4d27
| Python | lgpl-2.1 | Clyde-fare/cclib_bak,Clyde-fare/cclib_bak |
bad670aebbdeeb029a40762aae80eec1100268a2 | data_log/management/commands/generate_report_fixture.py | data_log/management/commands/generate_report_fixture.py | from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data L... | from django.core.management.base import BaseCommand
from django.core import serializers
from data_log import models
import json
class Command(BaseCommand):
help = 'Create Data Log Report fixtures'
def handle(self, *args, **kwargs):
self.stdout.write(self.style.HTTP_INFO('Creating fixtures for Data L... | Fix data log fixture foreign keys | Fix data log fixture foreign keys
| Python | apache-2.0 | porksmash/swarfarm,porksmash/swarfarm,porksmash/swarfarm,porksmash/swarfarm |
6309031090a135856e6e2b3f8381202d6d17b72f | test_app/signals.py | test_app/signals.py | # # -*- coding: utf-8 -*-
import logging
from django.conf import settings
from django.dispatch import receiver
from trello_webhooks.signals import callback_received
from test_app.hipchat import send_to_hipchat
logger = logging.getLogger(__name__)
@receiver(callback_received, dispatch_uid="callback_received")
def ... | # # -*- coding: utf-8 -*-
import logging
from django.conf import settings
from django.dispatch import receiver
from trello_webhooks.signals import callback_received
from test_app.hipchat import send_to_hipchat
logger = logging.getLogger(__name__)
@receiver(callback_received, dispatch_uid="callback_received")
def ... | Send unknown events to HipChat in red | Send unknown events to HipChat in red
If an event comes in to the test_app and has no matching template,
then send it to HipChat in red, not yellow, making it easier to
manage.
| Python | mit | yunojuno/django-trello-webhooks,yunojuno/django-trello-webhooks |
40f140682a902957d5875c8afc88e16bc327367f | tests/test_cat2cohort.py | tests/test_cat2cohort.py | """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def test_api_url(self):
"""Test api_url."""
values = [
('fr', 'https:/... | """Unit tests for cat2cohort."""
import unittest
from wm_metrics.cat2cohort import api_url, _make_CSV_line, _userlist_to_CSV_cohort
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
def setUp(self):
"""Set up the tests."""
self.userlist = [('Toto', 'fr'), ('Titi',... | Move unit tests data in setUp | Move unit tests data in setUp
When unit testing the various methods of cat2cohort,
we need some example data (input and expected output).
It makes sense to share it among testing methods through
the setUp method mechanism.
| Python | mit | danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics |
b52f0e9fe2c9e41205a8d703985ac39ab3524a8a | tests/blueprints/test_entity.py | tests/blueprints/test_entity.py | from json import loads
from tests import AppTestCase, main
from tentd import db
from tentd.models.entity import Entity
class EntityBlueprintTest (AppTestCase):
def setUp (self):
super(EntityBlueprintTest, self).setUp()
self.user = Entity(name="testuser")
db.session.add(self.user)
db.session.commit()
def t... | from json import loads
from tests import AppTestCase, main
from tentd import db
from tentd.models.entity import Entity
class EntityBlueprintTest (AppTestCase):
def setUp (self):
super(EntityBlueprintTest, self).setUp()
self.name = 'testuser'
self.user = Entity(name=self.name)
db.session.add(self.user)
db.... | Test that the api 404's when a user does not exist | Test that the api 404's when a user does not exist
| Python | apache-2.0 | pytent/pytentd |
8b0dcf1bfda26ab9463d2c5a892b7ffd3fa015d9 | packs/github/actions/lib/formatters.py | packs/github/actions/lib/formatters.py | __all__ = [
'issue_to_dict'
]
def issue_to_dict(issue):
result = {}
if issue.closed_by:
closed_by = issue.closed_by.name
else:
closed_by = None
result['id'] = issue.id
result['repository'] = issue.repository.name
result['title'] = issue.title
result['body'] = issue.bo... | __all__ = [
'issue_to_dict',
'label_to_dict'
]
def issue_to_dict(issue):
result = {}
if issue.closed_by:
closed_by = issue.closed_by.name
else:
closed_by = None
result['id'] = issue.id
result['repository'] = issue.repository.name
result['title'] = issue.title
resu... | Make sure we flatten the labels attribute to a serializable simple type. | Make sure we flatten the labels attribute to a serializable simple type.
| Python | apache-2.0 | pearsontechnology/st2contrib,pidah/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,armab/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,psychopenguin/st2contrib,tonybaloney/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,psychopenguin/st2contrib,pidah/st2contrib,ar... |
2d841bd7dcd7a7b564d8749b7faa9c9634f0dc55 | tests/lib/yaml/exceptions.py | tests/lib/yaml/exceptions.py | class YAMLException(Exception):
"""Base for the exception hierarchy of this module
"""
| class YAMLException(Exception):
"""Base for the exception hierarchy of this module
"""
def __str__(self):
# Format a reason
if not self.args:
message = "unknown"
elif len(self.args) == 1:
message = self.args[0]
else:
try:
m... | Format Error message in the exception | Format Error message in the exception
| Python | mit | pradyunsg/zazo,pradyunsg/zazo |
2421212be1072db1428e7c832c0818a3928c1153 | tests/test_collection_crs.py | tests/test_collection_crs.py | import os
import re
import fiona
import fiona.crs
from .conftest import WGS84PATTERN
def test_collection_crs_wkt(path_coutwildrnp_shp):
with fiona.open(path_coutwildrnp_shp) as src:
assert re.match(WGS84PATTERN, src.crs_wkt)
def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp):
"""crs membe... | import os
import re
import fiona
import fiona.crs
from .conftest import WGS84PATTERN
def test_collection_crs_wkt(path_coutwildrnp_shp):
with fiona.open(path_coutwildrnp_shp) as src:
assert re.match(WGS84PATTERN, src.crs_wkt)
def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp):
"""crs memb... | Add test for collection creation with crs_wkt | Add test for collection creation with crs_wkt
| Python | bsd-3-clause | Toblerity/Fiona,Toblerity/Fiona,rbuffat/Fiona,rbuffat/Fiona |
86a8034101c27ffd9daf15b6cd884c6b511feecc | python/protein-translation/protein_translation.py | python/protein-translation/protein_translation.py | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... | # Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UA... | Fix mapping for codon keys for Tyrosine | Fix mapping for codon keys for Tyrosine
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism |
1fe53ccce2aa9227bcb2b8f8cdfa576924d81fbd | range_hits_board.py | range_hits_board.py | from convenience_hole import all_hands_in_range
from convenience import pr
from deuces.deuces import Card, Evaluator
e = Evaluator()
board = [Card.new('Qs'), Card.new('Jd'), Card.new('2c')]
range_list = ['AA', 'KK', 'QQ', 'AK', 'AKs']
## tricky ones highlighted:
## 1 2 3 4 5 6 7 8... | from convenience_hole import all_hands_in_range
from convenience import pr
from deuces.deuces import Card, Evaluator
e = Evaluator()
basic_keys = []
rc_counts = {}
for i in range(1,10):
s = e.class_to_string(i)
basic_keys.append(s)
rc_counts[s] = 0
## Two input vars:
board = [Card.new('Qs'), Card.new('Jd... | Change rc_counts to a dict instead of list. | Change rc_counts to a dict instead of list.
| Python | mit | zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments |
2778096c6683257d672760908f4c07b0e6a1cedc | setup.py | setup.py | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
... | import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
packages = []
package_dir = "dbbackup"
for dirpath, dirnames, filenames in os.walk(package_dir):
# ignore dirnames that start with '.'
for i, dirname in enumerate(dirnames):
... | Remove dropbox and boto as dependencies because they are optional and boto is not py3 compat | Remove dropbox and boto as dependencies because they are optional and boto is not py3 compat
| Python | bsd-3-clause | bahoo/django-dbbackup,bahoo/django-dbbackup |
bc8e548e51fddc251eb2e915883e3ee57bb9515b | zc_common/jwt_auth/utils.py | zc_common/jwt_auth/utils.py | import jwt
from rest_framework_jwt.settings import api_settings
def jwt_payload_handler(user):
# The handler from rest_framework_jwt removed user_id, so this is a fork
payload = {
'id': user.pk,
'roles': user.get_roles(),
}
return payload
def jwt_encode_handler(payload):
return ... | import jwt
from rest_framework_jwt.settings import api_settings
def jwt_payload_handler(user):
'''Constructs a payload for a user JWT. This is a slimmed down version of
https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11
:param User: an object with `pk` ... | Add docstrings to jwt handlers | Add docstrings to jwt handlers | Python | mit | ZeroCater/zc_common,ZeroCater/zc_common |
aeb6ce26bdde8697e7beb3d06391a04f500f574a | mara_db/__init__.py | mara_db/__init__.py | from mara_db import config, views, cli
MARA_CONFIG_MODULES = [config]
MARA_NAVIGATION_ENTRY_FNS = [views.navigation_entry]
MARA_ACL_RESOURCES = [views.acl_resource]
MARA_FLASK_BLUEPRINTS = [views.blueprint]
MARA_CLICK_COMMANDS = [cli.migrate]
| """Make the functionalities of this package auto-discoverable by mara-app"""
def MARA_CONFIG_MODULES():
from . import config
return [config]
def MARA_FLASK_BLUEPRINTS():
from . import views
return [views.blueprint]
def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
return []
def MARA_ACL_RESOURCES():... | Change MARA_XXX variables to functions to delay importing of imports (requires updating mara-app to 2.0.0) | Change MARA_XXX variables to functions to delay importing of imports (requires updating mara-app to 2.0.0)
| Python | mit | mara/mara-db,mara/mara-db |
19a7a44449b4e08253ca9379dd23db50f27d6488 | markdown_wrapper.py | markdown_wrapper.py | from __future__ import absolute_import
import sublime
import traceback
ST3 = int(sublime.version()) >= 3000
if ST3:
from markdown import Markdown, util
from markdown.extensions import Extension
import importlib
else:
from markdown import Markdown, util
from markdown.extensions import Extension
c... | from __future__ import absolute_import
import sublime
import traceback
from markdown import Markdown, util
from markdown.extensions import Extension
import importlib
class StMarkdown(Markdown):
def __init__(self, *args, **kwargs):
Markdown.__init__(self, *args, **kwargs)
self.Meta = {}
def r... | Remove some more ST2 specific code | Remove some more ST2 specific code
| Python | mit | revolunet/sublimetext-markdown-preview,revolunet/sublimetext-markdown-preview |
c1ed5befe3081f6812fc77fc694ea3e82d90f39c | telemetry/telemetry/core/backends/facebook_credentials_backend.py | telemetry/telemetry/core/backends/facebook_credentials_backend.py | # Copyright 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.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredential... | # Copyright 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.
from telemetry.core.backends import form_based_credentials_backend
class FacebookCredentialsBackend(
form_based_credentials_backend.FormBasedCredential... | Set facebook_crendentials_backend_2's url to https | [Telemetry] Set facebook_crendentials_backend_2's url to https
TBR=tonyg@chromium.org
BUG=428098
Review URL: https://codereview.chromium.org/688113003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#301945}
| Python | bsd-3-clause | benschmaus/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,catapult-project/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,sahi... |
8360bebbd4bf2b2e9d51c7aa16bdb9506a91883e | tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py | tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py | import unittest
import mock
from chainer import testing
from chainer.training import extensions
@testing.parameterize(
{'trigger': ('epoch', 2)},
{'trigger': ('iteration', 10)},
)
class TestSnapshotObject(unittest.TestCase):
def test_trigger(self):
target = mock.MagicMock()
snapshot_obj... | import unittest
import mock
from chainer import testing
from chainer.training import extensions
from chainer.training import trigger
@testing.parameterize(
{'trigger': ('epoch', 2)},
{'trigger': ('iteration', 10)},
{'trigger': trigger.IntervalTrigger(5, 'epoch')},
{'trigger': trigger.IntervalTrigger... | Add unit test to pass Trigger instance. | Add unit test to pass Trigger instance.
| Python | mit | okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,ktnyt/chainer,cupy/cupy,kiyukuta/chainer,rezoo/chainer,keisuke-umezawa/chainer,okuta/chainer,ktnyt/chainer,hvy/chainer,tkerola/chainer,niboshi/chainer,cupy/cupy,niboshi/chainer,jnishi/chainer,okuta/chainer,wkentaro/chainer,wkentaro/chainer,jnishi/chainer,cupy/cupy,cupy/... |
04939189efdc55164af8dc04223c7733664f091f | valohai_cli/cli_utils.py | valohai_cli/cli_utils.py | import click
def prompt_from_list(options, prompt, nonlist_validator=None):
for i, option in enumerate(options, 1):
click.echo('{number} {name} {description}'.format(
number=click.style('[%3d]' % i, fg='cyan'),
name=option['name'],
description=(
click.st... | import click
def prompt_from_list(options, prompt, nonlist_validator=None):
for i, option in enumerate(options, 1):
click.echo('{number} {name} {description}'.format(
number=click.style('[%3d]' % i, fg='cyan'),
name=option['name'],
description=(
click.st... | Fix `prompt_from_list` misbehaving with nonlist_validator | Fix `prompt_from_list` misbehaving with nonlist_validator
| Python | mit | valohai/valohai-cli |
ee2187a4cb52acbedf89c3381459b33297371f6e | core/api/views/endpoints.py | core/api/views/endpoints.py | from flask import Module, jsonify
from flask.views import MethodView
from core.api.decorators import jsonp
api = Module(
__name__,
url_prefix='/api'
)
def jsonify_status_code(*args, **kw):
response = jsonify(*args, **kw)
response.status_code = kw['code']
return response
@api.route('/')
def ind... | from flask import Module, jsonify, request
from flask.views import MethodView
from core.api.decorators import jsonp
api = Module(
__name__,
url_prefix='/api'
)
def jsonify_status_code(*args, **kw):
response = jsonify(*args, **kw)
response.status_code = kw['code']
return response
@api.route('/'... | Add new Flask MethodView called CreateUnikernel | Add new Flask MethodView called CreateUnikernel
| Python | apache-2.0 | adyasha/dune,onyb/dune,adyasha/dune,adyasha/dune |
21e91efbf9cb064f1fcd19ba7a77ba81a6c843f5 | isso/db/preferences.py | isso/db/preferences.py | # -*- encoding: utf-8 -*-
import os
import binascii
class Preferences:
defaults = [
("session-key", binascii.b2a_hex(os.urandom(24))),
]
def __init__(self, db):
self.db = db
self.db.execute([
'CREATE TABLE IF NOT EXISTS preferences (',
' key VARCHAR PR... | # -*- encoding: utf-8 -*-
import os
import binascii
class Preferences:
defaults = [
("session-key", binascii.b2a_hex(os.urandom(24)).decode('utf-8')),
]
def __init__(self, db):
self.db = db
self.db.execute([
'CREATE TABLE IF NOT EXISTS preferences (',
' ... | Save the session-key as a unicode string in the db | Save the session-key as a unicode string in the db
The session-key should be saved as a string, not a byte string.
| Python | mit | posativ/isso,xuhdev/isso,Mushiyo/isso,jelmer/isso,princesuke/isso,jiumx60rus/isso,janusnic/isso,janusnic/isso,Mushiyo/isso,Mushiyo/isso,posativ/isso,mathstuf/isso,janusnic/isso,jiumx60rus/isso,WQuanfeng/isso,jelmer/isso,princesuke/isso,jelmer/isso,Mushiyo/isso,WQuanfeng/isso,xuhdev/isso,mathstuf/isso,xuhdev/isso,prince... |
4d5af4869871b45839952dd9f881635bd07595c1 | parsers/RPOnline.py | parsers/RPOnline.py | from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '1\.\d*$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_... | from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '(?<!(vid|bid|iid))(-1\.\d*)$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntitie... | Exclude Videos article and non-scrapable info-galleries and picture-galleries via URL-pattern | Exclude Videos article and non-scrapable info-galleries and picture-galleries via URL-pattern
| Python | mit | catcosmo/newsdiffs,catcosmo/newsdiffs,catcosmo/newsdiffs |
014f7d9ef9a10264f78f42a63ffa03dd9cd4e122 | test/test_texture.py | test/test_texture.py | import unittest
import os
import pywavefront.texture
import pywavefront.visualization # power of two test
def prepend_dir(file):
return os.path.join(os.path.dirname(__file__), file)
class TestTexture(unittest.TestCase):
def testPathedImageName(self):
"""For Texture objects, the image name should ... | import unittest
import os
import pywavefront.texture
def prepend_dir(file):
return os.path.join(os.path.dirname(__file__), file)
class TestTexture(unittest.TestCase):
def testPathedImageName(self):
"""For Texture objects, the image name should be the last component of the path."""
my_textu... | Remove tests depending on pyglet entirely | Remove tests depending on pyglet entirely
| Python | bsd-3-clause | greenmoss/PyWavefront |
b8a54a3bef04b43356d2472c59929ad15a0b6d4b | semantics/common.py | semantics/common.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import numpy as np
def get_exponent(v):
if isinstance(v, np.float32):
mask, shift, offset = 0x7f800000, 23, 127
else:
raise NotImplementedError('The value v can only be of type np.float32')
return ((v.view('i') & mask) >> shift) - off... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import gmpy2
from gmpy2 import mpq, mpfr
def ulp(v):
return mpq(2) ** v.as_mantissa_exp()[1]
def round(mode):
def decorator(f):
def wrapped(v1, v2):
with gmpy2.local_context(round=mode):
return f(v1, v2)
retu... | Use gmpy2 instead of numpy | Use gmpy2 instead of numpy
| Python | mit | admk/soap |
84e41e39921b33fc9c84a99fe498587ca7ac30ae | settings_example.py | settings_example.py | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by su... | import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{... | Add CSV folder setting comment | Add CSV folder setting comment
| Python | mit | AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files |
c2a090772e8aaa3a1f2239c0ca7abc0cb8978c88 | Tools/compiler/compile.py | Tools/compiler/compile.py | import sys
import getopt
from compiler import compile, visitor
def main():
VERBOSE = 0
DISPLAY = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqd')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVisitor.VERBOSE + 1
if k == '-q... | import sys
import getopt
from compiler import compile, visitor
##import profile
def main():
VERBOSE = 0
DISPLAY = 0
CONTINUE = 0
opts, args = getopt.getopt(sys.argv[1:], 'vqdc')
for k, v in opts:
if k == '-v':
VERBOSE = 1
visitor.ASTVisitor.VERBOSE = visitor.ASTVis... | Add -c option to continue if one file has a SyntaxError | Add -c option to continue if one file has a SyntaxError
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
9a0fd1daf7d35ae1b29e3d1dbbc11272fcb13847 | app/start.py | app/start.py | from lxml import objectify, etree
import simplejson as json
from converter.nsl.nsl_converter import NslConverter
from converter.nsl.other.nsl_other_converter import NslOtherConverter
import sys
xml = open("SEnsl_ssi.xml")
xml_string = xml.read()
xml_obj = objectify.fromstring(xml_string)
nsl_other_xml_string = open(... | from lxml import objectify, etree
import simplejson as json
from converter.nsl.nsl_converter import NslConverter
from converter.nsl.other.nsl_other_converter import NslOtherConverter
import sys
xml = open("SEnsl_ssi.xml")
xml_string = xml.read()
xml_obj = objectify.fromstring(xml_string)
nsl_other_xml_string = open(... | Enable sort keys in json dumps to make sure json is stable | Enable sort keys in json dumps to make sure json is stable
| Python | bsd-2-clause | c0d3m0nkey/xml-to-json-converter |
e195ab1f4e83febf7b3b7dff7e1b63b578986167 | tests.py | tests.py | from unittest import TestCase
from markdown import Markdown
from mdx_attr_cols import AttrColTreeProcessor
class TestAttrColTreeProcessor(TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_proc... | from unittest import TestCase
import xmltodict
from markdown import Markdown
from markdown.util import etree
from mdx_attr_cols import AttrColTreeProcessor
class XmlTestCaseMixin(object):
def mk_doc(self, s):
return etree.fromstring(
"<div>" + s.strip() + "</div>")
def assertXmlEqual(s... | Check handling of simple rows. | Check handling of simple rows.
| Python | isc | CTPUG/mdx_attr_cols |
ab73b2132825e9415ff24306a9d89da10294d79e | icekit/utils/management/base.py | icekit/utils/management/base.py | import time
from django import db
from django.core.management.base import BaseCommand
from optparse import make_option
class CronBaseCommand(BaseCommand):
help = ('Long running process (indefinitely) that executes task on a '
'specified interval (default is 1 min). The intent for the '
'ma... | import logging
import time
from django import db
from django.core.management.base import BaseCommand
from optparse import make_option
logger = logging.getLogger(__name__)
class CronBaseCommand(BaseCommand):
help = ('Long running process (indefinitely) that executes task on a '
'specified interval (de... | Use `logging` instead of printing to stdout by default. | Use `logging` instead of printing to stdout by default.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit |
4625a1ed4115b85ce7d96a0d0ba486e589e9fe6c | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from optparse import OptionParser
from os.path import abspath, dirname
from django.test.simple import DjangoTestSuiteRunner
def runtests(*test_args, **kwargs):
parent = dirname(abspath(__file__))
sys.path.insert(0, parent)
test_runner = DjangoTestSuiteRunner(
verbo... | #!/usr/bin/env python
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.test.utils import get_runner
from django.conf import settings
import django
if django.VERSION >= (1, 7):
django.setup()
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunn... | Make test runner only run basis tests | Make test runner only run basis tests
and not dependecies tests
| Python | mit | frecar/django-basis |
1648cec8667611aa7fec4bff12f873f8e6294f82 | scripts/bodyconf.py | scripts/bodyconf.py | #!/usr/bin/python2
# -*- coding: utf-8 -*-
pixval = {
'hair': 10,
'head': 20,
'upper': 30,
'arms': 40,
'lower': 50,
'legs': 60,
'feet': 70
}
groups = [
[10, 20],
[30, 40],
[50, 60],
[70]
]
| #!/usr/bin/python2
# -*- coding: utf-8 -*-
pixval = {
'hair': 10,
'head': 20,
'upper': 30,
'arms': 40,
'lower': 50,
'legs': 60,
'feet': 70
}
groups = [
[10, 20],
[30, 40],
[50, 60],
[70],
[0,10,20,30,40,50,60,70]
]
| Add whole image as an input | Add whole image as an input
| Python | mit | Cysu/Person-Reid,Cysu/Person-Reid,Cysu/Person-Reid,Cysu/Person-Reid,Cysu/Person-Reid |
c87a71035782da3a9f9b26c9fb6a30ce42855913 | board.py | board.py | import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.boardMatrix = numpy.... | import numpy
"""
Board represents a four in a row game board.
Author: Isaac Arvestad
"""
class Board:
"""
Initializes the game with a certain number of rows
and columns.
"""
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.matrix = numpy.zeros... | Change from camelcase to underscores. | Change from camelcase to underscores.
| Python | mit | isaacarvestad/four-in-a-row |
dfaff0553379f5686efc5da722e2ffac455a2d9f | administrator/serializers.py | administrator/serializers.py | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | from categories.models import Category, Keyword, Subcategory
from rest_framework import serializers
class SubcategoryListSerializer(serializers.ModelSerializer):
class Meta:
model = Subcategory
fields = ('pk', 'name')
class CategorySerializer(serializers.ModelSerializer):
subcategories = Sub... | Add is_active to category serializer | Add is_active to category serializer
| Python | apache-2.0 | belatrix/BackendAllStars |
0c79d2fee14d5d2bff51ade9d643df22dde7f301 | polyaxon/polyaxon/config_settings/scheduler/__init__.py | polyaxon/polyaxon/config_settings/scheduler/__init__.py | from polyaxon.config_settings.k8s import *
from polyaxon.config_settings.dirs import *
from polyaxon.config_settings.spawner import *
from .apps import *
| from polyaxon.config_settings.k8s import *
from polyaxon.config_settings.dirs import *
from polyaxon.config_settings.spawner import *
from polyaxon.config_settings.registry import *
from .apps import *
| Add registry settings to scheduler | Add registry settings to scheduler
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
2d5152e72e1813ee7bf040f4033d369d60a44cc2 | pipeline/compute_rpp/compute_rpp.py | pipeline/compute_rpp/compute_rpp.py | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of ... | import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path... | Update the pipeline to take into account the outlier rejection method to compute the RPP | Update the pipeline to take into account the outlier rejection method to compute the RPP
| Python | mit | glemaitre/power-profile,glemaitre/power-profile,clemaitre58/power-profile,clemaitre58/power-profile |
76a32bf058583072100246c92970fdbda9a45106 | locations/pipelines.py | locations/pipelines.py | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import DropItem
from scrapy import signals
cl... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import DropItem
from scrapy import signals
cl... | Handle geojson feature without latlon | Handle geojson feature without latlon
| Python | mit | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places |
69b816868337683a7dd90f24711e03c5eb982416 | kitchen/lib/__init__.py | kitchen/lib/__init__.py | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = {}
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listd... | Use a sortable list instead of a dictionary of values for the return value | Use a sortable list instead of a dictionary of values for the return value
| Python | apache-2.0 | edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen |
286c8151c174f11df98d6cb421252c0d61337add | flake8_coding.py | flake8_coding.py | # -*- coding: utf-8 -*-
import re
__version__ = '0.1.0'
class CodingChecker(object):
name = 'flake8_coding'
version = __version__
def __init__(self, tree, filename):
self.filename = filename
@classmethod
def add_options(cls, parser):
parser.add_option(
'--accept-enc... | # -*- coding: utf-8 -*-
import re
__version__ = '0.1.0'
class CodingChecker(object):
name = 'flake8_coding'
version = __version__
def __init__(self, tree, filename):
self.filename = filename
@classmethod
def add_options(cls, parser):
parser.add_option(
'--accept-enc... | Update regexp to detect magic comment | Update regexp to detect magic comment
| Python | apache-2.0 | tk0miya/flake8-coding |
7cb5a225738bfc1236ef5836aad50e216a7e7355 | apps/blog/license_urls.py | apps/blog/license_urls.py | """
URLCONF for the blog app.
"""
from django.conf.urls import url
from . import views, feeds
# URL patterns configuration
urlpatterns = (
# License index page
url(r'^(?P<slug>[-a-zA-Z0-9_]+)/$', views.license_detail, name='license_detail'),
# Related articles feed
url(r'^(?P<slug>[-a-zA-Z0-9_]+)/... | """
URLCONF for the blog app (add-on urls for the license app).
"""
from django.conf.urls import url
from . import views, feeds
# URL patterns configuration
urlpatterns = (
# License index page
url(r'^(?P<slug>[-a-zA-Z0-9_]+)/articles/$', views.license_detail, name='license_articles_detail'),
# Relate... | Rework blog license add-on urls | Rework blog license add-on urls
| Python | agpl-3.0 | TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker |
5dfacded4f0dd8e7b5e7fe212fc6bfe017dcb2b5 | games.py | games.py | """
This module is for generating fake game data for use with the API.
An example of some game data::
{
"id": 1,
"logURL": "http://derp.nope/",
"winner": 0,
"updates": [
{
"status": "complete",
"time": "today"
}
],
... | """
This module is for generating fake game data for use with the API.
An example of some game data::
{
"id": 1,
"logURL": "http://derp.nope/",
"winner": 0,
"updates": [
{
"status": "complete",
"time": "today"
}
],
... | Use ISO formatted time stamps | Use ISO formatted time stamps
| Python | bsd-3-clause | siggame/ng-games,siggame/ng-games,siggame/ng-games |
e45d6439d3858e70fde8f1dad1d72d8c291e8979 | build-single-file-version.py | build-single-file-version.py | #! /usr/bin/env python
import os
import stat
import zipfile
import StringIO
package_dir = 'xyppy'
python_directive = '#!/usr/bin/env python'
packed = StringIO.StringIO()
packed_writer = zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED)
for fname in os.listdir(package_dir):
fpath = os.path.join(package_dir, fnam... | #! /usr/bin/env python
import os
import stat
import zipfile
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
package_dir = 'xyppy'
python_directive = '#!/usr/bin/env python'
packed = StringIO()
packed_writer = zipfile.ZipFile(packed, 'w', zipfile.ZIP_DEFLATED)
for fn... | Make the build script P2/3 compatible | Make the build script P2/3 compatible
| Python | mit | theinternetftw/xyppy |
38964f0f840a7b60f5ce65ca2857789d92b133b5 | django_base64field/tests.py | django_base64field/tests.py | from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(max_length=13)
class Continent(models.Model):
ek = Base64Field()
name = model... | from django.db import models
from django.test import TestCase
from django.utils.baseconv import base64
from django_base64field.fields import Base64Field
class Planet(models.Model):
ek = Base64Field()
name = models.CharField(
default='Fucker',
max_length=103
)
class Continent(models.Model)... | Make fields on model have defaults value | Make fields on model have defaults value
Like who cares for their default value
| Python | bsd-3-clause | Alir3z4/django-base64field |
ee5af231a4faff8dd3aab7d6ae6984f95bfe892c | search/transforms.py | search/transforms.py | class Transforms:
convert_rules = {
"committee": {
"id": "id",
"title": "name",
"description": ["info", "about"]
},
"committee-meeting": {
"id": "id",
"title": "title",
"description": ["content", 0, "summary"],
"fulltext": ["content", 0, "body"]
},
"member": {
"id": "id",
"title": ... | class Transforms:
convert_rules = {
"committee": {
"id": "id",
"title": "name",
"description": ["info", "about"]
},
"committee-meeting": {
"id": "id",
"title": "title",
"description": ["content", 0, "summary"],
"fulltext": ["content", 0, "body"]
},
"member": {
"id": "id",
"title": ... | Move allowed data types out of search and fix for bills | Move allowed data types out of search and fix for bills
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 |
abd3542113baf801d76c740a2435c69fcda86b42 | src/DecodeTest.py | src/DecodeTest.py | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
def test_decoder_... | import unittest
from Decode import Decoder
import Frames
class TestDecoder(unittest.TestCase):
"""
"""
def setUp(self):
self.decoder = Decoder()
def test_decoder_get_frame_class(self):
command = 'SEND'
self.assertEquals(self.decoder.get_frame_class(command), Frames.SEND)
d... | Send and Connect frame tests | Send and Connect frame tests
| Python | mit | phan91/STOMP_agilis |
3a2daedd8bb198f5ec3fd06a0061ae06e6fb139e | tests/test_arpreq.py | tests/test_arpreq.py | import sys
from socket import htonl, inet_ntoa
from struct import pack
import pytest
from arpreq import arpreq
def test_localhost():
assert arpreq('127.0.0.1') == '00:00:00:00:00:00'
def decode_address(value):
return inet_ntoa(pack(">I", htonl(int(value, base=16))))
def decode_flags(value):
return i... | import sys
from socket import htonl, inet_ntoa
from struct import pack
import pytest
from arpreq import arpreq
def test_localhost():
assert arpreq('127.0.0.1') == '00:00:00:00:00:00'
def decode_address(value):
return inet_ntoa(pack(">I", htonl(int(value, base=16))))
def decode_flags(value):
return i... | Add tests for ValueError and TypeError | Add tests for ValueError and TypeError
| Python | mit | sebschrader/python-arpreq,sebschrader/python-arpreq,sebschrader/python-arpreq,sebschrader/python-arpreq |
0fa33bb58d6b042e79c52a6f33454140a7150f64 | lithium/blog/views.py | lithium/blog/views.py | from lithium.blog.models import Post
def decorator(request, view, author=None, tag=None, *args, **kwargs):
"""
A view decotator to change the queryset depending on whether
a user may read private posts.
"""
if request.user.has_perm('blog.can_read_private'):
kwargs['queryset'] = Post.on... | from lithium.blog.models import Post
def decorator(request, view, author=None, tag=None, *args, **kwargs):
"""
A view decotator to change the queryset depending on whether
a user may read private posts.
"""
if request.user.has_perm('blog.can_read_private'):
kwargs['queryset'] = Post.on... | Allow users with the permission 'blog.can_read_private' to see posts from the future. | Allow users with the permission 'blog.can_read_private' to see posts from the future.
| Python | bsd-2-clause | kylef/lithium |
af88bfaece839d044ccb0781a15c8c538979051e | tests/test_object.py | tests/test_object.py | #!/usr/bin/env python
import unittest
import mlbgame
class TestObject(unittest.TestCase):
def test_object(self):
data = {
'string': 'string',
'int': '10',
'float': '10.1'
}
obj = mlbgame.object.Object(data)
self.assertIsInstance(obj.string... | #!/usr/bin/env python
import unittest
import mlbgame
class TestObject(unittest.TestCase):
def test_object(self):
data = {
'string': 'string',
'int': '10',
'float': '10.1',
'unicode': u'\xe7\x8c\xab'
}
obj = mlbgame.object.Object(data)
... | Add test for unicode characters | Add test for unicode characters
| Python | mit | panzarino/mlbgame,zachpanz88/mlbgame |
c14f9c661e485243660970d3a76014b8e6b7f1af | src-python/setup.py | src-python/setup.py | from distutils.core import setup
import py2exe
setup(console=['process.py'])
| from distutils.core import setup
import py2exe, sys
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
console = [{'script': "process.py"}],
zipfile = None,
)
| Add options to generate single executable file | Add options to generate single executable file | Python | mit | yaa110/Adobe-Air-Registry-Modifier |
df8ae0415f9bf10c04472fb3009e91d7c3d7e24f | teuthology/sentry.py | teuthology/sentry.py | from raven import Client
client = None
def get_client(ctx):
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
| from raven import Client
client = None
def get_client(ctx):
global client
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
| Make client a global variable | Make client a global variable
| Python | mit | robbat2/teuthology,ceph/teuthology,tchaikov/teuthology,zhouyuan/teuthology,dmick/teuthology,michaelsevilla/teuthology,dreamhost/teuthology,SUSE/teuthology,t-miyamae/teuthology,caibo2014/teuthology,yghannam/teuthology,SUSE/teuthology,SUSE/teuthology,tchaikov/teuthology,michaelsevilla/teuthology,dmick/teuthology,ktdreyer... |
2e3b38d102c7e15ed121651c1eac26acd9c7f399 | grapdashboard.py | grapdashboard.py | from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard
class UQAMDashboard(Dashboard):
def __init__(self, **kwargs):
Dashboard.__init__(self, **kwargs)
self.children.append(modules.AppList(
title=_('Catalogue'),
column=1,... | from django.utils.translation import ugettext_lazy as _
from grappelli.dashboard import modules, Dashboard
class UQAMDashboard(Dashboard):
def __init__(self, **kwargs):
Dashboard.__init__(self, **kwargs)
self.children.append(modules.AppList(
title=_('Catalogue'),
column=1,... | Add links to admin dashboard | Add links to admin dashboard
| Python | bsd-3-clause | uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam,uq-eresearch/uqam |
bd68b6e44ec65ba8f1f0afeea3a1dce08f579690 | src/bots/chuck.py | src/bots/chuck.py | import re
import requests
import logging
from base import BaseBot
logger = logging.getLogger(__name__)
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/random' % CHUCK_API_URL.rstrip('/')).json()
return fact['... | import re
import requests
import logging
from base import BaseBot
from HTMLParser import HTMLParser
logger = logging.getLogger(__name__)
html_parser = HTMLParser()
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/rand... | Fix for html escaped characters | Fix for html escaped characters
| Python | mit | orangeblock/slack-bot |
532d9ea686793ebef8b6412a038ab58b54ca0ca6 | lib/disco/schemes/scheme_discodb.py | lib/disco/schemes/scheme_discodb.py | import __builtin__
from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DAT... | from disco import util
from discodb import DiscoDB, Q
def open(url, task=None):
if task:
disco_data = task.disco_data
ddfs_data = task.ddfs_data
else:
from disco.settings import DiscoSettings
settings = DiscoSettings()
disco_data = settings['DISCO_DATA']
ddfs_dat... | Use __builtins__ directly instead of import __builtin__. | Use __builtins__ directly instead of import __builtin__.
| Python | bsd-3-clause | simudream/disco,seabirdzh/disco,ErikDubbelboer/disco,simudream/disco,oldmantaiter/disco,ktkt2009/disco,beni55/disco,mwilliams3/disco,discoproject/disco,mozilla/disco,mwilliams3/disco,pooya/disco,pooya/disco,oldmantaiter/disco,discoproject/disco,pombredanne/disco,seabirdzh/disco,discoproject/disco,ErikDubbelboer/disco,o... |
cfdae6dcd3cc3f12e2c98fc3c6a51f146f185e98 | rollbar/contrib/starlette/middleware.py | rollbar/contrib/starlette/middleware.py | import sys
from starlette.requests import Request
from starlette.types import Receive, Scope, Send
import rollbar
from .requests import store_current_request
from rollbar.contrib.asgi import ReporterMiddleware as ASGIReporterMiddleware
from rollbar.lib._async import RollbarAsyncError, try_report
class ReporterMiddl... | import sys
from starlette.requests import Request
from starlette.types import Receive, Scope, Send
import rollbar
from .requests import store_current_request
from rollbar.contrib.asgi import ReporterMiddleware as ASGIReporterMiddleware
from rollbar.lib._async import RollbarAsyncError, try_report
class ReporterMiddl... | Update comment and optional instructions | Update comment and optional instructions
| Python | mit | rollbar/pyrollbar |
60e10d1e25a68f63a232b5c3fe1c23284baef63e | rnacentral/portal/utils/go_terms.py | rnacentral/portal/utils/go_terms.py | MAPPING = {
"RNase_MRP_RNA": None,
"RNase_P_RNA": None,
"SRP_RNA": None,
"Y_RNA": None,
"antisense_RNA": None,
"autocatalytically_spliced_intron": None,
"guide_RNA": None,
"hammerhead_ribozyme": None,
"lncRNA": None,
"miRNA": None,
"misc_RNA": None,
"ncRNA": None,
"ot... | MAPPING = {
"RNase_MRP_RNA": None,
"RNase_P_RNA": None,
"SRP_RNA": None,
"Y_RNA": None,
"antisense_RNA": None,
"autocatalytically_spliced_intron": None,
"guide_RNA": None,
"hammerhead_ribozyme": None,
"lncRNA": None,
"miRNA": None,
"misc_RNA": None,
"ncRNA": None,
"ot... | Add a guess about tRNA | Add a guess about tRNA
| Python | apache-2.0 | RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode |
10db23db0026c7e0987fb2481f1abebf5509b43c | tests/_test_selenium_marionette.py | tests/_test_selenium_marionette.py | import capybara
from capybara.tests.suite import DriverSuite
@capybara.register_driver("selenium_marionette")
def init_selenium_marionette_driver(app):
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.options import Options
from capybara.selen... | import capybara
from capybara.tests.suite import DriverSuite
@capybara.register_driver("selenium_marionette")
def init_selenium_marionette_driver(app):
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.firefox.options import Options
from capybara.selen... | Rename local Firefox options variable | Rename local Firefox options variable
| Python | mit | elliterate/capybara.py,elliterate/capybara.py,elliterate/capybara.py |
bf254d3f3cff2f3f3f9de1f8a904143813b01240 | passphrase/passphrase.py | passphrase/passphrase.py | #!/usr/bin/python
import argparse
from glob import glob
import random
import os.path
from contextlib import contextmanager
@contextmanager
def cd(path):
old_dir = os.getcwd()
os.chdir(path)
yield
os.chdir(old_dir)
_dir = os.path.dirname(os.path.abspath(__file__))
def available_languages():
with cd(_dir + "... | #!/usr/bin/python
import argparse
from glob import glob
import random
import os.path
from contextlib import contextmanager
@contextmanager
def cd(path):
old_dir = os.getcwd()
os.chdir(path)
yield
os.chdir(old_dir)
_dir = os.path.dirname(os.path.abspath(__file__))
def available_languages():
with cd(_dir + "... | Handle a missing dictionary exception | Handle a missing dictionary exception
| Python | bsd-3-clause | Version2beta/passphrase |
86377a2a0618957d9707441049cad24f0de684ca | scripts/round2_submit.py | scripts/round2_submit.py | #!/usr/bin/env python
import opensim as osim
from osim.redis.client import Client
from osim.env import *
import numpy as np
import argparse
import os
"""
Please ensure that `visualize=False`, else there might be unexpected errors in your submission
"""
env = RunEnv(visualize=False)
client = Client()
# Create enviro... | #!/usr/bin/env python
import opensim as osim
from osim.redis.client import Client
from osim.env import *
import numpy as np
import argparse
import os
"""
NOTE: For testing your submission scripts, you first need to ensure that redis-server is running in the background
and you can locally run the grading service by r... | Add a little bit more documentation for round2submission script | Add a little bit more documentation for round2submission script
| Python | mit | stanfordnmbl/osim-rl,vzhuang/osim-rl |
ceb5dfe96df6dc98d580b95296924f9c0ff50c5f | mrbelvedereci/trigger/models.py | mrbelvedereci/trigger/models.py | from __future__ import unicode_literals
from django.db import models
TRIGGER_TYPES = (
('manual', 'Manual'),
('commit', 'Commit'),
('tag', 'Tag'),
('pr', 'Pull Request'),
)
class Trigger(models.Model):
name = models.CharField(max_length=255)
repo = models.ForeignKey('github.Repository')
t... | from __future__ import unicode_literals
from django.db import models
TRIGGER_TYPES = (
('manual', 'Manual'),
('commit', 'Commit'),
('tag', 'Tag'),
('pr', 'Pull Request'),
)
class Trigger(models.Model):
name = models.CharField(max_length=255)
repo = models.ForeignKey('github.Repository', relat... | Add Repository.triggers backref to look up Triggers | Add Repository.triggers backref to look up Triggers
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci |
3c1747f52c7d0d150803ba938398e9fd3172efc0 | Orange/canvas/report/__init__.py | Orange/canvas/report/__init__.py | def plural(s, number):
return s.format(number=number, s="s" if number % 100 != 1 else "")
def plural_w(s, number, capitalize=False):
numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven",
"nine", "ten")
number_str = numbers[number] if number < len(numbers) else str(number... | import itertools
def plural(s, number):
return s.format(number=number, s="s" if number % 100 != 1 else "")
def plural_w(s, number, capitalize=False):
numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven",
"nine", "ten")
number_str = numbers[number] if number < len(numbe... | Add option to limit the number of lookups | report.clipped_list: Add option to limit the number of lookups
| Python | bsd-2-clause | cheral/orange3,marinkaz/orange3,qPCR4vir/orange3,kwikadi/orange3,marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,marinkaz/orange3,kwikadi/or... |
bf81f681bd15ccfd009a901a652f5fde6a885d9b | Orange/canvas/report/__init__.py | Orange/canvas/report/__init__.py | def plural(s, number):
return s.format(number=number, s="s" if number % 100 != 1 else "")
def plural_w(s, number, capitalize=False):
numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven",
"nine", "ten")
number_str = numbers[number] if number < len(numbers) else str(number... | import itertools
def plural(s, number):
return s.format(number=number, s="s" if number % 100 != 1 else "")
def plural_w(s, number, capitalize=False):
numbers = ("zero", "one", "two", "three", "four", "five", "six", "seven",
"nine", "ten")
number_str = numbers[number] if number < len(numbe... | Add option to limit the number of lookups | report.clipped_list: Add option to limit the number of lookups
| Python | bsd-2-clause | marinkaz/orange3,marinkaz/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,marinkaz/orange3,qPCR4vir/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,kwikadi/orange3,cheral/orange3,qPCR4vir/orange3,marinkaz/orange3,marinkaz/orange3,cheral/orange3,kwikadi/orange3,qPCR4vir/or... |
2288ff574db552dd5c078102f9bbed1b0c3b6490 | forms.py | forms.py | from flask.ext.wtf import Form, TextField, PasswordField, BooleanField, validators
from models import User
class LoginForm(Form):
username = TextField('username', [validators.Required()])
password = PasswordField('password', [validators.Required()])
remember = BooleanField('remember')
def __init__(se... | from flask.ext.wtf import Form
from wtforms.fields import TextField, PasswordField, BooleanField
from wtforms.validators import Required
from models import User
class LoginForm(Form):
username = TextField('username', [Required()])
password = PasswordField('password', [Required()])
remember = BooleanField(... | Update Flask-WTF imports to >0.9.0-style | Update Flask-WTF imports to >0.9.0-style
| Python | mit | mahrz/kernkrieg,mahrz/kernkrieg,mahrz/kernkrieg |
ef6bfe9a1ef25979a8e78a0c05012974c2d0d974 | 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, **kwargs2):
method = request.method
req_method = kwargs[method]
return req_method(request, **kwargs2)
return routed
def json_from_request(request):
"""
A... | 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... | Fix route function to support positional args | Fix route function to support positional args
| Python | agpl-3.0 | maurizi/otm-core,recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,maurizi/otm-core,maurizi/otm-core,recklessromeo/otm-core,maurizi/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,r... |
890647cc0cd952ed1a52bdd96f7e9dd8c28810c9 | socketlabs/socketlabs.py | socketlabs/socketlabs.py | import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username=None, password=None, serverid=None):
self._username = username
self._password = password
self._serverid = serverid
def failedMessages(sel... | import requests
from . constants import BASE_URL
from . exceptions import SocketLabsUnauthorized
class SocketLabs():
def __init__(self, username, password, serverid):
if username is None:
raise RuntimeError("username not defined")
if password is None:
raise RuntimeError(... | Add checks for username/password/serverid being defined | Add checks for username/password/serverid being defined
| Python | mit | MattHealy/socketlabs-python |
ea83b615ef6fcaf71eb5e5d656585056757ac64f | {{cookiecutter.app_name}}/views.py | {{cookiecutter.app_name}}/views.py | from django.core.urlresolvers import reverse_lazy
from vanilla import ListView, CreateView, DetailView, UpdateView, DeleteView
from .forms import {{ cookiecutter.model_name }}Form
from .models import {{ cookiecutter.model_name }}
class {{ cookiecutter.model_name }}CRUDView(object):
model = {{ cookiecutter.model_n... | from django.core.urlresolvers import reverse
from vanilla import ListView, CreateView, DetailView, UpdateView, DeleteView
from .forms import {{ cookiecutter.model_name }}Form
from .models import {{ cookiecutter.model_name }}
class {{ cookiecutter.model_name }}CRUDView(object):
model = {{ cookiecutter.model_name }... | Use get_success_url to work around reverse_lazy issue on Python3. | Use get_success_url to work around reverse_lazy issue on Python3.
| Python | bsd-3-clause | janusnic/cookiecutter-django-crud,wildfish/cookiecutter-django-crud,cericoda/cookiecutter-django-crud,janusnic/cookiecutter-django-crud,wildfish/cookiecutter-django-crud,cericoda/cookiecutter-django-crud |
216f0bb3680b86ac2dfc8c506b791db4e34eeee6 | nextactions/board.py | nextactions/board.py | from nextactions.list import List
class Board:
def __init__(self, trello, json):
self._trello = trello
self.id = json['id']
self.name = json['name']
self.nextActionList = []
def getLists(self):
json = self._trello.get(
'https://api.trello.com/1/boards/' + ... | from nextactions.list import List
class Board:
def __init__(self, trello, json):
self._trello = trello
self.id = json['id']
self.name = json['name']
self.nextActionList = []
def getLists(self):
json = self._trello.get(
'https://api.trello.com/1/boards/' + ... | Tidy matching lists by name | Tidy matching lists by name
| Python | mit | stevecshanks/trello-next-actions |
b7f153a383dad71f272d8ef211deeb1c1a149f51 | kerze.py | kerze.py | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
fillcolor(FARBE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESSE*30)
left(90)
forward... | from turtle import *
GROESSE = 0.5
FARBE = "red"
FAERBEN = True
SHAPE = "turtle"
fillcolor(FARBE)
shape(SHAPE)
def zeichneKerze(brennt):
pd()
begin_fill()
forward(GROESSE*100)
left(90)
forward(GROESSE*400)
left(90)
forward(GROESSE*100)
right(90)
forward(GROESSE*30)
back(GROESS... | Resolve NameError, add changeable turtle shape constant. | Resolve NameError, add changeable turtle shape constant.
| Python | mit | luforst/adventskranz |
99a41171c6030cfd88b66979d2f62bb18b51041a | sqlobject/tests/test_exceptions.py | sqlobject/tests/test_exceptions.py | from sqlobject import *
from sqlobject.dberrors import DuplicateEntryError
from sqlobject.tests.dbtest import *
########################################
## Table aliases and self-joins
########################################
class TestException(SQLObject):
name = StringCol(unique=True, length=100)
def test_exce... | from sqlobject import *
from sqlobject.dberrors import *
from sqlobject.tests.dbtest import *
########################################
## Table aliases and self-joins
########################################
class TestException(SQLObject):
name = StringCol(unique=True, length=100)
class TestExceptionWithNonexist... | Add a test for pgcode | Add a test for pgcode
git-svn-id: ace7fa9e7412674399eb986d17112e1377537c44@4665 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
| Python | lgpl-2.1 | sqlobject/sqlobject,drnlm/sqlobject,drnlm/sqlobject,sqlobject/sqlobject |
6a3fbb7280c1078b574736eae3c6a3e4e42d3f46 | seaborn/__init__.py | seaborn/__init__.py | # Capture the original matplotlib rcParams
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .timeseri... | # Capture the original matplotlib rcParams
import matplotlib as mpl
_orig_rc_params = mpl.rcParams.copy()
# Import seaborn objects
from .rcmod import *
from .utils import *
from .palettes import *
from .relational import *
from .regression import *
from .categorical import *
from .distributions import *
from .matrix i... | Remove top-level import of timeseries module | Remove top-level import of timeseries module
| Python | bsd-3-clause | arokem/seaborn,mwaskom/seaborn,mwaskom/seaborn,arokem/seaborn,anntzer/seaborn,anntzer/seaborn |
95f48c85aee59906fc498c8c44c34551fca32a43 | tests/blueprints/metrics/test_metrics.py | tests/blueprints/metrics/test_metrics.py | """
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
def test_metrics(make_admin_app):
client = _get_test_client(make_admin_app, True)
response = client.get('/metrics')
assert response.status_code == 200
assert response.content_type == 'text/plain; versi... | """
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import pytest
from ...conftest import database_recreated
# To be overridden by test parametrization
@pytest.fixture
def config_overrides():
return {}
@pytest.fixture
def client(config_overrides, make_admin_app,... | Adjust metrics test to set up/tear down database | Adjust metrics test to set up/tear down database
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps |
f7b48c9193511f693cc2ec17d46253077d06dcc3 | LR/lr/lib/__init__.py | LR/lr/lib/__init__.py | from model_parser import ModelParser, getFileString
__all__=['ModelParser', 'getFileString']
| # !/usr/bin/python
# Copyright 2011 Lockheed Martin
'''
Base couchdb threshold change handler class.
Created on August 18, 2011
@author: jpoyau
'''
from model_parser import ModelParser, getFileString
from couch_change_monitor import *
__all__=["ModelParser",
"getFileString",
"MonitorCh... | Add the new change feed module to __all__ | Add the new change feed module to __all__
| Python | apache-2.0 | jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,Learni... |
e6e3cd2b8e6ad64bce9fe6614c3d532fcbfa3359 | OpenSearchInNewTab.py | OpenSearchInNewTab.py | import sublime_plugin
class OpenSearchInNewTab(sublime_plugin.EventListener):
def on_deactivated(self, view):
if view.name() == 'Find Results':
# set a name with space
# so it won't be bothered
# during new search
view.set_name('Find Results ') | import sublime_plugin
default_name = 'Find Results'
alt_name = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
def on_deactivated(self, view):
if view.name() == 'Find Results':
# set a name with space
# so it won't be bothered
# during new search
view.set_name(alt_name)
# the... | Add text commands hook for other plugins | Add text commands hook for other plugins | Python | mit | everyonesdesign/OpenSearchInNewTab |
bf97326c668580eef49fc4323a249a1c3cd1b126 | src/formatter.py | src/formatter.py | from .command import Command
from .settings import Settings
class Formatter(object):
def __init__(self, name=None, source=None, binary=None):
self.__name = name
self.__source = 'source.' + (source if source else name.lower())
self.__binary = binary
self.__settings = Settings(name.l... | from .command import Command
from .settings import Settings
class Formatter(object):
def __init__(self, name=None, source=None, binary=None):
self.__name = name
self.__source = 'source.' + (source if source else name.lower())
self.__binary = binary
self.__settings = Settings(name.l... | Apply options defined in user settings to the formatting command | Apply options defined in user settings to the formatting command
| Python | mit | Rypac/sublime-format |
ee01e4574ec1a365e87c879a01216249f75c0da8 | src/commoner/registration/admin.py | src/commoner/registration/admin.py | from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
pass
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
| from django.contrib import admin
from commoner.registration.models import PartialRegistration
class PartialRegistrationAdmin(admin.ModelAdmin):
list_filter = ('complete',)
admin.site.register(PartialRegistration, PartialRegistrationAdmin)
| Allow filtering of registrations by complete status. | Allow filtering of registrations by complete status.
| Python | agpl-3.0 | cc-archive/commoner,cc-archive/commoner |
2cf7f70e352f8427cfb7d1dba309ee7d7e0ce5f4 | markitup/urls.py | markitup/urls.py | from __future__ import unicode_literals
from django.conf.urls import patterns, url
from markitup.views import apply_filter
urlpatterns = patterns(
'',
url(r'preview/$', apply_filter, name='markitup_preview')
)
| from __future__ import unicode_literals
from django.conf.urls import url
from markitup.views import apply_filter
urlpatterns = [
url(r'preview/$', apply_filter, name='markitup_preview'),
]
| Use plain Python list for urlpatterns. | Use plain Python list for urlpatterns.
| Python | bsd-3-clause | zsiciarz/django-markitup,zsiciarz/django-markitup,carljm/django-markitup,carljm/django-markitup,carljm/django-markitup,zsiciarz/django-markitup |
bdc0466c63347280fbd8bc8c30fb07f294200194 | client/third_party/idna/__init__.py | client/third_party/idna/__init__.py | # Emulate the bare minimum for idna for the Swarming bot.
# In practice, we do not need it, and it's very large.
def encode(host, uts46):
return unicode(host)
| # Emulate the bare minimum for idna for the Swarming bot.
# In practice, we do not need it, and it's very large.
# See https://pypi.org/project/idna/
from encodings import idna
def encode(host, uts46=False): # pylint: disable=unused-argument
# Used by urllib3
return idna.ToASCII(host)
def decode(host):
# Us... | Change idna stub to use python's default | [client] Change idna stub to use python's default
Fix a regression from 690b8ae29be2ca3b4782fa6ad0e7f2454443c38d which broke
select bots running inside docker.
The new stub is still simpler than https://pypi.org/project/idna/ and lighter
weight but much better than ignoring the "xn-" encoding as this was done
previou... | Python | apache-2.0 | luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py |
e64f1add0c36f33c15c93118b653de8752c576d5 | webserver/codemanagement/validators.py | webserver/codemanagement/validators.py | from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format
import re
sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+... | from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from dulwich.repo import check_ref_format
import re
sha1_validator = RegexValidator(regex="^[a-f0-9]{40}$",
message="Must be valid sha1 sum")
tag_regex = re.compile(r'^[\w\-\.]+$')
de... | Check submission names more leniently | Check submission names more leniently
Fixes #55
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver |
9e2eef4f246c446fbcf05ce29ae309b9a554d46b | app/views/schemas.py | app/views/schemas.py | from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class Meme... | from dataclasses import dataclass
from datetime import datetime
@dataclass
class AuthResponse:
email: str
image_access: bool
search_access: bool
created: datetime
modified: datetime
@dataclass
class FontResponse:
filename: str
id: str
alias: str
_self: str
@dataclass
class Meme... | Support layout on template endpoints | Support layout on template endpoints
| Python | mit | jacebrowning/memegen,jacebrowning/memegen |
8a8d36d1f39cf893328b008cb11ef8e4a3fe71b5 | txlege84/topics/management/commands/bootstraptopics.py | txlege84/topics/management/commands/bootstraptopics.py | from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics..... | from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics..... | Rename Criminal Justice to Law & Order, per Emily's request | Rename Criminal Justice to Law & Order, per Emily's request
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 |
14adf187c6b76c77259f140dad4fb1d502ec6779 | compass-api/G4SE/api/serializers.py | compass-api/G4SE/api/serializers.py | from .models import Record, HarvestedRecord, AllRecords
from django.contrib.auth.models import User
from rest_framework import serializers
import datetime
class AllRecordsSerializer(serializers.ModelSerializer):
class Meta:
model = AllRecords
class RecordSerializer(serializers.ModelSerializer):
cl... | from .models import Record, HarvestedRecord, AllRecords
from django.contrib.auth.models import User
from rest_framework import serializers
import datetime
class AllRecordsSerializer(serializers.ModelSerializer):
login_name = serializers.HiddenField(default=None)
class Meta:
model = AllRecords
class... | Exclude user name from api | Exclude user name from api
| Python | mit | geometalab/G4SE-Compass,geometalab/G4SE-Compass,geometalab/G4SE-Compass,geometalab/G4SE-Compass |
962b674053ecf52730315550675c29fa8ba8ec12 | openprovider/data/exception_map.py | openprovider/data/exception_map.py | # coding=utf-8
from openprovider.exceptions import *
MAPPING = {
307: BadRequest, # Invalid domain extension
501: BadRequest, # Domain name too short
}
def from_code(code):
"""
Return the specific exception class for the given code, or OpenproviderError
if no specific exception class is avai... | # coding=utf-8
from openprovider.exceptions import *
MAPPING = {
307: BadRequest, # Invalid domain extension
501: BadRequest, # Domain name too short
4005: ServiceUnavailable, # Temprorarily unavailable due to maintenance
}
def from_code(code):
"""
Return the specific except... | Add maintenance response to exception map | Add maintenance response to exception map
| Python | mit | AntagonistHQ/openprovider.py |
3cd25ea433518ec9b25a5e646e63413ebd0ffcd4 | parse.py | parse.py | import sys
indentation = 0
repl = [
('%', '_ARSCL', '['),
('$', '_ARSCR', ']'),
('#', '_EQOP', '='),
('<', '_PARL', '('),
('>', '_PARR', ')'),
]
sin = sys.argv[1]
for r in repl:
sin = sin.replace(r[0], r[1])
for r in repl:
sin = sin.replace(r[1], r[2])
sin = sin.replace('\\n', '\n')
fo... | import sys
import simplejson as json
indentation = 0
lang_def = None
with open('language.json') as lang_def_file:
lang_def = json.loads(lang_def_file.read())
if lang_def is None:
print("error reading json language definition")
exit(1)
repl = lang_def['rules']
sin = sys.argv[1]
for r in repl:
sin =... | Read json language rep and try to eval/exec stdin | Read json language rep and try to eval/exec stdin
| Python | unlicense | philipdexter/build-a-lang |
b39db786b73cc00676d35cd14b42c70d63b21ba3 | readthedocs/projects/templatetags/projects_tags.py | readthedocs/projects/templatetags/projects_tags.py | from django import template
register = template.Library()
@register.filter
def sort_version_aware(versions):
"""
Takes a list of versions objects and sort them caring about version schemes
"""
from distutils2.version import NormalizedVersion
from projects.utils import mkversion
fallback = Nor... | from django import template
from distutils2.version import NormalizedVersion
from projects.utils import mkversion
register = template.Library()
def make_version(version):
ver = mkversion(version)
if not ver:
if version.slug == 'latest':
return NormalizedVersion('99999.0', error_on_huge_m... | Fix version sorting to make latest and stable first. | Fix version sorting to make latest and stable first. | Python | mit | CedarLogic/readthedocs.org,GovReady/readthedocs.org,emawind84/readthedocs.org,attakei/readthedocs-oauth,sunnyzwh/readthedocs.org,rtfd/readthedocs.org,SteveViss/readthedocs.org,wanghaven/readthedocs.org,clarkperkins/readthedocs.org,asampat3090/readthedocs.org,wanghaven/readthedocs.org,fujita-shintaro/readthedocs.org,ats... |
a76fe727f9d6a7b95da2c3307ee7317a6426bd67 | simple_model/__init__.py | simple_model/__init__.py | from .builder import model_builder
from .models import DynamicModel, Model
__all__ = ('DynamicModel', 'Model', 'model_builder')
| from .builder import model_builder
from .models import Model
__all__ = ('Model', 'model_builder')
| Remove remaining links to DynamicModel | Remove remaining links to DynamicModel
| Python | mit | lamenezes/simple-model |
5bef5472b55b36c1c9174ef861e92f057249ca9a | zou/app/models/preview_file.py | zou/app/models/preview_file.py | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class PreviewFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is aimed at being reviewed. It is not a publication
neither a wo... | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class PreviewFile(db.Model, BaseMixin, SerializerMixin):
"""
Describes a file which is aimed at being reviewed. It is not a publication
neither a wo... | Add path field to preview file | Add path field to preview file
| Python | agpl-3.0 | cgwire/zou |
4e84dc31d52412a9d58d5f0c54f5514c0eac5137 | console.py | console.py | from dumpster import Dumpster
import os
i = input('\r>')
if i == 'list':
cwd = os.getcwd()
lcd = os.listdir()
dump = ''
for file in lcd:
if '.dmp' in file:
dump+= ' '+file
print(dump)
| from dumpster import Dumpster
import os
running = True
selected = ''
while running:
#cwd = os.getcwd()
i = input('\r%s>'%(selected))
if i == 'exit':
running = False
if i[0:6] == 'create':
name = i[7:]
Dumpster(name).write_to_dump()
if i == 'list':
if selected is... | Select and Create and List | Select and Create and List
| Python | apache-2.0 | SirGuyOfGibson/source-dump |
944746bd3e6b40b5ceb8ef974df6c26e550318cb | paradrop/tools/pdlog/pdlog/main.py | paradrop/tools/pdlog/pdlog/main.py | import sys
import argparse
import json
import urllib
import subprocess
LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log"
def parseLine(line):
try:
data = json.loads(line)
msg = urllib.unquote(data['message'])
print(msg)
except:
pass
def runTail(logFile):
cmd = ['tail... | import sys
import argparse
import json
import urllib
import subprocess
from time import sleep
LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log"
def parseLine(line):
try:
data = json.loads(line)
msg = urllib.unquote(data['message'])
print(msg)
except:
pass
def runTail(log... | Make sure the paradrop.pdlog retry when the log file does not exist | Make sure the paradrop.pdlog retry when the log file does not exist
| Python | apache-2.0 | ParadropLabs/Paradrop,ParadropLabs/Paradrop,ParadropLabs/Paradrop |
7db47e7b87305977d48be3f610004aed1626969a | setup.py | setup.py | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | #!/usr/bin/env python
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cr... | Change PyPI development status from pre-alpha to beta. | Change PyPI development status from pre-alpha to beta.
| Python | bsd-3-clause | msabramo/colorama,msabramo/colorama |
8307590d20f3a2bdb7efaa7679bfd37d83358475 | setup.py | setup.py | #!/usr/bin/python
import os
from distutils.core import setup
from evelink import __version__
__readme_path = os.path.join(os.path.dirname(__file__), "README.md")
__readme_contents = open(__readme_path).read()
setup(
name="EVELink",
version=__version__,
description="Python Bindings for the EVE Online API... | #!/usr/bin/python
import os
from distutils.core import setup
from evelink import __version__
__readme_path = os.path.join(os.path.dirname(__file__), "README.md")
__readme_contents = open(__readme_path).read()
setup(
name="EVELink",
version=__version__,
description="Python Bindings for the EVE Online API... | Include README.md and LICENSE in the package | Include README.md and LICENSE in the package
| Python | mit | bastianh/evelink,Morloth1274/EVE-Online-POCO-manager,FashtimeDotCom/evelink,ayust/evelink,zigdon/evelink |
87856b925d436df302eed4a65eac139ee394b427 | setup.py | setup.py | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... | #!/usr/bin/env python
"""
setup.py file for afnumpy
"""
from distutils.core import setup
from afnumpy import __version__
setup (name = 'afnumpy',
version = __version__,
author = "Filipe Maia",
author_email = "filipe.c.maia@gmail.com",
url = 'https://github.com/FilipeMaia/afnumpy',
... | Correct the pip download URL | Correct the pip download URL
| Python | bsd-2-clause | FilipeMaia/afnumpy,daurer/afnumpy |
4bcaff8e452973093a630d93086ea14636e97fc4 | tests/conftest.py | tests/conftest.py | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool... | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation
#
# Contributors:
# Brandon Myers bmyers@mozilla.com
de... | Remove unused config options in tests | Remove unused config options in tests
| Python | mpl-2.0 | ameihm0912/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,mozilla/MozDef,mpurzynski/MozDef,ameihm0912/MozDef,mozilla/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,gdestuynder/MozDef,jeffbryner... |
d7a347b0cee650d7b5cb6a0eca613da543e0e305 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from flask import Flask, jsonify
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')
@app.route('/ping')
def ping():
return j... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from textwrap import dedent
from flask import Flask, jsonify
pytest_plugins = 'pytester'
@pytest.fixture
def app():
app = Flask(__name__)
app.config['SECRET_KEY'] = '42'
@app.route('/')
def index():
return app.response_class('OK')... | Add `appdir` fixture to simplify testing | Add `appdir` fixture to simplify testing
| Python | mit | amateja/pytest-flask |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.