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 |
|---|---|---|---|---|---|---|---|---|---|
3de28fe8be76662654386f5b628eed87dca675db | abusehelper/bots/archivebot/tests/test_archivebot.py | abusehelper/bots/archivebot/tests/test_archivebot.py | import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name... | import unittest
import os
from tempfile import NamedTemporaryFile
from .. import archivebot
class TestRename(unittest.TestCase):
def test_valid_rename(self):
try:
tmp = NamedTemporaryFile()
new_tmp = archivebot._rename(tmp.name)
self.assertFalse(os.path.isfile(tmp.name... | Remove all temporary files from disk | Remove all temporary files from disk
| Python | mit | abusesa/abusehelper |
bb19c79ebc976bfa390f3c6ecc59ec6e0d03dd7e | speed_spider.py | speed_spider.py | #!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the deco... | #!/usr/bin/env python
# coding: utf-8
from grab.spider import Spider, Task
from grab.tools.logs import default_logging
import time
import logging
from random import randint
from grab.util.py3k_support import *
URL_28K = 'http://load.local/grab.html'
def timer(func):
"""
Display time taken to execute the deco... | Change code of speed test | Change code of speed test
| Python | mit | shaunstanislaus/grab,alihalabyah/grab,pombredanne/grab-1,alihalabyah/grab,lorien/grab,DDShadoww/grab,maurobaraldi/grab,maurobaraldi/grab,codevlabs/grab,istinspring/grab,DDShadoww/grab,codevlabs/grab,huiyi1990/grab,lorien/grab,kevinlondon/grab,giserh/grab,liorvh/grab,pombredanne/grab-1,shaunstanislaus/grab,raybuhr/grab,... |
7f1f001802ffdf4a53e17b120e65af3ef9d1d2da | openfisca_france/conf/cache_blacklist.py | openfisca_france/conf/cache_blacklist.py | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermadiate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logemen... | # When using openfisca for a large population, having too many variables in cache make openfisca performances drop.
# The following variables are intermediate results and do not need to be cached in those usecases.
cache_blacklist = set([
'aide_logement_loyer_retenu',
'aide_logement_charges',
'aide_logemen... | Add new variable to cache blacklist | Add new variable to cache blacklist
| Python | agpl-3.0 | sgmap/openfisca-france,antoinearnoud/openfisca-france,antoinearnoud/openfisca-france,sgmap/openfisca-france |
6e12974b1099044dff95fb632307cd6c5500c411 | corehq/apps/builds/utils.py | corehq/apps/builds/utils.py | import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions=None):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
versions = versions or []
db = CommCareBuild.get_db()
results = db.view('builds/al... | import re
from .models import CommCareBuild, CommCareBuildConfig
def get_all_versions(versions):
"""
Returns a list of all versions found in the database,
plus those in the optional list parameter.
"""
db = CommCareBuild.get_db()
results = db.view('builds/all', group_level=1).all()
versio... | Remove optional arg that's now always used | Remove optional arg that's now always used
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
ce1395db9340ee694ef7a7c35d7d185e4319cf4e | plugins/spotify.py | plugins/spotify.py | from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
t... | from plugins.util import command, get_url
import json
import re
SPOTIFY_URI_REGEX = r"(?<=spotify:)(?:track|album|artist):[a-zA-Z0-9]{22}"
ENDPOINT = "https://api.spotify.com/v1/{0}s/{1}"
@command()
def spotify(m):
spotify_uris = re.findall(SPOTIFY_URI_REGEX, m.body)
for spotify_uri in spotify_uris:
t... | Change formatting of response, add URL | Change formatting of response, add URL
| Python | mit | quanticle/GorillaBot,quanticle/GorillaBot,molly/GorillaBot,molly/GorillaBot |
8052577164ba144263c7f45e4c823ba396f19d65 | badgekit_webhooks/views.py | badgekit_webhooks/views.py | from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
def badge_issued_hook(request):
try:
data = json.loads(request.body)
except ValueError:
... | from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import json
def hello(request):
return HttpResponse("Hello, world. Badges!!!")
@require_POST
@csrf_exempt
def badge_issued_hook(request):
try... | Make webhook exempt from CSRF protection | Make webhook exempt from CSRF protection
Soon, we will add JWT verification, to replace it.
| Python | mit | tgs/django-badgekit-webhooks |
ea026eeeaae0ee30a5f3a4cb9f8cc2a9d1c37e6c | jackrabbit/utils.py | jackrabbit/utils.py | import collections
def is_callable(o):
return isinstance(o, collections.Callable)
| import collections
import sys
if sys.platform == 'win32':
from time import clock as time
else:
from time import time
def is_callable(o):
return isinstance(o, collections.Callable)
| Add platform dependent time import for best resolution. | Add platform dependent time import for best resolution.
| Python | mit | cbigler/jackrabbit |
a24bf76cd3d50b1370e5e63077e1f4ae1023b086 | lib/euehelpers.py | lib/euehelpers.py | """
helpers functions for various aspect of eue-ng project
"""
def check_mail(self, email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
return False
else:
return True
| #!/usr/bin/python
# -*- coding: utf-8 -*-
import re
"""
helpers functions for various aspect of eue-ng project
"""
def check_mail(email):
"""
Verify that the provided email is valid
"""
regex = r"^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z-]+.)+[A-Za-z]{2,4}$"
if not re.match(regex, email):
... | Fix check_mail helpers extracted from a class | Fix check_mail helpers extracted from a class
| Python | agpl-3.0 | david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng,david-guenault/eue-ng |
ddf3e604cee09d82ea8741d2ed08f600ba2f70c0 | scaffolder/commands/list.py | scaffolder/commands/list.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
def __init__(self, name, help='', aliases=(), stdout=None, stderr=... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.commands import BaseCommand
from scaffolder.core.template import TemplateManager
class ListCommand(BaseCommand):
help = 'Template command help entry'
def run(self, *args, **o... | Remove __init__ method, not needed. | ListCommand: Remove __init__ method, not needed.
| Python | mit | goliatone/minions |
2d31f6b842f26b5c33d2650f0f7672ba09230bfd | ratechecker/migrations/0002_remove_fee_loader.py | ratechecker/migrations/0002_remove_fee_loader.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations, OperationalError, ProgrammingError
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.22 on 2019-10-31 16:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ratechecker', '0001_initial'),
]
operations = [
migrations.AlterUniqueTogether(
... | Remove OperationalError and ProgrammingError imports | Remove OperationalError and ProgrammingError imports
| Python | cc0-1.0 | cfpb/owning-a-home-api |
ffc0b75d33264baea876898092bbd65247f564e6 | generate_input.py | generate_input.py | import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <n>')
sys.exit()
n = int(sys.argv[1])
f.write(str(n)+'\n')
for x in range(0, n):
for y in range(0, n):
if (y != 0):
f.write(' ' + str(randint(0, 20) - 10))
e... | import sys
from random import randint
f = open('input', 'w')
if (len(sys.argv) < 2):
print('python3 generate_input.py <nlines> <ncolums>')
sys.exit()
nl = int(sys.argv[1])
nc = int(sys.argv[2])
f.write(str(nl)+'\n')
f.write(str(nc)+'\n')
for x in range(0, nl):
for y in range(0, nc):
if (y != 0)... | Add variable lines and columns | Add variable lines and columns
| Python | mit | alepmaros/cuda_matrix_multiplication,alepmaros/cuda_matrix_multiplication,alepmaros/cuda_matrix_multiplication |
d020aeccc44d6de29724750355c341375739a6a9 | project_template/dataset_score_lookup.py | project_template/dataset_score_lookup.py | import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
d... | import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_looku... | Update score lookup to not load dataset file | Update score lookup to not load dataset file | Python | mit | warrencrowell/cs4300sp2016-TweetBeat,warrencrowell/cs4300sp2016-TweetBeat |
49721933b824e321db9e848c85647bb3d05a2388 | lib/feeds/errors.py | lib/feeds/errors.py | # Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | Remove import logging. This file is now identical to the branch point. | Remove import logging. This file is now identical to the branch point.
| Python | apache-2.0 | Princessgladys/googleresourcefinder,Princessgladys/googleresourcefinder,Princessgladys/googleresourcefinder |
6a1846c91a5829d0b41ca3f81f797e9f4aa26d6e | misura/canon/plugin/__init__.py | misura/canon/plugin/__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb a... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Plugin utilities"""
from domains import NavigatorDomain, navigator_domains, node, nodes
from dataimport import Converter, create_tree, create_dataset, search_registry, get_converter, convert_file, data_importers
# List of functions which will be executed to update confdb a... | Remove obsolete load_rules definition, FLTD-196 | Remove obsolete load_rules definition, FLTD-196
| Python | mit | tainstr/misura.canon,tainstr/misura.canon |
2c6bda335b48ca290070a629c5582b19751c524a | salt/modules/ftp.py | salt/modules/ftp.py | '''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.it... | '''
Minion side functions for salt-ftp
'''
import os
def recv(files, dest):
'''
Used with salt-ftp, pass the files dict, and the destination
'''
if not os.path.isdir(dest) or not os.path.isdir(os.path.dirname(dest)):
return 'Destination not available'
ret = {}
for path, data in files.it... | Make naming the destination file work | Make naming the destination file work
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
33154ad8decc2848ce30444ec51615397a4d8d37 | src/clusto/test/testbase.py | src/clusto/test/testbase.py | import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by s... | import sys
import os
sys.path.insert(0, os.curdir)
import unittest
import clusto
import ConfigParser
DB='sqlite:///:memory:'
ECHO=False
class ClustoTestResult(unittest.TestResult):
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by s... | Enable versioning during unit tests | Enable versioning during unit tests
| Python | bsd-3-clause | clusto/clusto,thekad/clusto,sloppyfocus/clusto,sloppyfocus/clusto,motivator/clusto,JTCunning/clusto,motivator/clusto,clusto/clusto,thekad/clusto,JTCunning/clusto |
c08e6a22e589880d97b92048cfaec994c41a23d4 | pylama/lint/pylama_pydocstyle.py | pylama/lint/pylama_pydocstyle.py | """pydocstyle support."""
from pydocstyle import PEP257Checker
from pylama.lint import Linter as Abstract
class Linter(Abstract):
"""Check pydocstyle errors."""
@staticmethod
def run(path, code=None, **meta):
"""pydocstyle code checking.
:return list: List of errors.
"""
... | """pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from ... | Update for pydocstyle 2.0.0 compatibility | Update for pydocstyle 2.0.0 compatibility
Fix klen/pylama#96
Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!
| Python | mit | klen/pylama |
95807cb007c9ea51a3594adca33b7fab809afc3e | tests/zeus/api/test_authentication.py | tests/zeus/api/test_authentication.py | import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
w... | import pytest
from zeus import factories
from zeus.auth import AuthenticationFailed
from zeus.api.authentication import ApiTokenAuthentication
def test_no_header(app):
with app.test_request_context('/'):
assert not ApiTokenAuthentication().authenticate()
def test_invalid_authentication_type(app):
w... | Fix tests for new header | test(auth): Fix tests for new header
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
79d2a78c0043aea7232933735654169ac05a70c3 | ofxclient/util.py | ofxclient/util.py | from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(... | from ofxclient.client import Client
from StringIO import StringIO
def combined_download(accounts, days=60):
"""Download OFX files and combine them into one
It expects an 'accounts' list of ofxclient.Account objects
as well as an optional 'days' specifier which defaults to 60
"""
client = Client(... | Fix bug with document merger | Fix bug with document merger
| Python | mit | captin411/ofxclient,jbms/ofxclient |
bc5fa08e84cd11349dc44c3065b7b5380d60ebd9 | raven/contrib/django/handlers.py | raven/contrib/django/handlers.py | """
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
cl... | """
raven.contrib.django.handlers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
from raven.handlers.logging import SentryHandler as BaseSentryHandler
cl... | Allow level param in Django SentryHandler.__init__ | Allow level param in Django SentryHandler.__init__
For consistency with superclass and with logging.Handler
| Python | bsd-3-clause | arthurlogilab/raven-python,inspirehep/raven-python,ewdurbin/raven-python,jbarbuto/raven-python,getsentry/raven-python,dbravender/raven-python,jbarbuto/raven-python,Photonomie/raven-python,percipient/raven-python,akheron/raven-python,icereval/raven-python,nikolas/raven-python,akalipetis/raven-python,someonehan/raven-pyt... |
486633791bea00c6a846b88124860efbc7532433 | fancypages/assets/fields.py | fancypages/assets/fields.py | from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(ob... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, ... | Fix south introspection rule for custom AssetField | Fix south introspection rule for custom AssetField
| Python | bsd-3-clause | tangentlabs/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages |
5c858e20eca77a2175178deacdbbc8005232879a | fireplace/cards/gvg/mage.py | fireplace/cards/gvg/mage.py | from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
in_hand... | from ..utils import *
##
# Minions
# Snowchugger
class GVG_002:
events = Damage().on(
lambda self, target, amount, source: source is self and Freeze(target)
)
# Goblin Blastmage
class GVG_004:
play = Find(FRIENDLY_MINIONS + MECH) & Hit(RANDOM_ENEMY_CHARACTER, 1) * 4
# Flame Leviathan
class GVG_007:
draw = ... | Update Flame Leviathan to use draw script | Update Flame Leviathan to use draw script
| Python | agpl-3.0 | smallnamespace/fireplace,oftc-ftw/fireplace,amw2104/fireplace,Ragowit/fireplace,smallnamespace/fireplace,liujimj/fireplace,NightKev/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,Meerkov/fireplace,Ragowit/fireplace,amw2104/fireplace,liujimj/fireplace,jleclanche/fireplace,beheh/fireplace |
2814d7b8060d1f468bb6fb34d1460cdad1811031 | tools/android/emulator/reporting.py | tools/android/emulator/reporting.py | """An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
... | """An interface to report the status of emulator launches."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import logging
import os
import uuid
class NoOpReporter(object):
"""Captures all device and failure data and throws it away."""
... | Update the reporter interface to even track the total runtime | Update the reporter interface to even track the total runtime
PiperOrigin-RevId: 160982468
| Python | apache-2.0 | android/android-test,android/android-test,android/android-test,android/android-test,android/android-test |
16ed5ff024a8ee04809cf9192727e1e7adcf565d | frigg/builds/serializers.py | frigg/builds/serializers.py | from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'priv... | from rest_framework import serializers
from frigg.projects.models import Project
from .models import Build, BuildResult
class ProjectInlineSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = (
'id',
'owner',
'name',
'priv... | Add more data to the api | Add more data to the api
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq |
8ed7fff1b7ec0d069e9a4545785bf99768afe761 | flask_jsonapiview/fields.py | flask_jsonapiview/fields.py | from marshmallow import fields, ValidationError
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_schema(self, field_name, schema):
supe... | from marshmallow import fields, ValidationError
from marshmallow.compat import basestring
from .exceptions import IncorrectTypeError
__all__ = ('StubObject',)
# -----------------------------------------------------------------------------
class Type(fields.Field):
_CHECK_ATTRIBUTE = False
def _add_to_sche... | Use compat basestring for id validation | Use compat basestring for id validation
| Python | mit | taion/flask-jsonapiview,4Catalyzer/flask-resty,4Catalyzer/flask-jsonapiview |
555536b93609ab3b1c29475d51408aaf7eda4675 | cray_test.py | cray_test.py | # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.append(testpage.get_test_suites())... | # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest
from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager
if __name__ == '__main__':
all_test_suites = []
all_test_suites.append(testpost.get_test_suites())
all_test_suites.ap... | Add new added test cases to travis. | Add new added test cases to travis.
| Python | mit | boluny/cray,boluny/cray |
e56e85b56fe68112c40f4d76ce103d5c10d6dea7 | kyokai/asphalt.py | kyokai/asphalt.py | """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger =... | """
Asphalt framework mixin for Kyokai.
"""
import logging
import asyncio
from functools import partial
from typing import Union
from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types
from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
logger =... | Fix server not being created properly. | Fix server not being created properly.
| Python | mit | SunDwarf/Kyoukai |
52bca1129cfe21669b5f7faf2e99e148a559bd32 | src/utils/build_dependencies.py | src/utils/build_dependencies.py | #!/usr/bin/env python
import glob
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
d = set()
for line in open(src, 'r'):
words = line.split()
if words and words[0].lower() == 'use':
name = words[1].strip(',')
if name in ['mpi','hdf5','h5... | #!/usr/bin/env python
import glob
import re
dependencies = {}
for src in glob.iglob('*.F90'):
module = src.strip('.F90')
deps = set()
d = re.findall(r'\n\s*use\s+(\w+)',
open(src,'r').read())
for name in d:
if name in ['mpi','hdf5','h5lt']:
continue
if n... | Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work. | Fix potential bug in build dependencies script. If you gave it ' use module,only: ...' before it would not work.
| Python | mit | mjlong/openmc,wbinventor/openmc,kellyrowland/openmc,lilulu/openmc,liangjg/openmc,mit-crpg/openmc,johnnyliu27/openmc,smharper/openmc,keadyk/openmc_mg_prepush,smharper/openmc,paulromano/openmc,johnnyliu27/openmc,smharper/openmc,liangjg/openmc,mit-crpg/openmc,smharper/openmc,walshjon/openmc,lilulu/openmc,sxds/opemmc,paulr... |
2084ac35a66067046db98e6b6d76d589952f1953 | chipy8.py | chipy8.py |
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address... |
class Memory(object):
def __init__(self):
self._stream = [0x00] * 4096
def __len__(self):
return len(self._stream)
def read_byte(self, address):
return self._stream[address]
def write_byte(self, address, data):
self._stream[address] = data
def load(self, address... | Refactor Chip8 to use a Memory instance. | Refactor Chip8 to use a Memory instance. | Python | bsd-3-clause | gutomaia/chipy8 |
e6b24f6e8bfca6f8e22bd63c893a228cc2a694f1 | starter_project/normalize_breton_test.py | starter_project/normalize_breton_test.py | import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
| import unittest
import normalize_breton_lib
class TestStringMethods(unittest.TestCase):
def test_normalize_breton(self):
'Test the output of NormalizeBreton.'
test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))]
for test in test_cases:
for test_case, expec... | Add basic test for example Pynini FST. | Add basic test for example Pynini FST.
| Python | apache-2.0 | googleinterns/text-norm-for-low-resource-languages,googleinterns/text-norm-for-low-resource-languages |
da3995150d6eacf7695c4606e83c24c82a17546d | autogenerate_config_docs/hooks.py | autogenerate_config_docs/hooks.py | #
# A collection of shared functions for managing help flag mapping files.
#
# 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 requi... | #
# A collection of shared functions for managing help flag mapping files.
#
# 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 requi... | Add a hook for nova.cmd.spicehtml5proxy | Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595
| Python | apache-2.0 | openstack/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,openstack/openstack-doc-tools |
09468a6411a5c0816ecb2f79037b0a79b3ceb9c5 | lib/carbon/hashing.py | lib/carbon/hashing.py | import hashlib
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(self, key):
big_hash = hashlib.md5( str(key) ).hexdiges... | try:
from hashlib import md5
except ImportError:
from md5 import md5
import bisect
serverRing = None
class ConsistentHashRing:
def __init__(self, nodes, replica_count=100):
self.ring = []
self.replica_count = replica_count
for node in nodes:
self.add_node(node)
def compute_ring_position(s... | Make compatible with python 2.4 hashlib was added in python 2.5, but just using the md5() method so fall back to md5.md5() if we can't import hashlib | Make compatible with python 2.4
hashlib was added in python 2.5, but just using the md5() method so fall back
to md5.md5() if we can't import hashlib
| Python | apache-2.0 | kharandziuk/carbon,criteo-forks/carbon,krux/carbon,graphite-project/carbon,pratX/carbon,johnseekins/carbon,graphite-server/carbon,JeanFred/carbon,mleinart/carbon,benburry/carbon,graphite-server/carbon,iain-buclaw-sociomantic/carbon,obfuscurity/carbon,xadjmerripen/carbon,cbowman0/carbon,deniszh/carbon,obfuscurity/carbon... |
81a35c396834667ba322456bac5abebe748e04f9 | tests/test_django_prometheus.py | tests/test_django_prometheus.py | #!/usr/bin/env python
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
| #!/usr/bin/env python
import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
... | Add a test for PowersOf. | Add a test for PowersOf.
| Python | apache-2.0 | obytes/django-prometheus,wangwanzhong/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus,DingaGa/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus |
f701ee5a8c1ee707fedcb9e20c86161f537b9013 | thinc/neural/_classes/resnet.py | thinc/neural/_classes/resnet.py | from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def be... | from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinsta... | Make residual connections work for list-valued inputs | Make residual connections work for list-valued inputs
| Python | mit | spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc |
5ab5d583aa056fb15b3b375768665aea8e9ab4be | pyhomer/__init__.py | pyhomer/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair | # -*- coding: utf-8 -*-
__author__ = 'Olga Botvinnik'
__email__ = 'olga.botvinnik@gmail.com'
__version__ = '0.1.0'
from .pyhomer import ForegroundBackgroundPair, construct_homer_command | Add constructing homer command to module level functions | Add constructing homer command to module level functions
| Python | bsd-3-clause | olgabot/pyhomer |
e08c2b053ab99de5a77b49b43524f5fab816b19e | fluent_blogs/templatetags/fluent_blogs_comments_tags.py | fluent_blogs/templatetags/fluent_blogs_comments_tags.py | """
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from dj... | """
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
import ... | Add render_comment_list / render_comment_form stub tags for Django | Add render_comment_list / render_comment_form stub tags for Django
| Python | apache-2.0 | edoburu/django-fluent-blogs,edoburu/django-fluent-blogs |
bc70937c953bae8d25478a71652a57c27f0940f2 | blanc_basic_events/events/listeners.py | blanc_basic_events/events/listeners.py | from django.db.models.signals import post_save, post_delete
from .models import RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
instance.event.save()
post_save.connect(update_event, sender=RecurringEvent)
post_save.connect(update_event, sender... | from django.db.models.signals import post_save, post_delete
from .models import Event, RecurringEvent, RecurringEventExclusion
def update_event(sender, instance, raw=False, **kwargs):
if not raw:
try:
instance.event.save()
except Event.DoesNotExist:
pass
post_save.connect... | Fix for when the event gets deleted before the recurring event or recurring event exclusion | Fix for when the event gets deleted before the recurring event or recurring event exclusion
| Python | bsd-3-clause | blancltd/blanc-basic-events |
147d545b7118d7d8974cfe2ee95648d62fc0d1e9 | microcms/admin.py | microcms/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from microcms.conf import settings
from microcms.models import Meta
class MetaAdmin(... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin as StockFlatPageAdmin
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from microcms.conf import set... | Insert automatically flatpage default site | Insert automatically flatpage default site
| Python | bsd-3-clause | eriol/django-microcms,eriol/django-microcms |
60de17292159deb590de6e5c9c2a45f1b95b0094 | girder/app/app/__init__.py | girder/app/app/__init__.py | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator... | from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import Girde... | Put the endpoint at /launch_taskflow/launch | Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
| Python | bsd-3-clause | OpenChemistry/mongochemserver |
61d20995b7bc291796299055751099204180bf28 | UM/Operations/AddSceneNodeOperation.py | UM/Operations/AddSceneNodeOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__()
self._node = node
self... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import Operation
from UM.Scene.Selection import Selection
from UM.Scene.SceneNode import SceneNode
class AddSceneNodeOperation(Operation.Operation):
def __init__(self, node, parent):
super().__init__... | Undo & redo of add SceneNode now correctly set the previous selection state. | Undo & redo of add SceneNode now correctly set the previous selection state.
CURA-640
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
59789bae7df5de6d7568a1b372b95a891fd5c3a2 | confluent_server/confluent/userutil.py | confluent_server/confluent/userutil.py | from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmall... | from ctypes import *
from ctypes.util import find_library
import grp
import pwd
import os
libc = cdll.LoadLibrary(find_library('libc'))
_getgrouplist = libc.getgrouplist
_getgrouplist.restype = c_int32
class TooSmallException(Exception):
def __init__(self, count):
self.count = count
super(TooSmall... | Fix python3 ctypes str usage | Fix python3 ctypes str usage
In python3, the string is likely to be unicode and incompatible
with the libc function. If it isn't bytes, force it to be bytes.
| Python | apache-2.0 | xcat2/confluent,xcat2/confluent,jjohnson42/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,xcat2/confluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent |
d12be22b5427a1433dd2ff7b1d2f97951d2b9c0f | pycon/migrations/0002_remove_old_google_openid_auths.py | pycon/migrations/0002_remove_old_google_openid_auths.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Google OpenID auth has been turned off, so any associations that
users had to their Google accounts via Google OpenID are now useless.
Just remove them.
"""
from django.db import migrations
def no_op(apps, schema_editor):
pass
def remove_old_... | Undo premature fix for dependency | Undo premature fix for dependency
| Python | bsd-3-clause | Diwahars/pycon,PyCon/pycon,njl/pycon,njl/pycon,njl/pycon,PyCon/pycon,Diwahars/pycon,Diwahars/pycon,PyCon/pycon,PyCon/pycon,Diwahars/pycon,njl/pycon |
7a5d5f8c495870222955dbf24f9680903f9e90b4 | recommends/management/commands/recommends_precompute.py | recommends/management/commands/recommends_precompute.py | from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
from optparse import make_option
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
... | from django.core.management.base import BaseCommand
from recommends.tasks import recommends_precompute
from datetime import datetime
import dateutil.relativedelta
import warnings
class Command(BaseCommand):
help = 'Calculate recommendations and similarities based on ratings'
def add_arguments(self, parser)... | Change deprecated options_list to add_arguments | Change deprecated options_list to add_arguments
| Python | mit | fcurella/django-recommends,fcurella/django-recommends |
d426351e86ab52f0c77f9a2b97d5bcdb35ee719f | tests/dojo_test.py | tests/dojo_test.py | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("Blue", "office")
self.assertTru... | import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTru... | Add test for creation of multiple rooms | Add test for creation of multiple rooms
| Python | mit | EdwinKato/Space-Allocator,EdwinKato/Space-Allocator |
a4d538d84fdfd8e20b58ada8a4435ed48ed64ab8 | spreadflow_delta/test/matchers.py | spreadflow_delta/test/matchers.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': mat... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from testtools import matchers
from spreadflow_core.test.matchers import MatchesInvocation
class MatchesDeltaItem(matchers.MatchesDict):
def __init__(self, item):
spec = {
'data': mat... | Use equal matcher for remaining keys | Use equal matcher for remaining keys
| Python | mit | znerol/spreadflow-delta |
22e1bc81b7aa456c8211f3fc83c1fd4fc69f514b | web_scraper/core/prettifiers.py | web_scraper/core/prettifiers.py | import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def simple_prettifier(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_ta... | import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import re
def remove_html_tags(scraped_data):
"""Return more presentable data (in a list) provided by scrape_target_elements()
:param bs4.element.ResultSet scraped_data: all of the data scraped by scrape_tar... | Change function name to be more accurate | Change function name to be more accurate
| Python | mit | Samuel-L/cli-ws,Samuel-L/cli-ws |
a268f6c74806d5996d469dd84ab365b0cf830f96 | OpenSSL/_util.py | OpenSSL/_util.py | from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
return native(ffi.string(charp))
errors = []
while True:
err... | from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
ffi = binding.ffi
lib = binding.lib
def exception_from_error_queue(exceptionType):
def text(charp):
if not charp:
return ""
return native(ffi.string(charp))
... | Handle when an OpenSSL error doesn't contain a reason | Handle when an OpenSSL error doesn't contain a reason
(Or any other field)
You can reproduce the error by running:
```
treq.get('https://nile.ghdonline.org')
```
from within a twisted program (and doing the approrpiate deferred stuff).
I'm unsure how to craft a unit test for this
| Python | apache-2.0 | mschmo/pyopenssl,daodaoliang/pyopenssl,mhils/pyopenssl,mhils/pyopenssl,pyca/pyopenssl,sorenh/pyopenssl,adamwolf/pyopenssl,reaperhulk/pyopenssl,aalba6675/pyopenssl,mitghi/pyopenssl,samv/pyopenssl,elitest/pyopenssl,r0ro/pyopenssl,r0ro/pyopenssl,reaperhulk/pyopenssl,kjav/pyopenssl,mitghi/pyopenssl,aalba6675/pyopenssl,hyne... |
9f7b105b0ff84123df72cf3d14577eb82e15f699 | community_mailbot/scripts/discourse_categories.py | community_mailbot/scripts/discourse_categories.py | # encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from urllib.parse import urljoin
import requests
def main():
args = parse_args()
params = {}
if args.key is not None:
params['api_key'] = args.key
if args.user is not N... | # encoding: utf-8
"""
List categories and their IDs in a Discourse forum.
"""
import os
from argparse import ArgumentParser
from community_mailbot.discourse import SiteFeed
def main():
args = parse_args()
site_feed = SiteFeed(args.url, user=args.user, key=args.key)
for c_id, name in site_feed.category_n... | Use SiteFeed to get a category listing | Use SiteFeed to get a category listing
| Python | mit | lsst-sqre/community_mailbot |
0668b59d8ec73e80976928706f96922605fe4f67 | tsserver/models.py | tsserver/models.py | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = d... | from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure... | Remove integer ID in Telemetry model | Remove integer ID in Telemetry model
| Python | mit | m4tx/techswarm-server |
ea180a007c1a5bfaeb56e6b223610876b0619e63 | webmaster_verification/views.py | webmaster_verification/views.py | import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for t... | import logging
logger = logging.getLogger(__name__)
from django.http import Http404
from django.views.generic import TemplateView
import settings
class VerificationView(TemplateView):
"""
This simply adds the verification key to the view context and makes sure
we return a 404 if the key wasn't set for t... | Use proper content-type for all files | Use proper content-type for all files
| Python | bsd-3-clause | nkuttler/django-webmaster-verification,nkuttler/django-webmaster-verification |
d84e8b60b0c619feaf529d4ab1eb53ef9e21aae5 | lingcod/bookmarks/forms.py | lingcod/bookmarks/forms.py | from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput(... | from lingcod.features.forms import FeatureForm
from lingcod.bookmarks.models import Bookmark
from django import forms
class BookmarkForm(FeatureForm):
name = forms.CharField(label='Bookmark Name')
latitude = forms.FloatField(widget=forms.HiddenInput())
longitude = forms.FloatField(widget=forms.HiddenInput(... | Allow IP to be blank in form | Allow IP to be blank in form
| Python | bsd-3-clause | Ecotrust/madrona_addons,Ecotrust/madrona_addons |
97f81ddfdd78d062e5019793101926fb52b0db38 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
| import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
| Set new file to read-only | Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum |
c36718dfb0ec25427a5c5c1c42945da1b757924d | topaz/modules/ffi/function.py | topaz/modules/ffi/function.py | from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('a... | from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('a... | Put the type unwrapping into a separat method | Put the type unwrapping into a separat method
| Python | bsd-3-clause | babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz |
d01a13f498e01efe613bace4c140d6901752475b | multilingual_model/admin.py | multilingual_model/admin.py | from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self.exclude = ('l... | from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self... | Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline. | Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
| Python | agpl-3.0 | dokterbob/django-multilingual-model |
1aa98285f1d51e36f9091542dd0323168a443a28 | wiblog/formatting.py | wiblog/formatting.py | from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.DocParser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary... | from django.utils.safestring import mark_safe
import CommonMark
# Convert a markdown string into HTML5, and prevent Django from escaping it
def mdToHTML(value):
parser = CommonMark.Parser()
renderer = CommonMark.HTMLRenderer()
ast = parser.parse(value)
return mark_safe(renderer.render(ast))
# Get a summary of... | Fix changed CommonMark syntax (?) | Fix changed CommonMark syntax (?)
| Python | agpl-3.0 | lo-windigo/fragdev,lo-windigo/fragdev |
5e50f8127a48a08d66bdc9d8aec28064b33ad864 | game.py | game.py | import datetime
import map_loader
class Game(object):
def __init__(self, name=name, players=players, map=None):
""" Initialize a new game. """
self.name = name,
self.players = players, # List of player usernames
self.status = 'Waiting',
self.raw_state = self.generate_cle... | import datetime
import json
import map_loader
class GAME_STATUS(object):
""" Game status constants. """
lobby = 'waiting for players'
waiting = 'waiting for moves'
playing = 'playing'
cancelled = 'cancelled'
complete = 'complete'
class Game(object):
def __init__(self, name=name, players... | Add some state related methods to Game | Add some state related methods to Game
| Python | mit | supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai |
067036e927fde0a97708162323ba13d4a239bb5b | grammpy/exceptions/NotNonterminalException.py | grammpy/exceptions/NotNonterminalException.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
pass
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from typing import Any
from .GrammpyException import GrammpyException
class NotNonterminalException(GrammpyException):
def __init__(self, parameter, *args: Any) -> None:
super().... | Implement NotNonterminalEception __init__ method and pass object | Implement NotNonterminalEception __init__ method and pass object
| Python | mit | PatrikValkovic/grammpy |
3f51ab2ada60e78c9821cef557cb06194a24226a | tests/optvis/test_integration.py | tests/optvis/test_integration.py | from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
model = InceptionV1()
model.load_graphdef()
@pytest.mark.parametrize("decorrelate", [True, False... | from __future__ import absolute_import, division, print_function
import pytest
import tensorflow as tf
from lucid.modelzoo.vision_models import InceptionV1
from lucid.optvis import objectives, param, render, transform
@pytest.fixture
def inceptionv1():
model = InceptionV1()
model.load_graphdef()
return model
... | Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module | Move model init into pytest fixture to avoid loading model and downloading graph just by importing the test module
| Python | apache-2.0 | tensorflow/lucid,tensorflow/lucid,tensorflow/lucid,tensorflow/lucid |
b14ec035f6a4890ce85504f449402aec857227fe | cla_backend/apps/status/tests/smoketests.py | cla_backend/apps/status/tests/smoketests.py | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | Configure Celery correctly in smoketest | Configure Celery correctly in smoketest
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
4158e2b5d2d7524f4d8e66b9ee021c1f63e11b25 | blanc_basic_events/events/templatetags/events_tags.py | blanc_basic_events/events/templatetags/events_tags.py | from django import template
from blanc_basic_events.events.models import Event
register = template.Library()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_set', 'recurringeventexclusion_set')
| from django import template
from blanc_basic_events.events.models import Category, Event
register = template.Library()
@register.assignment_tag
def get_events_categories():
return Category.objects.all()
@register.assignment_tag
def get_events():
return Event.objects.all().prefetch_related('recurringevent_s... | Tag to get all categories | Tag to get all categories
| Python | bsd-3-clause | blancltd/blanc-basic-events |
1344b1e521afd83494f99930260c00f679e883d1 | cms/djangoapps/contentstore/views/session_kv_store.py | cms/djangoapps/contentstore/views/session_kv_store.py | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, model_data):
self._model_data = model_data
self._session = request.session
def get(self, key):
try:
return self._model_data[key.field_name]
... | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return se... | Make SessionKeyValueStore variable names clearer | Make SessionKeyValueStore variable names clearer
| Python | agpl-3.0 | TsinghuaX/edx-platform,cognitiveclass/edx-platform,shashank971/edx-platform,J861449197/edx-platform,kursitet/edx-platform,LearnEra/LearnEraPlaftform,chauhanhardik/populo_2,philanthropy-u/edx-platform,analyseuc3m/ANALYSE-v1,amir-qayyum-khan/edx-platform,10clouds/edx-platform,abdoosh00/edraak,Semi-global/edx-platform,sam... |
03bca9051114a936b584632a72242ca023cbde3e | openslides/utils/csv_ext.py | openslides/utils/csv_ext.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, reg... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
openslides.utils.csv_ext
~~~~~~~~~~~~~~~~~~~~~~~~
Additional dialect definitions for pythons CSV module.
:copyright: 2011 by the OpenSlides team, see AUTHORS.
:license: GNU GPL, see LICENSE for more details.
"""
from csv import Dialect, excel, reg... | Extend patchup for builtin excel dialect | Extend patchup for builtin excel dialect
| Python | mit | ostcar/OpenSlides,normanjaeckel/OpenSlides,tsiegleauq/OpenSlides,jwinzer/OpenSlides,normanjaeckel/OpenSlides,OpenSlides/OpenSlides,emanuelschuetze/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides,rolandgeider/OpenSlides,emanuelschuetze/OpenSlides,OpenSlides/OpenSlides,jwinzer/OpenSlides,ostcar/OpenSlides,FinnStutzenstei... |
921ec4fce301dd98fc18d81fc7c78347486ea4f0 | counterpartylib/test/config_context_test.py | counterpartylib/test/config_context_test.py | #! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
... | #! /usr/bin/python3
import pprint
import tempfile
from counterpartylib.test import conftest # this is require near the top to do setup of the test suite
from counterpartylib.test.fixtures.params import DEFAULT_PARAMS as DP
from counterpartylib.test import util_test
from counterpartylib.test.util_test import CURR_DIR
... | Fix test failures comparing with "Bitcoin". | Fix test failures comparing with "Bitcoin".
| Python | mit | monaparty/counterparty-lib,monaparty/counterparty-lib |
8d0c87b21b17f0567dc4ce642437860cdf35bc6b | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syn... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2015-2017 The SublimeLinter Community
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):... | Update for luacheck >= 0.11.0 | Update for luacheck >= 0.11.0
* Remove 'channel' from default ignore list.
* Remove SublimeLinter inline options, use luacheck inline options.
* Use `--ranges` to highlight tokens correctly.
* Use `--codes` to distinguish warnings from errors.
* Use `--filename` to apply per-path config overrides correctly.
* Add vers... | Python | mit | SublimeLinter/SublimeLinter-luacheck |
41aa2c20a564c87fac1fd02d3bf40db84b02d49d | testing/test_run.py | testing/test_run.py | from regr_test import run
from subprocess import check_output
import os
def test_source():
script = 'test_env.sh'
var_name, var_value = 'TESTVAR', 'This is a test'
with open(script, 'w') as f:
f.write('export %s="%s"' % (var_name, var_value))
env = run.source(script)
cmd = ['/bin/bash', ... | from regr_test import run
import os
from subprocess import check_output
from tempfile import NamedTemporaryFile
def test_source():
var_name, var_value = 'TESTVAR', 'This is a test'
with NamedTemporaryFile('w', delete=False) as f:
f.write('export %s="%s"' % (var_name, var_value))
script_name =... | Make a test more secure | Make a test more secure
Choose a random filename to avoid overwriting a file.
| Python | mit | davidchall/nrtest |
85ff425513c27191309c49bd78b2b94c59603349 | examples/monitor.py | examples/monitor.py | #! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.... | #! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path... | Create a view and start it | Create a view and start it
| Python | lgpl-2.1 | lcp/mojito,lcp/libsocialweb,GNOME/libsocialweb,GNOME/libsocialweb,lcp/mojito,ThomasBollmeier/libsocialweb-flickr-oauth,ThomasBollmeier/libsocialweb-flickr-oauth,lcp/libsocialweb,GNOME/libsocialweb,lcp/mojito,ThomasBollmeier/libsocialweb-flickr-oauth,lcp/libsocialweb |
cc3a0f230c2f64fd2e4d974c536e9d2e99d89992 | tilezilla/errors.py | tilezilla/errors.py | """ Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
| """ Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
| Add exception for empty db search return | Add exception for empty db search return
| Python | bsd-3-clause | ceholden/tilezilla,ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tile,ceholden/landsat_tiles |
1592aa20fb41fed607ac48fd6ac1038f4bb6c665 | pylib/cqlshlib/__init__.py | pylib/cqlshlib/__init__.py | # Licensed to the Apache Software Foundation (ASF) 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 u... | # Licensed to the Apache Software Foundation (ASF) 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 u... | Add extension handler for "scylla_encryption_options" | cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info a... | Python | apache-2.0 | scylladb/scylla-tools-java,scylladb/scylla-tools-java,scylladb/scylla-tools-java,scylladb/scylla-tools-java |
79404e483462fd71aed1150e91657becd8a5aaf8 | clifford/test/test_multivector_inverse.py | clifford/test/test_multivector_inverse.py | import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades... | import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades... | Swap hitzer inverse test to use np.testing | Swap hitzer inverse test to use np.testing
| Python | bsd-3-clause | arsenovic/clifford,arsenovic/clifford |
ba8509a34104ff6aab5e97a6bed842b245ec4b64 | examples/pi-montecarlo/pi_distarray.py | examples/pi-montecarlo/pi_distarray.py | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | # encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""... | Update pi-montecarlo example to use `sum` again. | Update pi-montecarlo example to use `sum` again.
| Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray |
bba6c1f65010c208909d4f342b1d776c46c040c8 | Lib/importlib/test/__main__.py | Lib/importlib/test/__main__.py | import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '_... | import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sy... | Add support for a --builtin argument to importlib.test to trigger running import-specific tests with __import__ instead of importlib. | Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
8b7c5b7001ac005849fb31d83415db3a6517feb7 | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
| from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
... | Set the frame id to what aderk expects. | Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk |
7df717a48fb74ddd3b9ade644fb805020a20e91c | axiom/test/historic/test_processor1to2.py | axiom/test/historic/test_processor1to2.py |
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
... |
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# thi... | Fix an intermittent axiom test failure that occurs only in certain environments. | Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.
| Python | mit | twisted/axiom,hawkowl/axiom |
a7692bc810d1a30c9d0fa91bf1689651bd34d8c6 | moniek/accounting/views.py | moniek/accounting/views.py | from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
| from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
| Create home and accounts stub view | Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name>
| Python | agpl-3.0 | bwesterb/moniek,bwesterb/moniek |
1c736a5f48b2deb9732c65a5dec7ea47e542f6f4 | thinc/neural/_classes/resnet.py | thinc/neural/_classes/resnet.py | from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def be... | from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinsta... | Make residual connections work for list-valued inputs | Make residual connections work for list-valued inputs
| Python | mit | spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc |
db24629b7cc34f9a137c6bc5569dc7a39245fa52 | thinglang/compiler/sentinels.py | thinglang/compiler/sentinels.py | from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a ... | from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
c... | Add serialization sentintels for import table | Add serialization sentintels for import table
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
57461a7ebd35544c506e6b5021ff11c3b6dd943e | normandy/studies/models.py | normandy/studies/models.py | from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of ena... | from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def... | Add ordering to Extension model | Add ordering to Extension model
| Python | mpl-2.0 | mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy |
948f57469bc9e8144d6fceb49b5e2cf1d5858eeb | ores/wsgi/preprocessors.py | ores/wsgi/preprocessors.py | from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
... | from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
| Set minify to False as well as sometimes setting it to True. | Set minify to False as well as sometimes setting it to True.
| Python | mit | wiki-ai/ores,he7d3r/ores,he7d3r/ores,wiki-ai/ores,wiki-ai/ores,he7d3r/ores |
26f0b938bb8619f3ec705ff247c4d671613883fa | django/santropolFeast/member/factories.py | django/santropolFeast/member/factories.py | # coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = A... | # coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
mo... | Add a random <Route> to a generated <Client> | Add a random <Route> to a generated <Client>
Issue #214
| Python | agpl-3.0 | savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,madmath/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,madmath/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/santropol-feast |
7a3863355c36347c691d35166932e83a3f0352ea | examples/rmg/minimal_sensitivity/input.py | examples/rmg/minimal_sensitivity/input.py | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='et... | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
gener... | Update RMG example minimal_sensitivity with multiplicity label | Update RMG example minimal_sensitivity with multiplicity label
| Python | mit | nyee/RMG-Py,nyee/RMG-Py,enochd/RMG-Py,comocheng/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,chatelak/RMG-Py,comocheng/RMG-Py,pierrelb/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,nickvandewiele/RMG-Py |
7539a5445d24193395eed5dc658a4e69d8782736 | buffpy/tests/test_profile.py | buffpy/tests/test_profile.py | from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.g... | from unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.retu... | Migrate profile tests to pytest | Migrate profile tests to pytest
| Python | mit | vtemian/buffpy |
c383e06d51d4e59d400ab6fd62eff2359ab4e728 | python/the_birthday_bar.py | python/the_birthday_bar.py | #!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
... | #!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
... | Refactor to use map and filter | Refactor to use map and filter
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
ccab0ca5d1eba65d1ad6d1c3e4fe35b0cf883e0e | src/card.py | src/card.py | class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if at... | class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if at... | Change the default __getattr_ value | Change the default __getattr_ value
| Python | mit | theneosloth/Bolas |
8086ecd7d96dd4da4e90c583fd6300b9f87e3ef2 | src/main.py | src/main.py | import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
pr... | import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
pr... | Change the use of score_board object due to our change in score_board.py | Change the use of score_board object due to our change in score_board.py
| Python | mit | serenafr/My2048 |
dc0f76c676ec142fa6381fa4d6ac45e6f6127edf | common/util/update_wf_lib.py | common/util/update_wf_lib.py | #update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of seque... | #update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of seque... | Choose the pulses to update depending on library | Choose the pulses to update depending on library
| Python | apache-2.0 | BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab |
ba8d5c6ac809899265d13e366d66592efa12ca34 | imgfilter/filters/blurred_context.py | imgfilter/filters/blurred_context.py | import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extra... | import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extra... | Fix bug in blurred context recognition | Fix bug in blurred context recognition
| Python | mit | vismantic-ohtuprojekti/qualipy,vismantic-ohtuprojekti/image-filtering-suite |
e88c62f6e02cd84807d0b56468a0e0c21d2d4967 | imgur_downloader/directory_helper.py | imgur_downloader/directory_helper.py | import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just cr... | import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolu... | Raise an exception if File exist where download directory should be. | Raise an exception if File exist where download directory should be.
| Python | mit | odty101/ImgurDownloader |
3e397e79f49fc02bf78d3adaaaa90a65cf5caa67 | {{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py | {{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py | # -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{c... | # -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{c... | Remove the carousel fixture for the sake of simplicity | Remove the carousel fixture for the sake of simplicity
| Python | mit | hackebrot/cookiedozer,hackebrot/cookiedozer |
f5cd0de26f430f33fa91bfd21bc96914fe9c56b8 | troposphere/cloudwatch.py | troposphere/cloudwatch.py | # Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestri... | # Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (bas... | Allow Ref's in addition to basestrings | Allow Ref's in addition to basestrings
| Python | bsd-2-clause | jantman/troposphere,Yipit/troposphere,unravelin/troposphere,xxxVxxx/troposphere,alonsodomin/troposphere,Hons/troposphere,inetCatapult/troposphere,ptoraskar/troposphere,johnctitus/troposphere,cryptickp/troposphere,DualSpark/troposphere,dmm92/troposphere,7digital/troposphere,nicolaka/troposphere,ikben/troposphere,WeAreCl... |
2a99d8e3877162a3e06b324b84cb92ae26661d53 | packs/linux/actions/get_open_ports.py | packs/linux/actions/get_open_ports.py | import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ... | import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-pa... | Add a note about root and nmap binary dependency. | Add a note about root and nmap binary dependency.
| Python | apache-2.0 | armab/st2contrib,StackStorm/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,armab/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,jtopjian/st2contrib,dennybaa/st2contrib,pinterb/st2contrib,pinterb/st2contrib,meirwah/st2contrib,pearsontechnology/st2contrib,armab/st2contrib,tonybaloney/st2contrib,StackStorm... |
3b7452b6ffc52a4bc21128ddb9b04a6839286fe0 | cpm_data/wagtail_hooks.py | cpm_data/wagtail_hooks.py | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
sea... | from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
... | Add modeladmin classes for Season, JuryMember, Partner models | Add modeladmin classes for Season, JuryMember, Partner models
| Python | unlicense | nott/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,nott/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by |
2bfe8077d12a60450da10d53322d39d052bc6e0d | bud_get/cli.py | bud_get/cli.py | """ CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
... | """ CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output fi... | Print version in command line. | Print version in command line.
| Python | unlicense | doggan/bud-get |
dc512b896ca7311c0c04dc11b5283dc0ffb4f1e1 | seating_charts/management/commands/sync_students.py | seating_charts/management/commands/sync_students.py | #!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = lo... | #!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = lo... | Remove extra seating students during sync | Remove extra seating students during sync
| Python | mit | rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps |
9e9f71fd8a8fa9a78263c2adf260343c489eb602 | GitChat.py | GitChat.py | #!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = r... | #!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')... | Check directory is git repo | Check directory is git repo
| Python | apache-2.0 | shubhodeep9/GitChat,shubhodeep9/GitChat |
18f3cd10d07467eb9770ffe52b3d5b007f6967fe | cupy/array_api/_typing.py | cupy/array_api/_typing.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [... | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [... | Add a missing subscription slot to `NestedSequence` | MAINT: Add a missing subscription slot to `NestedSequence`
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
2f8fc66174b96f5ca45e4d656d9c1545d6d88720 | ixprofile_client/__init__.py | ixprofile_client/__init__.py | """
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.... | """
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'so... | Update social pipeline to social_core | Update social pipeline to social_core
| Python | mit | infoxchange/ixprofile-client,infoxchange/ixprofile-client |
62f6ac310f23ee529110529a3071f3c34f100fbb | examples/protocol/netstrings.py | examples/protocol/netstrings.py | grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(obj... | grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self... | Update the netstring code with newfound knowledge. | Update the netstring code with newfound knowledge.
| Python | mit | rbtcollins/parsley,rbtcollins/parsley,python-parsley/parsley,python-parsley/parsley |
12b181b585a54301c92103aa6ee979b628b76b59 | examples/crontabReader.py | examples/crontabReader.py | from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
... | import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!... | Add import error message to example | Add import error message to example
| Python | mit | Salamek/cron-descriptor,Salamek/cron-descriptor |
d82f569e5ea66020791325a31c4e0625ed1ee3a0 | captura/views.py | captura/views.py | from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render... | from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to rende... | Add userid to query to get socio-economic studies | Add userid to query to get socio-economic studies
| Python | mit | erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online |
229b92a2d83fc937da20aa4ea5325be5b587f1bc | docweb/tests/__init__.py | docweb/tests/__init__.py | import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstri... | import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstri... | Make Django to find the pydoc-tool.py script tests | Make Django to find the pydoc-tool.py script tests | Python | bsd-3-clause | pv/pydocweb,pv/pydocweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.