commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 19 3.3k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
7ad5e00abc9158951697e86242781567b82dd52c | oauth2_provider/generators.py | oauth2_provider/generators.py | from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
class BaseHashGenerator(object):
"""
All generators should extend this class overriding `.hash()` method.
"""
def hash(self):
raise NotImplementedError(... | from oauthlib.common import generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
class BaseHashGenerator(object):
"""
All generators should extend this class overriding `.... | Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations | Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
| Python | bsd-2-clause | cheif/django-oauth-toolkit,svetlyak40wt/django-oauth-toolkit,jensadne/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,Knotis/django-oauth-toolkit,jensadne/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,andrefsp/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,CloudNcodeIn... | from oauthlib.common import generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
class BaseHashGenerator(object):
"""
All generators should extend this class overriding `.... | Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id
from .settings import oau... |
3abe25d2272e2a0111511b68407da0ef3c53f59e | nazs/samba/module.py | nazs/samba/module.py | from nazs import module
from nazs.commands import run
from nazs.sudo import root
import os
import logging
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
ETC_FILE = '/etc/samba/smb.conf'
install_wizard = 'samba:instal... | from nazs import module
from nazs.commands import run
from nazs.sudo import root
import os
import logging
from .models import DomainSettings
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
ETC_FILE = '/etc/samba/smb.conf'... | Use wizard settings during samba provision | Use wizard settings during samba provision
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | from nazs import module
from nazs.commands import run
from nazs.sudo import root
import os
import logging
from .models import DomainSettings
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
ETC_FILE = '/etc/samba/smb.conf'... | Use wizard settings during samba provision
from nazs import module
from nazs.commands import run
from nazs.sudo import root
import os
import logging
logger = logging.getLogger(__name__)
class Samba(module.Module):
"""
Samba 4 module, it deploys samba AD and file server
"""
ETC_FILE = '/etc/samba/s... |
453b6a8697b066174802257156ac364aed2c650a | emission/storage/timeseries/aggregate_timeseries.py | emission/storage/timeseries/aggregate_timeseries.py | import logging
import pandas as pd
import pymongo
import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits
class AggregateTimeSeries(bits.BuiltinTimeSeries):
def __init__(self):
super(AggregateTimeSeries, self).__init__(None)
self.user_query = {}
| import logging
import pandas as pd
import pymongo
import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits
class AggregateTimeSeries(bits.BuiltinTimeSeries):
def __init__(self):
super(AggregateTimeSeries, self).__init__(None)
self.user_query = {}
... | Implement a sort key method for the aggregate timeseries | Implement a sort key method for the aggregate timeseries
This should return null because we want to mix up the identifying information
from the timeseries and sorting will re-impose some order. Also sorting takes
too much time!
| Python | bsd-3-clause | shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-... | import logging
import pandas as pd
import pymongo
import emission.core.get_database as edb
import emission.storage.timeseries.builtin_timeseries as bits
class AggregateTimeSeries(bits.BuiltinTimeSeries):
def __init__(self):
super(AggregateTimeSeries, self).__init__(None)
self.user_query = {}
... | Implement a sort key method for the aggregate timeseries
This should return null because we want to mix up the identifying information
from the timeseries and sorting will re-impose some order. Also sorting takes
too much time!
import logging
import pandas as pd
import pymongo
import emission.core.get_database as ed... |
01e62119750d0737e396358dbf45727dcbb5732f | tests/__init__.py | tests/__init__.py | import sys
import unittest
def main():
if sys.version_info[0] >= 3:
from unittest.main import main
main(module=None)
else:
unittest.main()
if __name__ == '__main__':
main()
| from unittest.main import main
if __name__ == '__main__':
main(module=None, verbosity=2)
| Drop Python 2 support in tests | Drop Python 2 support in tests
| Python | bsd-3-clause | retext-project/pymarkups,mitya57/pymarkups | from unittest.main import main
if __name__ == '__main__':
main(module=None, verbosity=2)
| Drop Python 2 support in tests
import sys
import unittest
def main():
if sys.version_info[0] >= 3:
from unittest.main import main
main(module=None)
else:
unittest.main()
if __name__ == '__main__':
main()
|
a7908b4f6369f5a29e72fa828aff12285e3f3d25 | app/applications.py | app/applications.py | from . import data_structures
# 1. Stack application
def balanced_parentheses_checker(symbol_string):
"""Verify that a set of parentheses is balanced."""
opening_symbols = '{[('
closing_symbols = '}])'
opening_symbols_stack = data_structures.Stack()
symbol_count = len(symbol_string)
counter =... | Apply stack in providing an efficient balanced parentheses-checker | Apply stack in providing an efficient balanced parentheses-checker
| Python | mit | andela-kerinoso/data_structures_algo | from . import data_structures
# 1. Stack application
def balanced_parentheses_checker(symbol_string):
"""Verify that a set of parentheses is balanced."""
opening_symbols = '{[('
closing_symbols = '}])'
opening_symbols_stack = data_structures.Stack()
symbol_count = len(symbol_string)
counter =... | Apply stack in providing an efficient balanced parentheses-checker
| |
f54db5d4e132fe1c227fe5bf1f7079772433429d | yunity/models/utils.py | yunity/models/utils.py | from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
... | from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
... | Add columns and values to repr | Add columns and values to repr
| Python | agpl-3.0 | yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend | from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
... | Add columns and values to repr
from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _ge... |
fbe7b34c575e30114c54587952c9aa919bc28d81 | south/introspection_plugins/__init__.py | south/introspection_plugins/__init__.py | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | Add import of django-annoying patch | Add import of django-annoying patch
| Python | apache-2.0 | theatlantic/django-south,theatlantic/django-south | # This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import south.introspection_plugins.django_o... | Add import of django-annoying patch
# This module contains built-in introspector plugins for various common
# Django apps.
# These imports trigger the lower-down files
import south.introspection_plugins.geodjango
import south.introspection_plugins.django_tagging
import south.introspection_plugins.django_taggit
import... |
b0d9a11292b6d6b17fe8b72d7735d26c47599187 | linkatos/printer.py | linkatos/printer.py | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | Change iteration over a collection based on ags suggestion | refactor: Change iteration over a collection based on ags suggestion
| Python | mit | iwi/linkatos,iwi/linkatos | def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose_explanation(url):
return "If you would like {} to be stored pleas... | refactor: Change iteration over a collection based on ags suggestion
def bot_says(channel, text, slack_client):
return slack_client.api_call("chat.postMessage",
channel=channel,
text=text,
as_user=True)
def compose... |
ee2e1727ece6b591b39752a1d3cd6a87d972226d | github3/search/code.py | github3/search/code.py | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
... | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
... | Add a __repr__ for CodeSearchResult | Add a __repr__ for CodeSearchResult
| Python | bsd-3-clause | h4ck3rm1k3/github3.py,ueg1990/github3.py,degustaf/github3.py,krxsky/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,agamdua/github3.py,wbrefvem/github3.py,jim-minter/github3.py,icio/github3.py,christophelec/github3.py,balloob/github3.py | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
... | Add a __repr__ for CodeSearchResult
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
... |
82162a334595ad47090dc1a8991d53ab5ece3736 | components/expression_evaluator.py | components/expression_evaluator.py | """A set of utility functions to evaluate expressions.
Sample Usage:
print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
t = tb.... | Add SgExpressionEvaluator - Evaluates expressions given fields and values | Add SgExpressionEvaluator - Evaluates expressions given fields and values
| Python | mit | lnishan/SQLGitHub | """A set of utility functions to evaluate expressions.
Sample Usage:
print(SgExpressionEvaluator.EvaluateExpressionInRow(["a", "bb", "ccc"], [1, 2, 3], "bb + 2.0 + ccc / a"))
print(SgExpressionEvaluator.EvaluateExpressionsInRow(["a", "bb", "ccc"], [1, 2, 3], ["bb + 2.0 + ccc / a", "a + bb + ccc"]))
t = tb.... | Add SgExpressionEvaluator - Evaluates expressions given fields and values
| |
2bcf80e71ffc75796ef7d3667f61e57a884e5c5b | angr/__init__.py | angr/__init__.py | """ Angr module """
# pylint: disable=wildcard-import
import logging
logging.getLogger("angr").addHandler(logging.NullHandler())
from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service impo... | """ Angr module """
# pylint: disable=wildcard-import
import logging
logging.getLogger("angr").addHandler(logging.NullHandler())
from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service impo... | Make default logging level ERROR | Make default logging level ERROR
| Python | bsd-2-clause | tyb0807/angr,axt/angr,chubbymaggie/angr,haylesr/angr,schieb/angr,chubbymaggie/angr,angr/angr,f-prettyland/angr,haylesr/angr,tyb0807/angr,axt/angr,angr/angr,angr/angr,schieb/angr,iamahuman/angr,chubbymaggie/angr,iamahuman/angr,schieb/angr,tyb0807/angr,iamahuman/angr,axt/angr,f-prettyland/angr,f-prettyland/angr | """ Angr module """
# pylint: disable=wildcard-import
import logging
logging.getLogger("angr").addHandler(logging.NullHandler())
from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .surveyor import *
from .service impo... | Make default logging level ERROR
""" Angr module """
# pylint: disable=wildcard-import
import logging
logging.getLogger("angr").addHandler(logging.NullHandler())
from .project import *
from .functionmanager import *
from .variableseekr import *
from .regmap import *
from .path import *
from .errors import *
from .su... |
762908c10fc3d9a6c9e30d9328e96c2a8bf3ce46 | setup.py | setup.py | """
The setup package to install MasterQA requirements
"""
from setuptools import setup, find_packages # noqa
from os import path
this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
with open(path.join(this_directory, 'README.md'), 'rb') as f:
long_description = f.read().d... | """
The setup package to install MasterQA requirements
"""
from setuptools import setup, find_packages # noqa
from os import path
this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
with open(path.join(this_directory, 'README.md'), 'rb') as f:
long_description = f.read().d... | Fix description content type for PyPi | Fix description content type for PyPi
| Python | mit | masterqa/MasterQA,mdmintz/MasterQA | """
The setup package to install MasterQA requirements
"""
from setuptools import setup, find_packages # noqa
from os import path
this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
with open(path.join(this_directory, 'README.md'), 'rb') as f:
long_description = f.read().d... | Fix description content type for PyPi
"""
The setup package to install MasterQA requirements
"""
from setuptools import setup, find_packages # noqa
from os import path
this_directory = path.abspath(path.dirname(__file__))
long_description = None
try:
with open(path.join(this_directory, 'README.md'), 'rb') as f... |
508c9ef5f7dfd974fdad650cf1a211dad9d41db5 | skipper/config.py | skipper/config.py | from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('c... | from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('c... | Handle env vars in volumes | Handle env vars in volumes
| Python | apache-2.0 | Stratoscale/skipper,Stratoscale/skipper | from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
containers = config.pop('c... | Handle env vars in volumes
from string import Template
from collections import defaultdict
import os
import yaml
def load_defaults():
skipper_conf = 'skipper.yaml'
defaults = {}
if os.path.exists(skipper_conf):
with open(skipper_conf) as confile:
config = yaml.load(confile)
... |
9c94c7c48f932e2134c2d520403fbfb09e464d95 | pygameMidi_extended.py | pygameMidi_extended.py | #import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan) | #import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan)
def set_volume(self, volume, channel):
... | Add Volume and Pitch methods | Add Volume and Pitch methods
| Python | bsd-3-clause | RenolY2/py-playBMS | #import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan)
def set_volume(self, volume, channel):
... | Add Volume and Pitch methods
#import pygame.midi.Output
from pygame.midi import Output
class Output(Output):#pygame.midi.Output):
def set_pan(self, pan, channel):
assert (0 <= channel <= 15)
assert pan <= 127
self.write_short(0xB0 + channel, 0x0A, pan) |
19a58255f247199d0e60408cab8220a8c2a1ff3b | qxlc/minifier.py | qxlc/minifier.py | import htmlmin
from markupsafe import Markup
from qxlc import app
@app.template_filter("minify")
def minify_filter(text):
return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))
| import htmlmin
from markupsafe import Markup
from qxlc import app
@app.template_filter("minify")
def minify_filter(s):
return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
| Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked) | Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
| Python | apache-2.0 | daboross/qxlc,daboross/qxlc | import htmlmin
from markupsafe import Markup
from qxlc import app
@app.template_filter("minify")
def minify_filter(s):
return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
| Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
import htmlmin
from markupsafe import Markup
from qxlc import app
@app.template_filter("minify")
def minify_filter(text):
return Markup(htmlmin.minify(text.unescape(), remove_comments=True, ... |
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312 | ideascube/mediacenter/tests/factories.py | ideascube/mediacenter/tests/factories.py | from django.conf import settings
import factory
from ..models import Document
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summary"
lang = settings.LANGUAGE_CODE
original = factory.django.FileFie... | from django.conf import settings
import factory
from ..models import Document
class EmptyFileField(factory.django.FileField):
DEFAULT_FILENAME = None
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summ... | Allow DocumentFactory to handle preview field. | Allow DocumentFactory to handle preview field.
The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'.
It means that by default a FileField created by factoryboy is considered as a
True value.
Before this commit, we were not defining a Document.preview field in the
factory so factoryboy created a empty FileFie... | Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from django.conf import settings
import factory
from ..models import Document
class EmptyFileField(factory.django.FileField):
DEFAULT_FILENAME = None
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summ... | Allow DocumentFactory to handle preview field.
The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'.
It means that by default a FileField created by factoryboy is considered as a
True value.
Before this commit, we were not defining a Document.preview field in the
factory so factoryboy created a empty FileFie... |
f890663daa329e3f22d0f619ed6acf9365308c7c | apps/ignite/views.py | apps/ignite/views.py | from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
project = get_object_or_404(Project, slug=pr... | from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
project = get_object_or_404(Project, slug=pr... | Update splash view to use visible() method. | Update splash view to use visible() method.
| Python | bsd-3-clause | mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite | from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
project = get_object_or_404(Project, slug=pr... | Update splash view to use visible() method.
from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
... |
cb7f4dfb9315c79448f2db52266df0f11aeb6210 | setup.py | setup.py | from setuptools import setup, find_packages
setup(name='coinop',
version='0.0.3',
description='Crypto-currency conveniences',
url='http://github.com/BitVault/coinop-py',
author='Matthew King',
author_email='matthew@bitvault.io',
license='MIT',
packages=find_packages(exclude=[... | from setuptools import setup, find_packages
setup(name='coinop',
version='0.1.0',
description='Crypto-currency conveniences',
url='http://github.com/BitVault/coinop-py',
author='Matthew King',
author_email='matthew@bitvault.io',
license='MIT',
packages=find_packages(exclude=[... | Make version number match patchboard, bitvault | Make version number match patchboard, bitvault
| Python | mit | GemHQ/coinop-py | from setuptools import setup, find_packages
setup(name='coinop',
version='0.1.0',
description='Crypto-currency conveniences',
url='http://github.com/BitVault/coinop-py',
author='Matthew King',
author_email='matthew@bitvault.io',
license='MIT',
packages=find_packages(exclude=[... | Make version number match patchboard, bitvault
from setuptools import setup, find_packages
setup(name='coinop',
version='0.0.3',
description='Crypto-currency conveniences',
url='http://github.com/BitVault/coinop-py',
author='Matthew King',
author_email='matthew@bitvault.io',
licen... |
f2eb45ea24429fd3e4d32a490dbe3f8a2f383d9f | scuole/stats/models/base.py | scuole/stats/models/base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase
@python_2_unicode_compatible
class S... | Add postsecondary stats to the StatsBase model | Add postsecondary stats to the StatsBase model
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
from .postsecondary_readiness import PostSecondaryReadinessBase
@python_2_unicode_compatible
class S... | Add postsecondary stats to the StatsBase model
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from .staff_student import StaffStudentBase
@python_2_unicode_compatible
class SchoolYear(models... |
e01697c5d5e5e45a0dd20870c71bb17399991ca1 | setup.py | setup.py | import os
from setuptools import setup, find_packages
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-nose',
version='0.2',
description='Django test runner that uses nose.',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Jeff Balogh',
author_email... | import os
from setuptools import setup, find_packages
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-nose',
version='0.2',
description='Django test runner that uses nose.',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Jeff Balogh',
author_email... | Comment out entrypoint because it blows up django-nose in connection with tox. Ouch. | Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.
| Python | bsd-3-clause | millerdev/django-nose,millerdev/django-nose,harukaeru/django-nose,dgladkov/django-nose,sociateru/django-nose,360youlun/django-nose,mzdaniel/django-nose,brilliant-org/django-nose,sociateru/django-nose,dgladkov/django-nose,krinart/django-nose,fabiosantoscode/django-nose-123-fix,mzdaniel/django-nose,franciscoruiz/django-n... | import os
from setuptools import setup, find_packages
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-nose',
version='0.2',
description='Django test runner that uses nose.',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Jeff Balogh',
author_email... | Comment out entrypoint because it blows up django-nose in connection with tox. Ouch.
import os
from setuptools import setup, find_packages
ROOT = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-nose',
version='0.2',
description='Django test runner that uses nose.',
long_description=ope... |
677d2d4f422f9b05746fa80d63492de4ae9aced4 | tests/test_examples.py | tests/test_examples.py | import pytest
import examples.basic_usage
import examples.basic_usage_manual
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
examples.variants.run(unihan_options=unihan_optio... | import importlib
import importlib.util
import sys
import types
import pytest
def load_script(example: str) -> types.ModuleType:
file_path = f"examples/{example}.py"
module_name = "run"
spec = importlib.util.spec_from_file_location(module_name, file_path)
assert spec is not None
module = importli... | Rework for handling of examples/ | refactor(tests): Rework for handling of examples/
| Python | mit | cihai/cihai,cihai/cihai | import importlib
import importlib.util
import sys
import types
import pytest
def load_script(example: str) -> types.ModuleType:
file_path = f"examples/{example}.py"
module_name = "run"
spec = importlib.util.spec_from_file_location(module_name, file_path)
assert spec is not None
module = importli... | refactor(tests): Rework for handling of examples/
import pytest
import examples.basic_usage
import examples.basic_usage_manual
import examples.dataset
import examples.variant_ts_difficulties
import examples.variants
def test_dataset(unihan_options):
examples.dataset.run()
def test_variants(unihan_options):
... |
893e4292f6b1799bf5f1888fcbad41ec8b5a5951 | examples/tic_ql_tabular_selfplay_all.py | examples/tic_ql_tabular_selfplay_all.py | '''
In this example we use Q-learning via self-play to learn
the value function of all Tic-Tac-Toe positions.
'''
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.rl import QLearningSelfPlay
from capstone.rl.tabularf import TabularF
from cap... | Use Q-learning to learn all state-action values via self-play | Use Q-learning to learn all state-action values via self-play
| Python | mit | davidrobles/mlnd-capstone-code | '''
In this example we use Q-learning via self-play to learn
the value function of all Tic-Tac-Toe positions.
'''
from capstone.environment import Environment
from capstone.game import TicTacToe
from capstone.mdp import GameMDP
from capstone.rl import QLearningSelfPlay
from capstone.rl.tabularf import TabularF
from cap... | Use Q-learning to learn all state-action values via self-play
| |
514614c68ced19e364e484e4dbec044e3fb03e24 | setup.py | setup.py | from setuptools import setup, find_packages
from taggit import VERSION
f = open('README.txt')
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagging.',
long_description=readme,
author='Alex... | import os
from setuptools import setup, find_packages
from taggit import VERSION
f = open(os.path.join(os.path.dirname(__file__), 'README.txt'))
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagg... | Update on suggestion of jezdez. | Update on suggestion of jezdez.
| Python | bsd-3-clause | twig/django-taggit,kminkov/django-taggit,orbitvu/django-taggit,cimani/django-taggit,tamarmot/django-taggit,laanlabs/django-taggit,kaedroho/django-taggit,theatlantic/django-taggit,vhf/django-taggit,izquierdo/django-taggit,theatlantic/django-taggit2,doselect/django-taggit,adrian-sgn/django-taggit,nealtodd/django-taggit,d... | import os
from setuptools import setup, find_packages
from taggit import VERSION
f = open(os.path.join(os.path.dirname(__file__), 'README.txt'))
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagg... | Update on suggestion of jezdez.
from setuptools import setup, find_packages
from taggit import VERSION
f = open('README.txt')
readme = f.read()
f.close()
setup(
name='django-taggit',
version=".".join(VERSION),
description='django-taggit is a reusable Django application for simple tagging.',
long_des... |
d436bcc20be8eb81960a53d442f699e42e2f9ea7 | src/tkjoincsv.py | src/tkjoincsv.py |
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename =... |
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename =... | Allow saving to a file that does not already exist again. | Allow saving to a file that does not already exist again.
| Python | apache-2.0 | peterSW/corow |
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
input_filename = sys.argv[1]
else:
input_filename =... | Allow saving to a file that does not already exist again.
import tkFileDialog
import joincsv
import os.path
import sys
if __name__ == '__main__':
filetypes=[("Spreadsheets", "*.csv"),
("Spreadsheets", "*.xls"),
("Spreadsheets", "*.xlsx")]
if len(sys.argv) == 2:
inpu... |
42bfa6b69697c0c093a961df5708f477288a6efa | icekit/plugins/twitter_embed/forms.py | icekit/plugins/twitter_embed/forms.py | import re
from django import forms
from fluent_contents.forms import ContentItemForm
class TwitterEmbedAdminForm(ContentItemForm):
def clean_twitter_url(self):
"""
Make sure the URL provided matches the twitter URL format.
"""
url = self.cleaned_data['twitter_url']
if url:... | import re
from django import forms
from fluent_contents.forms import ContentItemForm
from icekit.plugins.twitter_embed.models import TwitterEmbedItem
class TwitterEmbedAdminForm(ContentItemForm):
class Meta:
model = TwitterEmbedItem
fields = '__all__'
def clean_twitter_url(self):
"""
... | Add model and firld information to form. | Add model and firld information to form.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | import re
from django import forms
from fluent_contents.forms import ContentItemForm
from icekit.plugins.twitter_embed.models import TwitterEmbedItem
class TwitterEmbedAdminForm(ContentItemForm):
class Meta:
model = TwitterEmbedItem
fields = '__all__'
def clean_twitter_url(self):
"""
... | Add model and firld information to form.
import re
from django import forms
from fluent_contents.forms import ContentItemForm
class TwitterEmbedAdminForm(ContentItemForm):
def clean_twitter_url(self):
"""
Make sure the URL provided matches the twitter URL format.
"""
url = self.cl... |
591a40b6e1f4ac8b1d21050ccfa10779dc9dbf7c | analytic_code.py | analytic_code.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Add string to display the name of the field Dimension during the import | Add string to display the name of the field Dimension during the import
| Python | agpl-3.0 | xcgd/analytic_structure | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Add string to display the name of the field Dimension during the import
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# ... |
031bce223eac9eda1f856a204a07149c8e9549fd | hoomd/update/__init__.py | hoomd/update/__init__.py | from hoomd.update.box_resize import BoxResize
# TODO remove when no longer necessary
class _updater:
pass
__all__ = [BoxResize]
| from hoomd.update.box_resize import BoxResize
# TODO remove when no longer necessary
class _updater:
pass
__all__ = ['BoxResize']
| Fix typo in hoomd.update.__all__ quote class name | Fix typo in hoomd.update.__all__ quote class name
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | from hoomd.update.box_resize import BoxResize
# TODO remove when no longer necessary
class _updater:
pass
__all__ = ['BoxResize']
| Fix typo in hoomd.update.__all__ quote class name
from hoomd.update.box_resize import BoxResize
# TODO remove when no longer necessary
class _updater:
pass
__all__ = [BoxResize]
|
3fe4cb6fbafe69b9e7520466b7e7e2d405cf0ed0 | bookmarks/forms.py | bookmarks/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", verify_exists=True, widget=forms.TextInput(attrs={"size... | from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
descrip... | Make URLField compatible with Django 1.4 and remove verify_exists attribute | Make URLField compatible with Django 1.4 and remove verify_exists attribute
| Python | mit | incuna/incuna-bookmarks,incuna/incuna-bookmarks | from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.URLField(label = "URL", widget=forms.TextInput(attrs={"size": 40}))
descrip... | Make URLField compatible with Django 1.4 and remove verify_exists attribute
from django import forms
from django.utils.translation import ugettext_lazy as _
from tagging.forms import TagField
from bookmarks.models import Bookmark, BookmarkInstance
class BookmarkInstanceForm(forms.ModelForm):
url = forms.UR... |
0f047cded957bc67441a9acd65b46fab4bac6302 | SUASImageParser/ADLC/characteristic_identifier.py | SUASImageParser/ADLC/characteristic_identifier.py | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
... | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
... | Remove mention of Log parser | Remove mention of Log parser
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
... | Remove mention of Log parser
from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristi... |
f8a6b4d8053a60cfec372d8b91bf294d606055ec | app/admin/routes.py | app/admin/routes.py | from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return render_template('admin/user.html', user=... | from datetime import datetime
from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm, PostForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return... | Add a route to admin/news/post to post a news story. Uses the PostForm for forms | Add a route to admin/news/post to post a news story. Uses the PostForm for forms
| Python | mit | finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is | from datetime import datetime
from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm, PostForm
from .. import db
from ..models import User
@admin.route('/')
@login_required
def index():
return... | Add a route to admin/news/post to post a news story. Uses the PostForm for forms
from flask import render_template, redirect, url_for, flash, request
from flask.ext.login import login_required, current_user
from . import admin
from .forms import ProfileForm
from .. import db
from ..models import User
@admin.route('... |
479275674916e45c0a2b70a372962f3d0c271e4f | SatNOGS/base/management/commands/update_all_tle.py | SatNOGS/base/management/commands/update_all_tle.py | from orbit import satellite
from django.core.management.base import BaseCommand
from base.utils import update_all_satellites
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options):
satellites = Satellite.objets.all()
... | Add management command to update all existing satellite tle data | Add management command to update all existing satellite tle data
| Python | agpl-3.0 | cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network | from orbit import satellite
from django.core.management.base import BaseCommand
from base.utils import update_all_satellites
from base.models import Satellite
class Command(BaseCommand):
help = 'Create initial fixtures'
def handle(self, *args, **options):
satellites = Satellite.objets.all()
... | Add management command to update all existing satellite tle data
| |
959e30bed3dcaee03df929f8ec2848d07c745dc9 | tests/webcam_read_qr.py | tests/webcam_read_qr.py | #!/usr/bin/env python
"""
This module sets up a video stream from internal or connected webcam using Gstreamer.
You can then take snapshots.
import qrtools
qr = qrtools.QR()
qr.decode("cam.jpg")
print qr.data
"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gt... | Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code. | Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.
| Python | mit | daveol/Fedora-Test-Laptop,daveol/Fedora-Test-Laptop | #!/usr/bin/env python
"""
This module sets up a video stream from internal or connected webcam using Gstreamer.
You can then take snapshots.
import qrtools
qr = qrtools.QR()
qr.decode("cam.jpg")
print qr.data
"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gt... | Put gst code into Avocado test format. Needs to be edited to take a snapshot and read the qr code.
| |
290ead5bbc57e526f0fe12d161fa5fb684ab4edf | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import materializecssform
setup(
name='django-materializecss-form',
version=materializecssform.__version__,
packages=find_packages(),
author="Kal Walkden",
author_email="kal@walkden.us",
descriptio... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import materializecssform
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-materializecss-form',
version=materializecssform.__version__,
packages=find_packages(),
auth... | Update meta version so that documentation looks good in pypi | Update meta version so that documentation looks good in pypi
| Python | mit | florent1933/django-materializecss-form,florent1933/django-materializecss-form | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import materializecssform
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='django-materializecss-form',
version=materializecssform.__version__,
packages=find_packages(),
auth... | Update meta version so that documentation looks good in pypi
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import materializecssform
setup(
name='django-materializecss-form',
version=materializecssform.__version__,
packages=find_packages(),
author="Kal... |
cb45cea953880bf87a774bec4120bb0e7331d480 | tcconfig/parser/_model.py | tcconfig/parser/_model.py | from simplesqlite.model import Integer, Model, Text
from .._const import Tc
class Filter(Model):
device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
filter_id = Text(attr_name=Tc.Param.FILTER_ID)
flowid = Text(attr_name=Tc.Param.FLOW_ID)
protocol = Text(attr_name=Tc.Param.PROTOCOL)
priority =... | Add ORM models for filter/qdisc | Add ORM models for filter/qdisc
| Python | mit | thombashi/tcconfig,thombashi/tcconfig | from simplesqlite.model import Integer, Model, Text
from .._const import Tc
class Filter(Model):
device = Text(attr_name=Tc.Param.DEVICE, not_null=True)
filter_id = Text(attr_name=Tc.Param.FILTER_ID)
flowid = Text(attr_name=Tc.Param.FLOW_ID)
protocol = Text(attr_name=Tc.Param.PROTOCOL)
priority =... | Add ORM models for filter/qdisc
| |
d757ec338478ac67f984c1b7aa898f1c374b2a09 | openprescribing/frontend/tests/commands/test_import_ccg_boundaries.py | openprescribing/frontend/tests/commands/test_import_ccg_boundaries.py | from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT
def setUpModule():
call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
verbosity=0)
def tearDownModule():
call_command('flush', verbosity=0, interactive=False)
class ... | from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT
def setUpModule():
call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
verbosity=0)
def tearDownModule():
call_command('flush', verbosity=0, interactive=False)
class ... | Use almostEqual for comparing geo coordinates | Use almostEqual for comparing geo coordinates
An upgrade in one of the underlying libraries has shifted the numbers
very slightly.
| Python | mit | annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc | from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT
def setUpModule():
call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
verbosity=0)
def tearDownModule():
call_command('flush', verbosity=0, interactive=False)
class ... | Use almostEqual for comparing geo coordinates
An upgrade in one of the underlying libraries has shifted the numbers
very slightly.
from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT
def setUpModule():
call_command('loaddata', 'frontend/tests/fixtures... |
c02cad5047ff397229e1139109df80208e7dd5b6 | fireant/__init__.py | fireant/__init__.py | # coding: utf-8
__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=12, patch=0)
| # coding: utf-8
__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)
| Bump fireant version to 0.13.0 | Bump fireant version to 0.13.0
| Python | apache-2.0 | kayak/fireant,mikeengland/fireant | # coding: utf-8
__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=13, patch=0)
| Bump fireant version to 0.13.0
# coding: utf-8
__version__ = '{major}.{minor}.{patch}'.format(major=0, minor=12, patch=0)
|
0ad8d8665f064542346c3788cecaffdcb68f168a | plasmapy/utils/tests/test_exceptions.py | plasmapy/utils/tests/test_exceptions.py | import pytest
import warnings
from .. import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError)
from .. import (PlasmaPyWarning,
PhysicsWarning,
RelativityWarning,
AtomicWarning)
plasmapy_exceptions = [
Plas... | Create tests for custom exceptions and warnings | Create tests for custom exceptions and warnings
| Python | bsd-3-clause | StanczakDominik/PlasmaPy | import pytest
import warnings
from .. import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError)
from .. import (PlasmaPyWarning,
PhysicsWarning,
RelativityWarning,
AtomicWarning)
plasmapy_exceptions = [
Plas... | Create tests for custom exceptions and warnings
| |
85d2c012bfaeeb04fa8dd31cd05a04a8dc43c14e | tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py | tests/grammar_term-nonterm_test/NonterminalsInvalidTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar
class NonterminalsInvalidTest(TestCase):
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar as Grammar
from grammpy import Nonterminal
from grammpy.exceptions import NotNonterminalException
class TempClass(... | Add tests that have and get of nonterms raise exceptions | Add tests that have and get of nonterms raise exceptions
| Python | mit | PatrikValkovic/grammpy | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar as Grammar
from grammpy import Nonterminal
from grammpy.exceptions import NotNonterminalException
class TempClass(... | Add tests that have and get of nonterms raise exceptions
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy.RawGrammar import RawGrammar
class NonterminalsInvalidTest(TestCase):
pass
... |
8214d516b3feba92ab3ad3b1f2fa1cf253e83012 | pyexcel/internal/__init__.py | pyexcel/internal/__init__.py | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.int... | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.int... | Remove use of deprecated `scan_plugins` method | Remove use of deprecated `scan_plugins` method
`scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This
is causing warnings to be logged.
The new method takes a regular expression as its first argument, rather than a
simple prefix string. This commit adds a regular expression which does the s... | Python | bsd-3-clause | chfw/pyexcel,chfw/pyexcel | """
pyexcel.internal
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pyexcel internals that subjected to change
:copyright: (c) 2015-2017 by Onni Software Ltd.
:license: New BSD License
"""
from lml.loader import scan_plugins
from pyexcel.internal.plugins import PARSER, RENDERER # noqa
from pyexcel.int... | Remove use of deprecated `scan_plugins` method
`scan_plugins` has been deprecated in favour of `scan_plugins_regex`. This
is causing warnings to be logged.
The new method takes a regular expression as its first argument, rather than a
simple prefix string. This commit adds a regular expression which does the s... |
9140b3249820d0dd86f7f85270327d9264841b50 | tests/search_backend_mysql.py | tests/search_backend_mysql.py | from wolis.test_case import WolisTestCase
from wolis import utils
class SearchBackendMysqlTest(WolisTestCase):
@utils.restrict_database('mysql*')
@utils.restrict_phpbb_version('>=3.1.0')
def test_set_search_backend(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morphe... | Test for selecting mysql search backend | Test for selecting mysql search backend
| Python | bsd-2-clause | p/wolis-phpbb,p/wolis-phpbb | from wolis.test_case import WolisTestCase
from wolis import utils
class SearchBackendMysqlTest(WolisTestCase):
@utils.restrict_database('mysql*')
@utils.restrict_phpbb_version('>=3.1.0')
def test_set_search_backend(self):
self.login('morpheus', 'morpheus')
self.acp_login('morpheus', 'morphe... | Test for selecting mysql search backend
| |
200efbba25130b84da80720329794e4c47806573 | NDIR_RasPi_Python/example.py | NDIR_RasPi_Python/example.py | import NDIR
import time
sensor = NDIR.Sensor(0x4D)
sensor.begin()
while True:
sensor.measure()
print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
time.sleep(1)
| import NDIR
import time
sensor = NDIR.Sensor(0x4D)
if sensor.begin() == False:
print("Adaptor initialization FAILED!")
exit()
while True:
if sensor.measure():
print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
else:
print("Sensor communication ERROR.")
time.sleep(1)
| Make use of the return value of begin() and measure() | Make use of the return value of begin() and measure() | Python | mit | SandboxElectronics/NDIR,SandboxElectronics/NDIR,SandboxElectronics/NDIR | import NDIR
import time
sensor = NDIR.Sensor(0x4D)
if sensor.begin() == False:
print("Adaptor initialization FAILED!")
exit()
while True:
if sensor.measure():
print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
else:
print("Sensor communication ERROR.")
time.sleep(1)
| Make use of the return value of begin() and measure()
import NDIR
import time
sensor = NDIR.Sensor(0x4D)
sensor.begin()
while True:
sensor.measure()
print("CO2 Concentration: " + str(sensor.ppm) + "ppm")
time.sleep(1)
|
fa991297168f216c208d53b880124a4f23250034 | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Add gzip to cx-freeze packages | Add gzip to cx-freeze packages
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Add gzip to cx-freeze packages
import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
... |
7a0b8550fa2f52519df81c7fa795d454e5e3b0bc | scripts/master/factory/dart/channels.py | scripts/master/factory/dart/channels.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | Update the build branch for stable to 0.7 | Update the build branch for stable to 0.7
TBR=ricow
Review URL: https://codereview.chromium.org/26993005
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | Update the build branch for stable to 0.7
TBR=ricow
Review URL: https://codereview.chromium.org/26993005
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@228644 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style l... |
02f35718c6f6c3b18851b94e232031738629684e | promgen/sender/__init__.py | promgen/sender/__init__.py | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
for alert in data['alerts']:
if 'project' in alert['labels']:
sent = 0
for project in Project.objects.filter(name=al... | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
sent = 0
for alert in data['alerts']:
if 'project' in alert['labels']:
logger.debug('Checking for projects')
... | Fix send count and add debug logging | Fix send count and add debug logging
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
sent = 0
for alert in data['alerts']:
if 'project' in alert['labels']:
logger.debug('Checking for projects')
... | Fix send count and add debug logging
import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
for alert in data['alerts']:
if 'project' in alert['labels']:
sent = 0
for pro... |
50b773cdde5b367ee6cb44426817664ee379ee9f | setup.py | setup.py | from setuptools import setup
setup(
name='jobcli',
version='0.1.a2',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',... | from setuptools import setup
setup(
name='jobcli',
version='0.1b1',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
... | Increase version to beta 1. | Increase version to beta 1.
| Python | mit | jobcli/jobcli-app,jobcli/jobcli-app | from setuptools import setup
setup(
name='jobcli',
version='0.1b1',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email='stephan.goergen@gmail.com',
... | Increase version to beta 1.
from setuptools import setup
setup(
name='jobcli',
version='0.1.a2',
py_modules=['jobcli'],
install_requires=['click', 'requests',],
entry_points={'console_scripts':['jobcli=jobcli:cli',]},
url='https://www.jobcli.com',
author='Stephan Goergen',
author_email... |
a667b3503b0434f01459bae2d29df800d95ba1c4 | gapipy/resources/tour/departure.py | gapipy/resources/tour/departure.py | from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
_is_listable = True
_is_par... | from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
_is_listable = True
_is_par... | Add name to Departure resource | Add name to Departure resource
| Python | mit | gadventures/gapipy | from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
_is_listable = True
_is_par... | Add name to Departure resource
from __future__ import unicode_literals
from ...models import Address, AddOn, DepartureRoom, PP2aPrice
from ..base import Product
from .tour_dossier import TourDossier
from .departure_component import DepartureComponent
class Departure(Product):
_resource_name = 'departures'
... |
b55676c4cfb2d662c9a82d17504db091449e3992 | setup.py | setup.py | from setuptools import setup, find_packages
setup(name='scattertext',
version='0.0.2.22',
description='An NLP package to visualize interesting terms in text.',
url='https://github.com/JasonKessler/scattertext',
author='Jason Kessler',
author_email='jason.kessler@gmail.com',
license=... | from setuptools import setup, find_packages
setup(name='scattertext',
version='0.0.2.22',
description='An NLP package to visualize interesting terms in text.',
url='https://github.com/JasonKessler/scattertext',
author='Jason Kessler',
author_email='jason.kessler@gmail.com',
license=... | Replace `sklearn` dependency with `scikit-learn` | Replace `sklearn` dependency with `scikit-learn`
`sklearn` isn't the package you're looking for; as https://pypi.python.org/pypi/sklearn politely notes, you should "use scikit-learn instead": https://pypi.python.org/pypi/scikit-learn/
It's unfortunate that the names of Python packages have nothing to do with their ... | Python | apache-2.0 | JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext,JasonKessler/scattertext | from setuptools import setup, find_packages
setup(name='scattertext',
version='0.0.2.22',
description='An NLP package to visualize interesting terms in text.',
url='https://github.com/JasonKessler/scattertext',
author='Jason Kessler',
author_email='jason.kessler@gmail.com',
license=... | Replace `sklearn` dependency with `scikit-learn`
`sklearn` isn't the package you're looking for; as https://pypi.python.org/pypi/sklearn politely notes, you should "use scikit-learn instead": https://pypi.python.org/pypi/scikit-learn/
It's unfortunate that the names of Python packages have nothing to do with their ... |
d5c296197c7f5b422f44e58f8e58ead5fdc5c2ad | reports/models.py | reports/models.py | from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Report(models.Model):
addressed_to = models.TextField()
reported_from = models.ForeignKey('members.User')
content = models.TextField()
created_at = models.DateField(_("Date"), defa... | from datetime import datetime
from django.db import models
class Report(models.Model):
addressed_to = models.TextField()
reported_from = models.ForeignKey('members.User')
content = models.TextField()
created_at = models.DateField(default=datetime.now)
copies = models.ManyToManyField('protocols.Top... | Add new initial migration for reports | Add new initial migration for reports
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from datetime import datetime
from django.db import models
class Report(models.Model):
addressed_to = models.TextField()
reported_from = models.ForeignKey('members.User')
content = models.TextField()
created_at = models.DateField(default=datetime.now)
copies = models.ManyToManyField('protocols.Top... | Add new initial migration for reports
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Report(models.Model):
addressed_to = models.TextField()
reported_from = models.ForeignKey('members.User')
content = models.TextField()
create... |
c8af52e91eb5ea40090a4b303e147c2d5d6cf28a | cloudbaseinit/shell.py | cloudbaseinit/shell.py | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | Fix py3 x64 crash thread related | Fix py3 x64 crash thread related
Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd
| Python | apache-2.0 | chialiang-8/cloudbase-init,stackforge/cloudbase-init,openstack/cloudbase-init,stefan-caraiman/cloudbase-init,cmin764/cloudbase-init,alexpilotti/cloudbase-init,ader1990/cloudbase-init | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | Fix py3 x64 crash thread related
Change-Id: Iac00ea2463df4346ad60a17d0ba9a2af089c87cd
# Copyright 2012 Cloudbase Solutions Srl
#
# 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
#
# ... |
60bf4d1457059b3cd53e5b37eab6d428ff4df511 | src/artgraph/plugins/infobox.py | src/artgraph/plugins/infobox.py | from artgraph.plugins.plugin import Plugin
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
wikicode = self.get_wikicode(self._node.get_tit... | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wi... | Fix imports to be able to import properly from the worker nodes | Fix imports to be able to import properly from the worker nodes | Python | mit | dMaggot/ArtistGraph | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wi... | Fix imports to be able to import properly from the worker nodes
from artgraph.plugins.plugin import Plugin
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_node... |
1058ed0847d151246299f73b325004fc04946fa0 | Basics/challenge_2.py | Basics/challenge_2.py | #!/usr/bin/env python
if __name__ == '__main__':
s1 = 0x1c0111001f010100061a024b53535009181c
s2 = 0x686974207468652062756c6c277320657965
print(hex(s1 ^ s2))
| Set 1 - Challenge 2 | Set 1 - Challenge 2
| Python | apache-2.0 | Scythe14/Crypto | #!/usr/bin/env python
if __name__ == '__main__':
s1 = 0x1c0111001f010100061a024b53535009181c
s2 = 0x686974207468652062756c6c277320657965
print(hex(s1 ^ s2))
| Set 1 - Challenge 2
| |
79ac1550b5acd407b2a107e694c66cccfbc0be89 | alerts/lib/deadman_alerttask.py | alerts/lib/deadman_alerttask.py | from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def __init__(self):
self.deadman = True
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.e... | from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
| Remove deadman alerttask init method | Remove deadman alerttask init method
| Python | mpl-2.0 | jeffbryner/MozDef,gdestuynder/MozDef,mozilla/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,Phrozyn/MozDef,mozilla/MozDef,jeffbryner/MozDef,mozilla/MozDef... | from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found or not
return self.main_query.execute(self.es, indices=self.event_indices, size=1)
| Remove deadman alerttask init method
from alerttask import AlertTask
class DeadmanAlertTask(AlertTask):
def __init__(self):
self.deadman = True
def executeSearchEventsSimple(self):
# We override this method to specify the size as 1
# since we only care about if ANY events are found o... |
adab4c914d759f84731bc736fc9afe9862f8222e | tests/backends/gstreamer.py | tests/backends/gstreamer.py | import unittest
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase):
uri = ['file://data/song1.... | import unittest
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase):
uris = ['file://data/song1... | Fix typo in GStreamer test | Fix typo in GStreamer test
| Python | apache-2.0 | woutervanwijk/mopidy,hkariti/mopidy,quartz55/mopidy,woutervanwijk/mopidy,swak/mopidy,vrs01/mopidy,vrs01/mopidy,tkem/mopidy,jmarsik/mopidy,kingosticks/mopidy,swak/mopidy,mokieyue/mopidy,kingosticks/mopidy,bacontext/mopidy,glogiotatidis/mopidy,priestd09/mopidy,mokieyue/mopidy,ali/mopidy,hkariti/mopidy,mokieyue/mopidy,tke... | import unittest
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase):
uris = ['file://data/song1... | Fix typo in GStreamer test
import unittest
from mopidy.backends.gstreamer import GStreamerBackend
from tests.backends import (BasePlaybackControllerTest,
BaseCurrentPlaylistControllerTest)
class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase):
... |
dfb53cd63c908f13dafcc159ce337af653523748 | datasets/forms.py | datasets/forms.py | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(for... | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(for... | Remove upper case Not Present | Remove upper case Not Present
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class PresentNotPresentUnsureForm(for... | Remove upper case Not Present
from django import forms
from datasets.models import DatasetRelease, CategoryComment
class DatasetReleaseForm(forms.ModelForm):
max_number_of_sounds = forms.IntegerField(required=False)
class Meta:
model = DatasetRelease
fields = ['release_tag', 'type']
class ... |
d2106c0a6cb4bbf523914786ded873261cb174c2 | nipype/pipeline/__init__.py | nipype/pipeline/__init__.py | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from .engine import Node, MapNode, Workflow
from .utils import write_prov
| # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from engine import Node, MapNode, JoinNode, Workflow
from .utils import write_prov
| Add JoinNode to pipeline init | Add JoinNode to pipeline init
| Python | bsd-3-clause | arokem/nipype,gerddie/nipype,Leoniela/nipype,fprados/nipype,pearsonlab/nipype,blakedewey/nipype,carolFrohlich/nipype,blakedewey/nipype,gerddie/nipype,dgellis90/nipype,glatard/nipype,arokem/nipype,carlohamalainen/nipype,carolFrohlich/nipype,Leoniela/nipype,glatard/nipype,dmordom/nipype,grlee77/nipype,carolFrohlich/nipyp... | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from engine import Node, MapNode, JoinNode, Workflow
from .utils import write_prov
| Add JoinNode to pipeline init
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Package contains modules for generating pipelines using interfaces
"""
__docformat__ = 'restructuredtext'
from .engine import Node, MapNode, Workflow
from .utils import w... |
896a9b3d116a6ac2d313c5ea8dbc16345a097138 | linguine/ops/StanfordCoreNLP.py | linguine/ops/StanfordCoreNLP.py | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
def __init__(self):
# I don't see anywhere to put properties like this path...
# For now it's hardcoded and would ... | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their... | Format JSON to be collections of tokens | Format JSON to be collections of tokens
When coreNLP returns the JSON payload, it is in an unmanageable format
where multiple arrays are made for all parts of speech, tokens, and
lemmas. It's much easier to manage when the response is formatted as a
list of objects:
{
"token": "Pineapple",
"lemma": "Pineapple",
... | Python | mit | rigatoni/linguine-python,Pastafarians/linguine-python | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their... | Format JSON to be collections of tokens
When coreNLP returns the JSON payload, it is in an unmanageable format
where multiple arrays are made for all parts of speech, tokens, and
lemmas. It's much easier to manage when the response is formatted as a
list of objects:
{
"token": "Pineapple",
"lemma": "Pineapple",
... |
27d37833663842405f159127f30c6351958fcb10 | bench_examples/bench_dec_insert.py | bench_examples/bench_dec_insert.py | from csv import DictWriter
from ktbs_bench.utils.decorators import bench
@bench
def batch_insert(graph, file):
"""Insert triples in batch."""
print(graph, file)
if __name__ == '__main__':
# Define some graph/store to use
graph_list = ['g1', 'g2']
# Define some files to get the triples from
... | Add draft of example using the new @bench | Add draft of example using the new @bench
| Python | mit | ktbs/ktbs-bench,ktbs/ktbs-bench | from csv import DictWriter
from ktbs_bench.utils.decorators import bench
@bench
def batch_insert(graph, file):
"""Insert triples in batch."""
print(graph, file)
if __name__ == '__main__':
# Define some graph/store to use
graph_list = ['g1', 'g2']
# Define some files to get the triples from
... | Add draft of example using the new @bench
| |
6708fd75eb7272701e8e333e4940e47d5b6a05af | plugin_tests/web_client_test.py | plugin_tests/web_client_test.py | from tests import web_client_test
setUpModule = web_client_test.setUpModule
tearDownModule = web_client_test.tearDownModule
class WebClientTestCase(web_client_test.WebClientTestCase):
def setUp(self):
super(WebClientTestCase, self).setUp()
self.model('user').createUser(
login='mine... | Add a custom client side test runner | Add a custom client side test runner
| Python | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva | from tests import web_client_test
setUpModule = web_client_test.setUpModule
tearDownModule = web_client_test.tearDownModule
class WebClientTestCase(web_client_test.WebClientTestCase):
def setUp(self):
super(WebClientTestCase, self).setUp()
self.model('user').createUser(
login='mine... | Add a custom client side test runner
| |
468e82418ceec8eb453054c1b3fbce433a27240f | keyring/__init__.py | keyring/__init__.py | from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
try:
import pkg_resources
__version__ = pkg_resources.get_distribution('keyring').version
except... | from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
__all__ = (
'set_keyring', 'get_keyring', 'set_password', 'get_password',
'delete_password', 'ge... | Remove usage of pkg_resources, which has huge import overhead. | Remove usage of pkg_resources, which has huge import overhead. | Python | mit | jaraco/keyring | from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
__all__ = (
'set_keyring', 'get_keyring', 'set_password', 'get_password',
'delete_password', 'ge... | Remove usage of pkg_resources, which has huge import overhead.
from __future__ import absolute_import
from .core import (set_keyring, get_keyring, set_password, get_password,
delete_password)
from .getpassbackend import get_password as get_pass_get_password
try:
import pkg_resources
__versi... |
546a4681aa54ba183e956d220e98ef67ae6de691 | user/decorators.py | user/decorators.py | from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
if user.is_authenticated():
return v... | from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view... | Use functools.wraps to copy view signature. | Ch20: Use functools.wraps to copy view signature.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | from functools import wraps
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
from django.utils.decorators import \
available_attrs
def custom_login_required(view):
# view argument must be a function
@wraps(view, assigned=available_attrs(view... | Ch20: Use functools.wraps to copy view signature.
from django.conf import settings
from django.contrib.auth import get_user
from django.shortcuts import redirect
def custom_login_required(view):
# view argument must be a function
def new_view(request, *args, **kwargs):
user = get_user(request)
... |
9b255d781e3b0aefa708e1366810d14700384d10 | satyr/__init__.py | satyr/__init__.py | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.DEBU... | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO... | Set default logging level to INFO | Set default logging level to INFO
| Python | apache-2.0 | lensacom/satyr | from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
logging.basicConfig(level=logging.INFO... | Set default logging level to INFO
from __future__ import absolute_import, division, print_function
import logging
import pkg_resources as _pkg_resources
from .scheduler import QueueScheduler
from .executor import OneOffExecutor
from .messages import PythonTask, PythonTaskStatus # important to register classes
log... |
98190f0e96b2e2880e81b4801ebd5b04c1e9f1d8 | geomdl/__init__.py | geomdl/__init__.py | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | Fix importing * (star) from package | Fix importing * (star) from package
| Python | mit | orbingol/NURBS-Python,orbingol/NURBS-Python | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | Fix importing * (star) from package
""" This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these c... |
b59d1dd5afd63422cd478d8ee519347bd1c43e3b | project/urls.py | project/urls.py | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | Change ember app prefix to 'share/' | Change ember app prefix to 'share/'
| Python | apache-2.0 | CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | Change ember app prefix to 'share/'
"""share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$',... |
484636805602348c883d8dc775082169f97cce76 | crawler/management/commands/similar_apps_category_counter.py | crawler/management/commands/similar_apps_category_counter.py | import logging.config
from operator import or_
from django.core.management.base import BaseCommand
from crawler.models import *
logger = logging.getLogger('crawler.command')
class Command(BaseCommand):
help = 'Generate comparison between google similar app and ours'
def handle(self, *args, **options):
... | Create similar category counter command | Create similar category counter command
| Python | apache-2.0 | bkosawa/admin-recommendation | import logging.config
from operator import or_
from django.core.management.base import BaseCommand
from crawler.models import *
logger = logging.getLogger('crawler.command')
class Command(BaseCommand):
help = 'Generate comparison between google similar app and ours'
def handle(self, *args, **options):
... | Create similar category counter command
| |
deb5a6c45d6f52daef7ca5752f574d7c14abbc47 | admin/base/urls.py | admin/base/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r... | from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r... | Add preprints to the sidebar | Add preprints to the sidebar
[#OSF-7198]
| Python | apache-2.0 | mattclark/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,felliott/osf.io,cwisecarver/osf.io,adlius/osf.io,crcresearch/osf.io,caneruguz/osf.io,cslzchen/osf.io,pattisdr/osf.io,leb2dg/osf.io,mattclark/osf.io,mfraezz/osf.io,caseyrollins/osf.io,baylee-d/osf.io,chrisseto/osf.io,saradbowman/osf.io,brianjgeiger/osf.i... | from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', views.home, name='home'),
url(r... | Add preprints to the sidebar
[#OSF-7198]
from django.conf.urls import include, url
from django.contrib import admin
from settings import ADMIN_BASE
from . import views
base_pattern = '^{}'.format(ADMIN_BASE)
urlpatterns = [
### ADMIN ###
url(
base_pattern,
include([
url(r'^$', ... |
d3caf69dfe98aa2fd0f9046c01035cdd7e4e359e | opps/articles/tests/models.py | opps/articles/tests/models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Article, Post
class ArticleModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUp(self):
self.article = Article.objects.get(id=1)
def test_child_class(self):
s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Article, Post
class ArticleModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUp(self):
self.article = Article.objects.get(id=1)
def test_child_class(self):
s... | Test recommendation via article class | Test recommendation via article class
| Python | mit | williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Article, Post
class ArticleModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUp(self):
self.article = Article.objects.get(id=1)
def test_child_class(self):
s... | Test recommendation via article class
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.test import TestCase
from opps.articles.models import Article, Post
class ArticleModelTest(TestCase):
fixtures = ['tests/initial_data.json']
def setUp(self):
self.article = Article.objects.get(id=1)
... |
c43a677e19ba1d2603dd4b7907fe053561c4fa06 | neutron/objects/__init__.py | neutron/objects/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Use dirname in object recursive import | Use dirname in object recursive import
__file__ just returns the init file which there was nothing
under.
TrivialFix
Change-Id: I39da8a50c0b9197b7a5cb3d5ca4fd95f8d739eaa
| Python | apache-2.0 | openstack/neutron,huntxu/neutron,openstack/neutron,eayunstack/neutron,eayunstack/neutron,huntxu/neutron,mahak/neutron,openstack/neutron,mahak/neutron,mahak/neutron,noironetworks/neutron,noironetworks/neutron | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | Use dirname in object recursive import
__file__ just returns the init file which there was nothing
under.
TrivialFix
Change-Id: I39da8a50c0b9197b7a5cb3d5ca4fd95f8d739eaa
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may... |
c954c153525265b2b4ff0d89f0cf7f89c08a136c | settings/test_settings.py | settings/test_settings.py | # -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'),
... | # -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'),
... | Remove debug toolbar in test settings | Remove debug toolbar in test settings
| Python | mit | praba230890/junction,praba230890/junction,farhaanbukhsh/junction,farhaanbukhsh/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junction,praba230890/junction,ChillarAnand/junction,pythonindia/junction,nava45/junction,nava45/junction,ChillarAnand/junction,nava45/junction,ChillarAnand/junction,praba230890/... | # -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'test.sqlite3'),
... | Remove debug toolbar in test settings
# -*- coding: utf-8 -*-# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os... |
a77ead1975050938c8557979f54683829747bf0f | addons/sale_stock/migrations/8.0.1.0/pre-migration.py | addons/sale_stock/migrations/8.0.1.0/pre-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | Fix table name error in sale_stock column renames | Fix table name error in sale_stock column renames
| Python | agpl-3.0 | blaggacao/OpenUpgrade,sebalix/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,hifly/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,blaggacao/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,hifly/OpenUpgrade,Endika/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade/OpenUpgrade,pedrobaeza/OpenUpgrade,grap/OpenUpgrade,damdam-s/Ope... | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Af... | Fix table name error in sale_stock column renames
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, a suite of business apps
# This module Copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it ... |
7dbc1359ea4fb1b725fd53869a218856e4dec701 | lswapi/httpie/__init__.py | lswapi/httpie/__init__.py | """
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
class LswApiAuth(object):
def __init__(self, client_id, client_s... | """
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
class LswApiAuth(object):
def __init__(self, client_id, client_s... | Fix for function signature change in 0.4.0 in fetch_access_token | Fix for function signature change in 0.4.0 in fetch_access_token
| Python | apache-2.0 | nrocco/lswapi | """
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
class LswApiAuth(object):
def __init__(self, client_id, client_s... | Fix for function signature change in 0.4.0 in fetch_access_token
"""
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
cl... |
5beb443d4c9cf834be03ff33a2fb01605f8feb80 | pyof/v0x01/symmetric/hello.py | pyof/v0x01/symmetric/hello.py | """Defines Hello message."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.v0x01.common.header import Header, Type
__all__ = ('Hello',)
# Classes
class Hello(GenericMessage):
"""OpenFlow Hello Message.
This message does not contain a body beyond the Ope... | """Defines Hello message."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import BinaryData
from pyof.v0x01.common.header import Header, Type
__all__ = ('Hello',)
# Classes
class Hello(GenericMessage):
"""OpenFlow Hello Message.
... | Add optional elements in v0x01 Hello | Add optional elements in v0x01 Hello
For spec compliance. Ignore the elements as they're not used.
Fix #379
| Python | mit | kytos/python-openflow | """Defines Hello message."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.foundation.basic_types import BinaryData
from pyof.v0x01.common.header import Header, Type
__all__ = ('Hello',)
# Classes
class Hello(GenericMessage):
"""OpenFlow Hello Message.
... | Add optional elements in v0x01 Hello
For spec compliance. Ignore the elements as they're not used.
Fix #379
"""Defines Hello message."""
# System imports
# Third-party imports
from pyof.foundation.base import GenericMessage
from pyof.v0x01.common.header import Header, Type
__all__ = ('Hello',)
# Classes
class ... |
901bd73c61fbc6d9d8971ec1ce12e64100e633cb | base/settings/testing.py | base/settings/testing.py | # -*- coding: utf-8 -*-
import os
from .base import Base as Settings
class Testing(Settings):
# Database Configuration.
# ------------------------------------------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME... | # -*- coding: utf-8 -*-
import os
from .base import Base as Settings
class Testing(Settings):
# Database Configuration.
# ------------------------------------------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME... | Fix the Celery configuration under test settings. | Fix the Celery configuration under test settings.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | # -*- coding: utf-8 -*-
import os
from .base import Base as Settings
class Testing(Settings):
# Database Configuration.
# ------------------------------------------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME... | Fix the Celery configuration under test settings.
# -*- coding: utf-8 -*-
import os
from .base import Base as Settings
class Testing(Settings):
# Database Configuration.
# ------------------------------------------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.... |
c73d24259a6aa198d749fba097999ba2c18bd6da | website/addons/figshare/settings/defaults.py | website/addons/figshare/settings/defaults.py | API_URL = 'http://api.figshare.com/v1/'
API_OAUTH_URL = API_URL + 'my_data/'
MAX_RENDER_SIZE = 1000
| CLIENT_ID = None
CLIENT_SECRET = None
API_URL = 'http://api.figshare.com/v1/'
API_OAUTH_URL = API_URL + 'my_data/'
MAX_RENDER_SIZE = 1000
| Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. | Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
[skip ci]
| Python | apache-2.0 | mattclark/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,jnayak1/osf.io,SSJohns/osf.io,revanthkolli/osf.io,kch8qx/osf.io,amyshi188/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,revanthkolli/osf.io,jinluyuan/osf.io,cldershem/osf.io,KAsante95/osf.io,lamdnhan/osf.io,caseyrygt/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,caneruguz/o... | CLIENT_ID = None
CLIENT_SECRET = None
API_URL = 'http://api.figshare.com/v1/'
API_OAUTH_URL = API_URL + 'my_data/'
MAX_RENDER_SIZE = 1000
| Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
[skip ci]
API_URL = 'http://api.figshare.com/v1/'
API_OAUTH_URL = API_URL + 'my_data/'
MAX_RENDER_SIZE = 1000
|
539608a9ca9a21707184496e744fc40a8cb72cc1 | announce/management/commands/migrate_mailchimp_users.py | announce/management/commands/migrate_mailchimp_users.py | from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = logging.getLogger(__name__)
class Command(BaseCo... | from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = logging.getLogger(__name__)
class Command(BaseCo... | Remove once of code for mailchimp list migration | Remove once of code for mailchimp list migration
| Python | mit | p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles | from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = logging.getLogger(__name__)
class Command(BaseCo... | Remove once of code for mailchimp list migration
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from announce.mailchimp import archive_members, list_members, batch_subscribe
from studygroups.models import Profile
import requests
import logging
logger = ... |
305c3e0ce2705dd23e00ec801f5588ec1dbcc3a8 | py/two-sum-ii-input-array-is-sorted.py | py/two-sum-ii-input-array-is-sorted.py | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
head, tail = 0, len(numbers) - 1
while head < tail:
s = numbers[head] + numbers[tail]
if s == target:
... | Add py solution for 167. Two Sum II - Input array is sorted | Add py solution for 167. Two Sum II - Input array is sorted
167. Two Sum II - Input array is sorted: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
head, tail = 0, len(numbers) - 1
while head < tail:
s = numbers[head] + numbers[tail]
if s == target:
... | Add py solution for 167. Two Sum II - Input array is sorted
167. Two Sum II - Input array is sorted: https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
| |
619ca614890aa9d02acaf04fff51bee67233a8a8 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... | Fix NameError on Python 2.6 | Fix NameError on Python 2.6
| Python | agpl-3.0 | openhatch/oh-bugimporters,openhatch/oh-bugimporters,openhatch/oh-bugimporters | #!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='B... | Fix NameError on Python 2.6
#!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_p... |
ecce72199a8c9f0f333715419d572444d5b9fc90 | shade/tests/functional/test_devstack.py | shade/tests/functional/test_devstack.py | # Copyright (c) 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Add test to trap for missing services | Add test to trap for missing services
Recently when there was an issue with the magnum devstack plugin causing
the shade gate to not have swift, we didn't notice except through the
ansible tests. That's because we have a bunch of has_service checks in
the tests themselves to deal with different configs. Unfortunately,... | Python | apache-2.0 | openstack/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk,openstack-infra/shade,openstack-infra/shade | # Copyright (c) 2016 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Add test to trap for missing services
Recently when there was an issue with the magnum devstack plugin causing
the shade gate to not have swift, we didn't notice except through the
ansible tests. That's because we have a bunch of has_service checks in
the tests themselves to deal with different configs. Unfortunately,... | |
c36a088ad0d56f2a4dbff85bc33922ab95fbc184 | test_board_pytest.py | test_board_pytest.py | from board import Board
def test_addPiece():
print("Testing adding a piece.")
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item(0,4) == 1
| Add test for adding piece to board. | Add test for adding piece to board.
| Python | mit | isaacarvestad/four-in-a-row | from board import Board
def test_addPiece():
print("Testing adding a piece.")
board = Board(5,5)
board.addPiece(0, 1)
assert board.boardMatrix.item(0,4) == 1
| Add test for adding piece to board.
| |
90655c89fcf56af06a69f8110a9f7154294ca11c | ritter/analytics/sentiment_analyzer.py | ritter/analytics/sentiment_analyzer.py | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calculate_friend_scores... | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calcu... | Update to Sentimental 2.2.x with undersampling | feat: Update to Sentimental 2.2.x with undersampling
| Python | mit | ErikGartner/ghostdoc-ritter | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calcu... | feat: Update to Sentimental 2.2.x with undersampling
import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([p... |
e0385d0ba8fab48f129175123e103544574d1dac | commands.py | commands.py | #!/usr/bin/env python
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set... | from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False... | Remove shebang line from non-script. | Remove shebang line from non-script.
| Python | mit | dripton/ampchat | from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin: "UnauthorizedLogin"}
# If we set requiresAnswer = False... | Remove shebang line from non-script.
#!/usr/bin/env python
from twisted.protocols import amp
from twisted.cred.error import UnauthorizedLogin
# commands to server side
class Login(amp.Command):
arguments = [("username", amp.String()), ("password", amp.String())]
response = []
errors = {UnauthorizedLogin... |
4393740af93ae0ac1927e68c422e24735b0216c1 | infosystem/subsystem/policy/entity.py | infosystem/subsystem/policy/entity.py | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False)
capabil... | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False)
capabil... | Make role_id & bypass opt args in Policy __init__ | Make role_id & bypass opt args in Policy __init__
| Python | apache-2.0 | samueldmq/infosystem | from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.ForeignKey("domain.id"), nullable=False)
capabil... | Make role_id & bypass opt args in Policy __init__
from sqlalchemy import UniqueConstraint
from infosystem.common.subsystem import entity
from infosystem.database import db
class Policy(entity.Entity, db.Model):
attributes = ['id', 'capability_id', 'role_id', 'bypass']
domain_id = db.Column(db.CHAR(32), db.F... |
810a43c859264e3d5e1af8b43888bf89c06bee1d | ipybind/stream.py | ipybind/stream.py | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if han... | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if han... | Remove suppress() as it's no longer required | Remove suppress() as it's no longer required
| Python | mit | aldanor/ipybind,aldanor/ipybind,aldanor/ipybind | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if han... | Remove suppress() as it's no longer required
# -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None... |
c25b7820ccd52b943586af42d09ce53c3633ed96 | cmsplugin_simple_markdown/models.py | cmsplugin_simple_markdown/models.py | import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE... | import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE... | Add some tiny docstring to the unicode method | Add some tiny docstring to the unicode method
| Python | bsd-3-clause | Alir3z4/cmsplugin-simple-markdown,Alir3z4/cmsplugin-simple-markdown | import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_templates()
TEMPLATE_CHOICES = localdata.TEMPLATE... | Add some tiny docstring to the unicode method
import threading
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cmsplugin_simple_markdown import utils
localdata = threading.local()
localdata.TEMPLATE_CHOICES = utils.autodiscover_te... |
7e4aab6980519fd8124e36a6f8fd4415eaf8a4e7 | tests/test_tracer.py | tests/test_tracer.py | import os
import nose
import tracer
import logging
l = logging.getLogger("tracer.tests.test_tracer")
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
pov_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), "povs"))
test_data_location = str(os.path.di... | Add a single testcase for the tracer | Add a single testcase for the tracer
| Python | bsd-2-clause | schieb/angr,tyb0807/angr,tyb0807/angr,f-prettyland/angr,iamahuman/angr,angr/angr,angr/tracer,schieb/angr,iamahuman/angr,angr/angr,iamahuman/angr,schieb/angr,f-prettyland/angr,tyb0807/angr,f-prettyland/angr,angr/angr | import os
import nose
import tracer
import logging
l = logging.getLogger("tracer.tests.test_tracer")
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
pov_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), "povs"))
test_data_location = str(os.path.di... | Add a single testcase for the tracer
| |
7560bce01be5560395dd2373e979dbee086f3c21 | py2app/converters/nibfile.py | py2app/converters/nibfile.py | """
Automatic compilation of XIB files
"""
import subprocess, os
from py2app.decorators import converts
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
return
p = subprocess.Popen(['ibtool', '--compile', destination, so... | """
Automatic compilation of XIB files
"""
from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
gTool = None
def _get_ibtool():
global gTool
if gTool is None:
if os.path.exists('/usr/bin/xcrun'):
gTool = subprocess.check_output(['/usr/bin/xcrun'... | Simplify nib compiler and support recent Xcode versions by using xcrun | Simplify nib compiler and support recent Xcode versions by using xcrun
| Python | mit | metachris/py2app,metachris/py2app,metachris/py2app,metachris/py2app | """
Automatic compilation of XIB files
"""
from __future__ import print_function
import subprocess, os
from py2app.decorators import converts
gTool = None
def _get_ibtool():
global gTool
if gTool is None:
if os.path.exists('/usr/bin/xcrun'):
gTool = subprocess.check_output(['/usr/bin/xcrun'... | Simplify nib compiler and support recent Xcode versions by using xcrun
"""
Automatic compilation of XIB files
"""
import subprocess, os
from py2app.decorators import converts
@converts(suffix=".xib")
def convert_xib(source, destination, dry_run=0):
destination = destination[:-4] + ".nib"
if dry_run:
... |
fe78335e4f469e22f9a1de7a1e5ddd52021a7f0f | linesep.py | linesep.py | STARTER = -1
SEPARATOR = 0
TERMINATOR = 1
def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):
if mode < 0:
return _readlines_start(fp, sep, retain, size)
elif mode == 0:
return _readlines_sep(fp, sep, size)
else:
return _readlines_term(fp, sep, retain, size)
def _readli... | def read_begun(fp, sep, retain=True, size=512):
# Omits empty leading entry
entries = read_separated(fp, sep, size=size)
e = next(entries)
if e:
yield e
for e in entries:
if retain:
e = sep + e
yield e
def read_separated(fp, sep, size=512):
buff = ''
for ... | Use three public functions instead of one | Use three public functions instead of one
| Python | mit | jwodder/linesep | def read_begun(fp, sep, retain=True, size=512):
# Omits empty leading entry
entries = read_separated(fp, sep, size=size)
e = next(entries)
if e:
yield e
for e in entries:
if retain:
e = sep + e
yield e
def read_separated(fp, sep, size=512):
buff = ''
for ... | Use three public functions instead of one
STARTER = -1
SEPARATOR = 0
TERMINATOR = 1
def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):
if mode < 0:
return _readlines_start(fp, sep, retain, size)
elif mode == 0:
return _readlines_sep(fp, sep, size)
else:
return _readlin... |
f54c8f3b40bf44c4ba0f9fd1d1b6187991c327d5 | tests/lints/check-external-size.py | tests/lints/check-external-size.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
This script checks that all the external archive included in the repository are
as small as they can be.
"""
from __future__ import print_function
import os
import sys
import glob
ROOT = os.path.join(os.path.dirname(__file__), "..", "..")
ERRORS = 0
# when adding new ... | Add a test checking the external archive size | Add a test checking the external archive size
This should prevent size regressions
| Python | bsd-3-clause | Luthaf/Chemharp,chemfiles/chemfiles,chemfiles/chemfiles,chemfiles/chemfiles,Luthaf/Chemharp,Luthaf/Chemharp,chemfiles/chemfiles | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
This script checks that all the external archive included in the repository are
as small as they can be.
"""
from __future__ import print_function
import os
import sys
import glob
ROOT = os.path.join(os.path.dirname(__file__), "..", "..")
ERRORS = 0
# when adding new ... | Add a test checking the external archive size
This should prevent size regressions
| |
beac0323253454f343b32d42d8c065cfc4fcc04f | src/epiweb/apps/reminder/models.py | src/epiweb/apps/reminder/models.py | import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Reminder(models.Model):
user = models.ForeignKey(User, unique=True)
last_reminder = models.DateTimeField()
next_reminder = models.DateField()
wday = models.Inte... | import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
_ = lambda x: x
# Reference: http://docs.python.org/library/time.html
# - tm_wday => range [0,6], Monday is 0
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY =... | Set available options for weekday field of reminder's model | Set available options for weekday field of reminder's model
| Python | agpl-3.0 | ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website | import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
_ = lambda x: x
# Reference: http://docs.python.org/library/time.html
# - tm_wday => range [0,6], Monday is 0
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
THURSDAY = 3
FRIDAY = 4
SATURDAY =... | Set available options for weekday field of reminder's model
import datetime
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class Reminder(models.Model):
user = models.ForeignKey(User, unique=True)
last_reminder = models.DateTimeField()
... |
9ceace60593f133b4f6dfdbd9b6f583362415294 | src/configuration.py | src/configuration.py | import ConfigParser
import os
def class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self)
"""Open the configuration files handler, choosing the right
path depending o... | import ConfigParser
import os
class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self):
"""Open the configuration files handler, choosing the right
path depend... | Fix a few syntax errors | Fix a few syntax errors
| Python | agpl-3.0 | MichelJuillard/dlstats,Widukind/dlstats,mmalter/dlstats,mmalter/dlstats,Widukind/dlstats,MichelJuillard/dlstats,mmalter/dlstats,MichelJuillard/dlstats | import ConfigParser
import os
class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self):
"""Open the configuration files handler, choosing the right
path depend... | Fix a few syntax errors
import ConfigParser
import os
def class ConfigDlstats(object):
"""Cross platform configuration file handler.
This class manages dlstats configuration files, providing
easy access to the options."""
def __init__(self)
"""Open the configuration files handler, choosing the r... |
3b684eeadb0c8b39593b14c15233a314bbab0895 | troposphere/sns.py | troposphere/sns.py | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
... | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
... | Update SNS per 2019-11-21 changes | Update SNS per 2019-11-21 changes
| Python | bsd-2-clause | cloudtools/troposphere,ikben/troposphere,ikben/troposphere,cloudtools/troposphere | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endpoint': (basestring, True),
... | Update SNS per 2019-11-21 changes
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Tags
from .compat import policytypes
from .validators import boolean
class Subscription(AWSProperty):
props = {
'Endp... |
d52c9731b0c6494e9f4181fc33f00cdf39adb3ca | tests/unit/test_util.py | tests/unit/test_util.py | import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
| import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
@pytest.has_internet
def test_emergency_compliment():
assert util.load_emergency_compliments()
| Add test for emergency compliments | Add test for emergency compliments
| Python | mit | yougov/pmxbot,yougov/pmxbot,yougov/pmxbot | import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
@pytest.has_internet
def test_emergency_compliment():
assert util.load_emergency_compliments()
| Add test for emergency compliments
import pytest
from pmxbot import util
@pytest.has_wordnik
def test_lookup():
assert util.lookup('dachshund') is not None
|
4657acf6408b2fb416e2c9577ac09d18d81f8a68 | nameless/config.py | nameless/config.py | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
# Plugin settings
DATABASE_NAMES = ['atc', 'nhs', 'sms']
# Using sqlite for local development, will be SQL on production.
SQLALCHEMY_BINDS = {
'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'),
'nhs': 'sqlite:///' + os.path.join(_basedir, '... | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
# Plugin settings
DATABASE_NAMES = ['atc', 'sms']
# Using sqlite for local development, will be SQL on production.
SQLALCHEMY_BINDS = {
'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'),
'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.... | Remove unused NHS database mockup | Remove unused NHS database mockup
| Python | mit | jawrainey/sris | import os
_basedir = os.path.abspath(os.path.dirname(__file__))
# Plugin settings
DATABASE_NAMES = ['atc', 'sms']
# Using sqlite for local development, will be SQL on production.
SQLALCHEMY_BINDS = {
'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'),
'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.... | Remove unused NHS database mockup
import os
_basedir = os.path.abspath(os.path.dirname(__file__))
# Plugin settings
DATABASE_NAMES = ['atc', 'nhs', 'sms']
# Using sqlite for local development, will be SQL on production.
SQLALCHEMY_BINDS = {
'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'),
'nhs': 'sql... |
6c6934e8a36429e2a988835d8bd4d66fe95e306b | tensorflow_datasets/image/cifar_test.py | tensorflow_datasets/image/cifar_test.py | # coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# 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 appl... | # coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# 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 appl... | Move references of deleted generate_cifar10_like_example.py to the new name cifar.py | Move references of deleted generate_cifar10_like_example.py to the new name cifar.py
PiperOrigin-RevId: 225386826
| Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | # coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# 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 appl... | Move references of deleted generate_cifar10_like_example.py to the new name cifar.py
PiperOrigin-RevId: 225386826
# coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Yo... |
dcfb5116ba5f068afa354d063a4ab33bce853715 | numba/sigutils.py | numba/sigutils.py | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
return isinstance(sig, (str, tuple))
def normalize_signature(sig):
if isinstance(sig, str):
return normalize_signature(parse_signature(sig))
elif isinstance(sig, tuple):
... | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
"""
Return whether *sig* is a valid signature specification (for user-facing
APIs).
"""
return isinstance(sig, (str, tuple, typing.Signature))
def normalize_signature(sig):
... | Add docstrings and fix failures | Add docstrings and fix failures
| Python | bsd-2-clause | pitrou/numba,GaZ3ll3/numba,pitrou/numba,gdementen/numba,ssarangi/numba,gmarkall/numba,stonebig/numba,stonebig/numba,seibert/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,IntelLabs/numba,seibert/numba,pombredanne/numba,numba/numba,seibert/numba,jriehl/numba,pitrou/numba,numba/numba,stefanseefeld/numba,IntelLabs/numb... | from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
"""
Return whether *sig* is a valid signature specification (for user-facing
APIs).
"""
return isinstance(sig, (str, tuple, typing.Signature))
def normalize_signature(sig):
... | Add docstrings and fix failures
from __future__ import print_function, division, absolute_import
from numba import types, typing
def is_signature(sig):
return isinstance(sig, (str, tuple))
def normalize_signature(sig):
if isinstance(sig, str):
return normalize_signature(parse_signature(sig))
e... |
cbdfc1b1cb4162256538576cabe2b6832aa83bca | django_mysqlpool/__init__.py | django_mysqlpool/__init__.py | from functools import wraps
from django.db import connection
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
return wr... | from functools import wraps
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
retur... | Fix circular import when used with other add-ons that import django.db | Fix circular import when used with other add-ons that import django.db
eg sorl_thumbnail:
Traceback (most recent call last):
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module>
sys.exit(manage.main())
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/mana... | Python | mit | smartfile/django-mysqlpool | from functools import wraps
def auto_close_db(f):
"Ensures the database connection is closed when the function returns."
from django.db import connection
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
finally:
connection.close()
retur... | Fix circular import when used with other add-ons that import django.db
eg sorl_thumbnail:
Traceback (most recent call last):
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module>
sys.exit(manage.main())
File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/mana... |
cbb90d03b83a495b1c46514a583538f2cfc0d29c | test/functional/test_manager.py | test/functional/test_manager.py | from osmviz.manager import PILImageManager, OSMManager
import PIL.Image as Image
def test_pil():
imgr = PILImageManager("RGB")
osm = OSMManager(image_manager=imgr)
image, bnds = osm.createOSMImage((30, 35, -117, -112), 9)
wh_ratio = float(image.size[0]) / image.size[1]
image2 = image.resize((int(8... | from osmviz.manager import PILImageManager, OSMManager
import PIL.Image as Image
def test_pil():
image_manager = PILImageManager("RGB")
osm = OSMManager(image_manager=image_manager)
image, bounds = osm.createOSMImage((30, 31, -117, -116), 9)
wh_ratio = float(image.size[0]) / image.size[1]
image2 =... | Reduce number of tiles downloaded | Reduce number of tiles downloaded
| Python | mit | hugovk/osmviz,hugovk/osmviz | from osmviz.manager import PILImageManager, OSMManager
import PIL.Image as Image
def test_pil():
image_manager = PILImageManager("RGB")
osm = OSMManager(image_manager=image_manager)
image, bounds = osm.createOSMImage((30, 31, -117, -116), 9)
wh_ratio = float(image.size[0]) / image.size[1]
image2 =... | Reduce number of tiles downloaded
from osmviz.manager import PILImageManager, OSMManager
import PIL.Image as Image
def test_pil():
imgr = PILImageManager("RGB")
osm = OSMManager(image_manager=imgr)
image, bnds = osm.createOSMImage((30, 35, -117, -112), 9)
wh_ratio = float(image.size[0]) / image.size[... |
42a92130fc9d6f3358bb03a7ab56cdc5f20eb4d1 | tests/test_config.py | tests/test_config.py | import os
import pytest
from vrun import config
from vrun.compat import ConfigParser
@pytest.mark.parametrize('parts, result', [
(
['simple'],
['simple']
),
(
['multiple', 'simple'],
['multiple', 'simple']
),
(
['with', '"quotes"'],
['with', '"quot... | Add tests for ancillary functions | Add tests for ancillary functions
| Python | isc | bertjwregeer/vrun | import os
import pytest
from vrun import config
from vrun.compat import ConfigParser
@pytest.mark.parametrize('parts, result', [
(
['simple'],
['simple']
),
(
['multiple', 'simple'],
['multiple', 'simple']
),
(
['with', '"quotes"'],
['with', '"quot... | Add tests for ancillary functions
| |
20fa7e30e4658984a4057f5c99ef293216f57815 | base_phone/controllers/main.py | base_phone/controllers/main.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | Make click2dial work in real life | Make click2dial work in real life
| Python | agpl-3.0 | OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony,OCA/connector-telephony | # -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | Make click2dial work in real life
# -*- coding: utf-8 -*-
##############################################################################
#
# Base Phone module for Odoo
# Copyright (C) 2014-2015 Alexis de Lattre (alexis@via.ecp.fr)
#
# This program is free software: you can redistribute it and/or modify
# i... |
f499f58c765cbd83e77e44be1dfbccc3aed772c6 | mozillians/users/management/commands/reindex_mozillians.py | mozillians/users/management/commands/reindex_mozillians.py | from django.core.management.base import BaseCommand
from mozillians.users.tasks import index_all_profiles
class Command(BaseCommand):
def handle(self, *args, **options):
index_all_profiles()
| Add management command to reindex mozillians ES. | Add management command to reindex mozillians ES.
| Python | bsd-3-clause | akatsoulas/mozillians,mozilla/mozillians,johngian/mozillians,mozilla/mozillians,mozilla/mozillians,johngian/mozillians,akatsoulas/mozillians,johngian/mozillians,akatsoulas/mozillians,mozilla/mozillians,akatsoulas/mozillians,johngian/mozillians | from django.core.management.base import BaseCommand
from mozillians.users.tasks import index_all_profiles
class Command(BaseCommand):
def handle(self, *args, **options):
index_all_profiles()
| Add management command to reindex mozillians ES.
| |
469fdc0dfc756e68231eebd5ce40eb33e0fdd2f2 | fireplace/cards/gvg/rogue.py | fireplace/cards/gvg/rogue.py | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
##
# Spells
# Tinker's Sharpsword Oil
class GVG_022:
action = buffWeapon("GVG_022a")
def action(self):
if self.controller.weapon:
self.buff(self.controller.weapon, "GVG_022a")
if self.controller.field... | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
# One-eyed Cheat
class GVG_025:
def OWN_MINION_SUMMON(self, player, minion):
if minion.race == Race.PIRATE and minion != self:
self.stealth = True
# Iron Sensei
class GVG_027:
def OWN_TURN_END(self):
... | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
| Python | agpl-3.0 | beheh/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,NightKev/fireplace,smallnamespace/fireplace,jleclanche/fireplace,butozerca/fireplace,liujimj/fireplace,Ragowit/fireplace,liujimj/fireplace,smallnamespace/fireplace,amw2104/fireplace,amw2104/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Ragowit/fi... | from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
# One-eyed Cheat
class GVG_025:
def OWN_MINION_SUMMON(self, player, minion):
if minion.race == Race.PIRATE and minion != self:
self.stealth = True
# Iron Sensei
class GVG_027:
def OWN_TURN_END(self):
... | Implement One-eyed Cheat, Iron Sensei and Trade Prince Gallywix
from ..utils import *
##
# Minions
# Goblin Auto-Barber
class GVG_023:
action = buffWeapon("GVG_023a")
##
# Spells
# Tinker's Sharpsword Oil
class GVG_022:
action = buffWeapon("GVG_022a")
def action(self):
if self.controller.weapon:
self.bu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.