commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 3.18k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 5 43k | ndiff stringlengths 51 3.32k | instruction stringlengths 16 444 | content stringlengths 133 4.32k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ac492be603f958a29bbc6bb5215d79ec469d269 | tests/test_init.py | tests/test_init.py | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "USER"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = che... | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "PATH"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "PATH1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
good, results = c... | Update environment test to have cross platform support | Update environment test to have cross platform support
| Python | mit | humangeo/preflyt | """Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
- {"checker": "env", "name": "USER"}
+ {"checker": "env", "name": "PATH"}
]
BAD_CHECKERS = [
- {"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
+ {"checker": ... | Update environment test to have cross platform support | ## Code Before:
"""Test the checkers"""
from nose.tools import ok_, eq_
from preflyt import check
CHECKERS = [
{"checker": "env", "name": "USER"}
]
BAD_CHECKERS = [
{"checker": "env", "name": "USER1231342dhkfgjhk2394dv09324jk12039csdfg01231"}
]
def test_everything():
"""Test the check method."""
goo... |
131fb74b0f399ad3abff5dcc2b09621cac1226e7 | config/nox_routing.py | config/nox_routing.py | from experiment_config_lib import ControllerConfig
from sts.control_flow import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use NOX as our controller
command_line = "./nox_core -i ptcp:6633 routing"
... | from experiment_config_lib import ControllerConfig
from sts.control_flow import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
from sts.topology import MeshTopology
# Use NOX as our controller
command_lin... | Update NOX config to use sample_routing | Update NOX config to use sample_routing
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts | from experiment_config_lib import ControllerConfig
from sts.control_flow import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
+ from sts.topology import MeshTopology
# Use NOX as our contro... | Update NOX config to use sample_routing | ## Code Before:
from experiment_config_lib import ControllerConfig
from sts.control_flow import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use NOX as our controller
command_line = "./nox_core -i ptc... |
96e86fb389d67d55bf6b4e0f3f0f318e75b532dd | kirppu/management/commands/accounting_data.py | kirppu/management/commands/accounting_data.py | from django.core.management.base import BaseCommand
from django.utils.translation import activate
from kirppu.accounting import accounting_receipt
class Command(BaseCommand):
help = 'Dump accounting CSV to standard output'
def add_arguments(self, parser):
parser.add_argument('--lang', type=str, help... | from django.core.management.base import BaseCommand
from django.utils.translation import activate
from kirppu.accounting import accounting_receipt
class Command(BaseCommand):
help = 'Dump accounting CSV to standard output'
def add_arguments(self, parser):
parser.add_argument('--lang', type=str, help... | Fix accounting data dump command. | Fix accounting data dump command.
| Python | mit | jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu | from django.core.management.base import BaseCommand
from django.utils.translation import activate
from kirppu.accounting import accounting_receipt
class Command(BaseCommand):
help = 'Dump accounting CSV to standard output'
def add_arguments(self, parser):
parser.add_argument('-... | Fix accounting data dump command. | ## Code Before:
from django.core.management.base import BaseCommand
from django.utils.translation import activate
from kirppu.accounting import accounting_receipt
class Command(BaseCommand):
help = 'Dump accounting CSV to standard output'
def add_arguments(self, parser):
parser.add_argument('--lang'... |
ca75631f513c433c6024a2f00d045f304703a85d | webapp/tests/test_browser.py | webapp/tests/test_browser.py | import os
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from . import DATA_DIR
class BrowserTest(TestCase):
def test_browser(self):
url = reverse('graphite.browser.views.browser')
response = self.client.get(url)
... | import os
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from . import DATA_DIR
class BrowserTest(TestCase):
def test_browser(self):
url = reverse('graphite.browser.views.browser')
... | Add tests for making sure a user is dynamically created | Add tests for making sure a user is dynamically created
| Python | apache-2.0 | EinsamHauer/graphite-web-iow,bpaquet/graphite-web,Skyscanner/graphite-web,disqus/graphite-web,synedge/graphite-web,gwaldo/graphite-web,blacked/graphite-web,cosm0s/graphite-web,brutasse/graphite-web,blacked/graphite-web,bbc/graphite-web,gwaldo/graphite-web,Invoca/graphite-web,atnak/graphite-web,deniszh/graphite-web,dhte... | import os
+ from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from . import DATA_DIR
class BrowserTest(TestCase):
def test_browser(self):
url = reverse('graphit... | Add tests for making sure a user is dynamically created | ## Code Before:
import os
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from . import DATA_DIR
class BrowserTest(TestCase):
def test_browser(self):
url = reverse('graphite.browser.views.browser')
response = self.clie... |
20bd5c16d5850f988e92c39db3ff041c37c83b73 | contract_sale_generation/models/abstract_contract.py | contract_sale_generation/models/abstract_contract.py |
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.abstract.contract"
sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm")
@api.model
def _get_generation_type_selection(self):
res = super()._get_generation_type_selection()... |
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.abstract.contract"
sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm")
@api.model
def _selection_generation_type(self):
res = super()._selection_generation_type()
... | Align method on Odoo conventions | [14.0][IMP] contract_sale_generation: Align method on Odoo conventions
| Python | agpl-3.0 | OCA/contract,OCA/contract,OCA/contract |
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.abstract.contract"
sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm")
@api.model
- def _get_generation_type_selection(self):
+ def _selection_generation_... | Align method on Odoo conventions | ## Code Before:
from odoo import api, fields, models
class ContractAbstractContract(models.AbstractModel):
_inherit = "contract.abstract.contract"
sale_autoconfirm = fields.Boolean(string="Sale Autoconfirm")
@api.model
def _get_generation_type_selection(self):
res = super()._get_generation_... |
6422f6057d43dfb5259028291991f39c5b81b446 | spreadflow_core/flow.py | spreadflow_core/flow.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict
class Flowmap(dict):
def __init__(self):
super(Flowmap, self).__init__()
self.decorators = []
self.annotations = {}
def graph(self):
... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict, MutableMapping
class Flowmap(MutableMapping):
def __init__(self):
super(Flowmap, self).__init__()
self.annotations = {}
self.connections = {}... | Refactor Flowmap into a MutableMapping | Refactor Flowmap into a MutableMapping
| Python | mit | spreadflow/spreadflow-core,znerol/spreadflow-core | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
- from collections import defaultdict
+ from collections import defaultdict, MutableMapping
- class Flowmap(dict):
+ class Flowmap(MutableMapping):
def __init__(self):
super(Flow... | Refactor Flowmap into a MutableMapping | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import defaultdict
class Flowmap(dict):
def __init__(self):
super(Flowmap, self).__init__()
self.decorators = []
self.annotations = {}
def g... |
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):
... | Add optional elements in v0x01 Hello | ## Code Before:
"""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 bod... |
015d536e591d5af7e93f299e84504fe8a17f76b3 | tests.py | tests.py | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
... | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
... | Test that log messages go to stderr. | Test that log messages go to stderr.
| Python | isc | whilp/python-script,whilp/python-script | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = s... | Test that log messages go to stderr. | ## Code Before:
import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(... |
bc6001d6c25bdb5d83830e5a65fe5aea9fc1eb99 | ume/cmd.py | ume/cmd.py | import logging as l
import argparse
from ume.utils import (
save_mat,
dynamic_load,
)
def parse_args():
p = argparse.ArgumentParser(
description='CLI interface UME')
p.add_argument('--config', dest='inifile', default='config.ini')
subparsers = p.add_subparsers(
dest='subparser_na... | import logging as l
import argparse
import os
from ume.utils import (
save_mat,
dynamic_load,
)
def parse_args():
p = argparse.ArgumentParser(
description='CLI interface UME')
p.add_argument('--config', dest='inifile', default='config.ini')
subparsers = p.add_subparsers(
dest='su... | Add init function to create directories | Add init function to create directories
| Python | mit | smly/ume,smly/ume,smly/ume,smly/ume | import logging as l
import argparse
+ import os
from ume.utils import (
save_mat,
dynamic_load,
)
def parse_args():
p = argparse.ArgumentParser(
description='CLI interface UME')
p.add_argument('--config', dest='inifile', default='config.ini')
subparsers = p.... | Add init function to create directories | ## Code Before:
import logging as l
import argparse
from ume.utils import (
save_mat,
dynamic_load,
)
def parse_args():
p = argparse.ArgumentParser(
description='CLI interface UME')
p.add_argument('--config', dest='inifile', default='config.ini')
subparsers = p.add_subparsers(
de... |
1b75fe13249eba8d951735ad422dc512b1e28caf | test/test_all_stores.py | test/test_all_stores.py | import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
| import os
import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
def test_creates_required_dirs(self):
for d in groundstation.store.git_store.GitStore.required_dirs:
path = os.path.join(self.pat... | Add testcase for database initialization | Add testcase for database initialization
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | + import os
+
import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
+ def test_creates_required_dirs(self):
+ for d in groundstation.store.git_store.GitStore.required_dirs:
+ path... | Add testcase for database initialization | ## Code Before:
import store_fixture
import groundstation.store
class TestGitStore(store_fixture.StoreTestCase):
storeClass = groundstation.store.git_store.GitStore
## Instruction:
Add testcase for database initialization
## Code After:
import os
import store_fixture
import groundstation.store
class TestGitSt... |
2f9a4029e909f71539f3b7326b867e27386c3378 | tests/interface_test.py | tests/interface_test.py | import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotImplementedError, tr.get... | import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotImplementedError, tr.get... | Add missing tests for interfaces | Add missing tests for interfaces
| Python | bsd-2-clause | MetaMemoryT/aiozmq,claws/aiozmq,asteven/aiozmq,aio-libs/aiozmq | import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotIm... | Add missing tests for interfaces | ## Code Before:
import unittest
import aiozmq
class ZmqTransportTests(unittest.TestCase):
def test_interface(self):
tr = aiozmq.ZmqTransport()
self.assertRaises(NotImplementedError, tr.write, [b'data'])
self.assertRaises(NotImplementedError, tr.abort)
self.assertRaises(NotImplemen... |
5b3d26b6c9256f869d3bc08dfa00bf9b8de58f85 | tests/test_cli_parse.py | tests/test_cli_parse.py |
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.TemporaryDirectory()... |
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.NamedTemporaryFile()... | Change from TemporaryDirectory to NamedTemporaryFile | Change from TemporaryDirectory to NamedTemporaryFile
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels |
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
- with... | Change from TemporaryDirectory to NamedTemporaryFile | ## Code Before:
import os
import pytest
import tempfile
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
@pytest.mark.parametrize('prefix', ['silicon', 'bi'])
def test_cli_parse(models_equal, prefix):
runner = CliRunner()
with tempfile.Temp... |
62cee7d5a625bb3515eddaddbe940239a41ba31c | rest_framework_msgpack/parsers.py | rest_framework_msgpack/parsers.py | import decimal
import msgpack
from dateutil.parser import parse
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in obj:
decode_func = getattr(self, 'decode_%s' % obj['__clas... | import decimal
import msgpack
from dateutil.parser import parse
from django.utils.six import text_type
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in obj:
decode_func =... | Use six.text_type for python3 compat | Use six.text_type for python3 compat | Python | bsd-3-clause | juanriaza/django-rest-framework-msgpack | import decimal
import msgpack
from dateutil.parser import parse
+ from django.utils.six import text_type
+
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in ob... | Use six.text_type for python3 compat | ## Code Before:
import decimal
import msgpack
from dateutil.parser import parse
from rest_framework.parsers import BaseParser
from rest_framework.exceptions import ParseError
class MessagePackDecoder(object):
def decode(self, obj):
if '__class__' in obj:
decode_func = getattr(self, 'decode_%... |
19bae697bc6e017a97eef77d1425d1ccfbe27ff6 | vprof/__main__.py | vprof/__main__.py | """Visual profiler for Python."""
import argparse
import functools
import json
import profile
import stats_server
import subprocess
import sys
_MODULE_DESC = 'Python visual profiler.'
_HOST = 'localhost'
_PORT = 8000
def main():
parser = argparse.ArgumentParser(description=_MODULE_DESC)
parser.add_argument('... | """Visual profiler for Python."""
import argparse
import functools
import json
import profile
import stats_server
import subprocess
import sys
_MODULE_DESC = 'Python visual profiler.'
_HOST = 'localhost'
_PORT = 8000
_PROFILE_MAP = {
'c': profile.CProfile
}
def main():
parser = argparse.ArgumentParser(descri... | Add profilers selection as CLI option. | Add profilers selection as CLI option.
| Python | bsd-2-clause | nvdv/vprof,nvdv/vprof,nvdv/vprof | """Visual profiler for Python."""
import argparse
import functools
import json
import profile
import stats_server
import subprocess
import sys
_MODULE_DESC = 'Python visual profiler.'
_HOST = 'localhost'
_PORT = 8000
+ _PROFILE_MAP = {
+ 'c': profile.CProfile
+ }
def main():
p... | Add profilers selection as CLI option. | ## Code Before:
"""Visual profiler for Python."""
import argparse
import functools
import json
import profile
import stats_server
import subprocess
import sys
_MODULE_DESC = 'Python visual profiler.'
_HOST = 'localhost'
_PORT = 8000
def main():
parser = argparse.ArgumentParser(description=_MODULE_DESC)
parse... |
5e7cce09a6e6a847dad1714973fddb53d60c4c3f | yawf_sample/simple/models.py | yawf_sample/simple/models.py | from django.db import models
import reversion
from yawf.revision import RevisionModelMixin
class WINDOW_OPEN_STATUS:
MINIMIZED = 'minimized'
MAXIMIZED = 'maximized'
NORMAL = 'normal'
types = (MINIMIZED, MAXIMIZED, NORMAL)
choices = zip(types, types)
@reversion.register
class Window(RevisionMo... | from django.db import models
import reversion
from yawf.revision import RevisionModelMixin
class WINDOW_OPEN_STATUS:
MINIMIZED = 'minimized'
MAXIMIZED = 'maximized'
NORMAL = 'normal'
types = (MINIMIZED, MAXIMIZED, NORMAL)
choices = zip(types, types)
class Window(RevisionModelMixin, models.Mod... | Fix reversion register in sample app | Fix reversion register in sample app
| Python | mit | freevoid/yawf | from django.db import models
import reversion
from yawf.revision import RevisionModelMixin
class WINDOW_OPEN_STATUS:
MINIMIZED = 'minimized'
MAXIMIZED = 'maximized'
NORMAL = 'normal'
types = (MINIMIZED, MAXIMIZED, NORMAL)
choices = zip(types, types)
- @reversio... | Fix reversion register in sample app | ## Code Before:
from django.db import models
import reversion
from yawf.revision import RevisionModelMixin
class WINDOW_OPEN_STATUS:
MINIMIZED = 'minimized'
MAXIMIZED = 'maximized'
NORMAL = 'normal'
types = (MINIMIZED, MAXIMIZED, NORMAL)
choices = zip(types, types)
@reversion.register
class W... |
d15f6df74b8fe188a7a80c3491aeec62c35ce415 | policy.py | policy.py | from __future__ import unicode_literals
class PolicyError(RuntimeError):
def __init__(self, message, url):
self.message = message
self.url = url
def __str__(self):
return "{}: {}".format(self.message, self.url)
class RedirectLimitPolicy(object):
def __init__(self, max_redirects):... | from __future__ import unicode_literals
class PolicyError(RuntimeError):
def __init__(self, message, url):
self.message = message
self.url = url
def __str__(self):
return "{}: {}".format(self.message, self.url)
class RedirectLimitPolicy(object):
def __init__(self, max_redirects):... | Check for the first part of the version string | Check for the first part of the version string
Older CentOS Linux images only used the xxxx part of the full xxxx.yy
version string from Atlas.
| Python | mit | lpancescu/atlas-lint | from __future__ import unicode_literals
class PolicyError(RuntimeError):
def __init__(self, message, url):
self.message = message
self.url = url
def __str__(self):
return "{}: {}".format(self.message, self.url)
class RedirectLimitPolicy(object):
def __in... | Check for the first part of the version string | ## Code Before:
from __future__ import unicode_literals
class PolicyError(RuntimeError):
def __init__(self, message, url):
self.message = message
self.url = url
def __str__(self):
return "{}: {}".format(self.message, self.url)
class RedirectLimitPolicy(object):
def __init__(self,... |
2965891b46e89e0d7222ec16a2327f2bdef86f52 | chemex/util.py | chemex/util.py | """The util module contains a variety of utility functions."""
import configparser
import sys
def read_cfg_file(filename):
"""Read and parse the experiment configuration file with configparser."""
config = configparser.ConfigParser(inline_comment_prefixes=("#", ";"))
config.optionxform = str
try:
... | """The util module contains a variety of utility functions."""
import configparser
import sys
def listfloat(text):
return [float(val) for val in text.strip("[]").split(",")]
def read_cfg_file(filename=None):
"""Read and parse the experiment configuration file with configparser."""
config = configparser... | Update settings for reading config files | Update settings for reading config files
Update the definition of comments, now only allowing the use of "#"
for comments. Add a converter function to parse list of floats,
such as:
list_of_floats = [1.0, 2.0, 3.0]
| Python | bsd-3-clause | gbouvignies/chemex | """The util module contains a variety of utility functions."""
import configparser
import sys
+ def listfloat(text):
+ return [float(val) for val in text.strip("[]").split(",")]
+
+
- def read_cfg_file(filename):
+ def read_cfg_file(filename=None):
"""Read and parse the experiment configuration ... | Update settings for reading config files | ## Code Before:
"""The util module contains a variety of utility functions."""
import configparser
import sys
def read_cfg_file(filename):
"""Read and parse the experiment configuration file with configparser."""
config = configparser.ConfigParser(inline_comment_prefixes=("#", ";"))
config.optionxform = ... |
b6e9e37350a4b435df00a54b2ccd9da70a4db788 | nogotofail/mitm/util/ip.py | nogotofail/mitm/util/ip.py | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | Fix local interface addr parsing | Fix local interface addr parsing
On Fedora 21 the format of ifconfig is a little different.
Fixes #17
| Python | apache-2.0 | google/nogotofail,leasual/nogotofail,mkenne11/nogotofail,joshcooper/nogotofail,digideskio/nogotofail,mkenne11/nogotofail-pii,joshcooper/nogotofail,google/nogotofail,mkenne11/nogotofail,digideskio/nogotofail,leasual/nogotofail,mkenne11/nogotofail-pii | r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicabl... | Fix local interface addr parsing | ## Code Before:
r'''
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
91f5db6ddf6e26cec27917109689c200498dc85f | statsmodels/formula/try_formula.py | statsmodels/formula/try_formula.py | import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHI... | import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "PERBLACK", "PERHI... | Add example for injecting user transform | ENH: Add example for injecting user transform
| Python | bsd-3-clause | bert9bert/statsmodels,YihaoLu/statsmodels,cbmoore/statsmodels,hlin117/statsmodels,bavardage/statsmodels,detrout/debian-statsmodels,hainm/statsmodels,statsmodels/statsmodels,jstoxrocky/statsmodels,statsmodels/statsmodels,astocko/statsmodels,DonBeo/statsmodels,bzero/statsmodels,Averroes/statsmodels,gef756/statsmodels,jos... | import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", ... | Add example for injecting user transform | ## Code Before:
import statsmodels.api as sm
import numpy as np
star98 = sm.datasets.star98.load_pandas().data
formula = 'SUCCESS ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '
formula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'
dta = star98[["NABOVE", "NBELOW", "LOWINC", "PERASIAN", "P... |
5e7c99844a0687125e34104cf2c7ee87ca69c0de | mopidy_soundcloud/__init__.py | mopidy_soundcloud/__init__.py | import os
from mopidy import config, ext
from mopidy.exceptions import ExtensionError
__version__ = "2.1.0"
class Extension(ext.Extension):
dist_name = "Mopidy-SoundCloud"
ext_name = "soundcloud"
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(_... | import pathlib
from mopidy import config, ext
from mopidy.exceptions import ExtensionError
__version__ = "2.1.0"
class Extension(ext.Extension):
dist_name = "Mopidy-SoundCloud"
ext_name = "soundcloud"
version = __version__
def get_default_config(self):
return config.read(pathlib.Path(__fil... | Use pathlib to read ext.conf | Use pathlib to read ext.conf
| Python | mit | mopidy/mopidy-soundcloud | - import os
+ import pathlib
from mopidy import config, ext
from mopidy.exceptions import ExtensionError
__version__ = "2.1.0"
class Extension(ext.Extension):
dist_name = "Mopidy-SoundCloud"
ext_name = "soundcloud"
version = __version__
def get_default_config(self):
+ ... | Use pathlib to read ext.conf | ## Code Before:
import os
from mopidy import config, ext
from mopidy.exceptions import ExtensionError
__version__ = "2.1.0"
class Extension(ext.Extension):
dist_name = "Mopidy-SoundCloud"
ext_name = "soundcloud"
version = __version__
def get_default_config(self):
conf_file = os.path.join(o... |
94ec7d4816d2a243b8a2b0a0f2dc8a55a7347122 | tests/saltunittest.py | tests/saltunittest.py |
# Import python libs
import os
import sys
# support python < 2.7 via unittest2
if sys.version_info[0:2] < (2, 7):
try:
from unittest2 import TestLoader, TextTestRunner,\
TestCase, expectedFailure, \
TestSuite, skipIf
except ImportError:
... |
# Import python libs
import os
import sys
# support python < 2.7 via unittest2
if sys.version_info[0:2] < (2, 7):
try:
from unittest2 import TestLoader, TextTestRunner,\
TestCase, expectedFailure, \
TestSuite, skipIf
except ImportError:
... | Make an error go to stderr and remove net 1 LOC | Make an error go to stderr and remove net 1 LOC
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
# Import python libs
import os
import sys
# support python < 2.7 via unittest2
if sys.version_info[0:2] < (2, 7):
try:
from unittest2 import TestLoader, TextTestRunner,\
TestCase, expectedFailure, \
TestSuite, skipIf
e... | Make an error go to stderr and remove net 1 LOC | ## Code Before:
# Import python libs
import os
import sys
# support python < 2.7 via unittest2
if sys.version_info[0:2] < (2, 7):
try:
from unittest2 import TestLoader, TextTestRunner,\
TestCase, expectedFailure, \
TestSuite, skipIf
except Im... |
b6737b91938d527872eff1d645a205cacf94e15d | tests/test_gobject.py | tests/test_gobject.py |
import unittest
import gobject
import testhelper
class TestGObjectAPI(unittest.TestCase):
def testGObjectModule(self):
obj = gobject.GObject()
self.assertEquals(obj.__module__,
'gobject._gobject')
self.assertEquals(obj.__grefcount__, 1)
class TestFloating(unit... |
import unittest
import gobject
import testhelper
class TestGObjectAPI(unittest.TestCase):
def testGObjectModule(self):
obj = gobject.GObject()
self.assertEquals(obj.__module__,
'gobject._gobject')
class TestReferenceCounting(unittest.TestCase):
def testRegularObje... | Add a test to check for regular object reference count | Add a test to check for regular object reference count
https://bugzilla.gnome.org/show_bug.cgi?id=639949
| Python | lgpl-2.1 | alexef/pygobject,Distrotech/pygobject,davidmalcolm/pygobject,davibe/pygobject,jdahlin/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,choeger/pygobject-cmake,davidmalcolm/pygobject,davibe/pygobject,pexip/pygobject,Distrotech/pygobject,alexef/pygobject,sfeltman/pygobject,jdahlin/pygobject,GNOME/pygobject,... |
import unittest
import gobject
import testhelper
class TestGObjectAPI(unittest.TestCase):
def testGObjectModule(self):
obj = gobject.GObject()
self.assertEquals(obj.__module__,
'gobject._gobject')
+
+
+ class TestReferenceCounting(unittest.Test... | Add a test to check for regular object reference count | ## Code Before:
import unittest
import gobject
import testhelper
class TestGObjectAPI(unittest.TestCase):
def testGObjectModule(self):
obj = gobject.GObject()
self.assertEquals(obj.__module__,
'gobject._gobject')
self.assertEquals(obj.__grefcount__, 1)
class T... |
5cf0b19d67a667d4e0d48a12f0ee94f3387cfa37 | tests/test_helpers.py | tests/test_helpers.py |
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.Exp... |
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
with testtools.Exp... | Add test to ensure talons.helpers.import_function returns a callable | Add test to ensure talons.helpers.import_function returns a callable
| Python | apache-2.0 | talons/talons,jaypipes/talons |
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(sel... | Add test to ensure talons.helpers.import_function returns a callable | ## Code Before:
import testtools
from talons import helpers
from tests import base
class TestHelpers(base.TestCase):
def test_bad_import(self):
with testtools.ExpectedException(ImportError):
helpers.import_function('not.exist.function')
def test_no_function_in_module(self):
wi... |
73dfb1fc4ff62705f37b1128e0684e88be416d8f | src/webmention/models.py | src/webmention/models.py | from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models.DateTimeField(auto_... | from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models.DateTimeField(auto_... | Update deprecated allow_tags to format_html | Update deprecated allow_tags to format_html
| Python | mit | easy-as-python/django-webmention | from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models... | Update deprecated allow_tags to format_html | ## Code Before:
from django.db import models
class WebMentionResponse(models.Model):
response_body = models.TextField()
response_to = models.URLField()
source = models.URLField()
reviewed = models.BooleanField(default=False)
current = models.BooleanField(default=True)
date_created = models.Dat... |
e612a742caeedf5398522365c984a39c505e7872 | warehouse/exceptions.py | warehouse/exceptions.py | class FailedSynchronization(Exception):
pass
class SynchronizationTimeout(Exception):
"""
A synchronization for a particular project took longer than the timeout.
"""
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
class FailedSynchronization(Exception):
pass
class SynchronizationTimeout(Exception):
"""
A synchronization for a particular project took longer than the timeout.
"""
| Add the standard __future__ imports | Add the standard __future__ imports
| Python | bsd-2-clause | davidfischer/warehouse | + from __future__ import absolute_import
+ from __future__ import division
+ from __future__ import unicode_literals
+
+
class FailedSynchronization(Exception):
pass
class SynchronizationTimeout(Exception):
"""
A synchronization for a particular project took longer than the timeout.
... | Add the standard __future__ imports | ## Code Before:
class FailedSynchronization(Exception):
pass
class SynchronizationTimeout(Exception):
"""
A synchronization for a particular project took longer than the timeout.
"""
## Instruction:
Add the standard __future__ imports
## Code After:
from __future__ import absolute_import
from __futur... |
34c427200c6ab50fb64fa0d6116366a8fa9186a3 | netman/core/objects/bond.py | netman/core/objects/bond.py |
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
| import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = ... | Support deprecated use of the interface property of Bond. | Support deprecated use of the interface property of Bond.
| Python | apache-2.0 | idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman | + import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
... | Support deprecated use of the interface property of Bond. | ## Code Before:
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = ... |
ab06e871a6c820845da2d4d60bb6b1874350cf16 | circuits/web/__init__.py | circuits/web/__init__.py |
from loggers import Logger
from core import Controller
from sessions import Sessions
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC
try:
from dispatchers import... |
from utils import url
from loggers import Logger
from sessions import Sessions
from core import expose, Controller
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC
tr... | Add url and expose to this namesapce | circuits.web: Add url and expose to this namesapce
| Python | mit | eriol/circuits,eriol/circuits,nizox/circuits,treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits |
+ from utils import url
from loggers import Logger
- from core import Controller
from sessions import Sessions
+ from core import expose, Controller
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers imp... | Add url and expose to this namesapce | ## Code Before:
from loggers import Logger
from core import Controller
from sessions import Sessions
from events import Request, Response
from servers import BaseServer, Server
from errors import HTTPError, Forbidden, NotFound, Redirect
from dispatchers import Static, Dispatcher, VirtualHosts, XMLRPC
try:
from di... |
3ddad0538430499182c583a0a7f877884038c0a5 | Lib/test/test_symtable.py | Lib/test/test_symtable.py | from test.test_support import vereq, TestFailed
import symtable
symbols = symtable.symtable("def f(x): return x", "?", "exec")
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global")
##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), ... | from test import test_support
import symtable
import unittest
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global")
##vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1)
### Bug tickler: SyntaxError file name correct whether error ... | Use unittest and make sure a few other cases don't crash | Use unittest and make sure a few other cases don't crash
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | - from test.test_support import vereq, TestFailed
+ from test import test_support
import symtable
+ import unittest
- symbols = symtable.symtable("def f(x): return x", "?", "exec")
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global... | Use unittest and make sure a few other cases don't crash | ## Code Before:
from test.test_support import vereq, TestFailed
import symtable
symbols = symtable.symtable("def f(x): return x", "?", "exec")
## XXX
## Test disabled because symtable module needs to be rewritten for new compiler
##vereq(symbols[0].name, "global")
##vereq(len([ste for ste in symbols.values() if ste... |
f559001d2c46fade2d9b62f9cb7a3f8053e8b80f | OMDB_api_scrape.py | OMDB_api_scrape.py |
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
# Craft the... |
import requests, sys, os
import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit(1)
... | Convert OMDB scrapper to grab xml | Convert OMDB scrapper to grab xml
| Python | mit | samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia |
- import json, requests, sys, os
+ import requests, sys, os
+ import lxml.etree
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usag... | Convert OMDB scrapper to grab xml | ## Code Before:
import json, requests, sys, os
URL_BASE = 'http://www.omdbapi.com/?'
if len(sys.argv) > 1:
# Get address from command line.
mTitle = '+'.join(sys.argv[1:-1])
mYear = sys.argv[-1]
print(mTitle)
print(mYear)
else:
print("Usage: OMDB_api_scrape.py <Movie Title> <Year>")
sys.exit... |
8ac20f5bec2d94e71b92e48568d18fd74be4e5d4 | fabfile.py | fabfile.py | from fabric.api import task, local
@task
def up():
"""
Deploy new release to pypi. Using twine util
"""
local("rm -rf dist")
local("rm -rf pgup.egg-info")
local("python ./setup.py sdist")
local("twine upload dist/{}".format(local("ls dist", capture=True).strip()))
@task
def docs():
... | from fabric.api import task, local, execute
@task
def up():
"""
Deploy new release to pypi. Using twine util
"""
local("rm -rf dist")
local("rm -rf pgup.egg-info")
local("python ./setup.py sdist")
local("twine upload dist/{}".format(local("ls dist", capture=True).strip()))
execute(s... | Add fab task for syncing pgup with mezzo | Add fab task for syncing pgup with mezzo
| Python | mit | stepan-perlov/pgup | - from fabric.api import task, local
+ from fabric.api import task, local, execute
@task
def up():
"""
Deploy new release to pypi. Using twine util
"""
local("rm -rf dist")
local("rm -rf pgup.egg-info")
local("python ./setup.py sdist")
local("twine upload dist/{}".fo... | Add fab task for syncing pgup with mezzo | ## Code Before:
from fabric.api import task, local
@task
def up():
"""
Deploy new release to pypi. Using twine util
"""
local("rm -rf dist")
local("rm -rf pgup.egg-info")
local("python ./setup.py sdist")
local("twine upload dist/{}".format(local("ls dist", capture=True).strip()))
@task... |
c3c26c15895a192fba22482306182950c0ccd57c | python/simple-linked-list/simple_linked_list.py | python/simple-linked-list/simple_linked_list.py | class Node(object):
def __init__(self, value):
pass
def value(self):
pass
def next(self):
pass
class LinkedList(object):
def __init__(self, values=[]):
self.size = 0
for value in values:
self.push(value)
def __len__(self):
return self.... | class Node(object):
def __init__(self, value):
pass
def value(self):
pass
def next(self):
pass
class LinkedList(object):
def __init__(self, values=[]):
self._size = 0
self._head = None
for value in values:
self.push(value)
def __len__... | Mark instance variables private with leading _ | Mark instance variables private with leading _
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism | class Node(object):
def __init__(self, value):
pass
def value(self):
pass
def next(self):
pass
class LinkedList(object):
def __init__(self, values=[]):
- self.size = 0
+ self._size = 0
+ self._head = None
+
for valu... | Mark instance variables private with leading _ | ## Code Before:
class Node(object):
def __init__(self, value):
pass
def value(self):
pass
def next(self):
pass
class LinkedList(object):
def __init__(self, values=[]):
self.size = 0
for value in values:
self.push(value)
def __len__(self):
... |
fa609681c2732e655cde9075182af918983ccc1f | photutils/utils/_misc.py | photutils/utils/_misc.py | from datetime import datetime, timezone
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils and
its dependencies.
"""
... | from datetime import datetime, timezone
import sys
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils and
its dependencies... | Add all optional dependencies to version info dict | Add all optional dependencies to version info dict
| Python | bsd-3-clause | larrybradley/photutils,astropy/photutils | from datetime import datetime, timezone
+ import sys
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils an... | Add all optional dependencies to version info dict | ## Code Before:
from datetime import datetime, timezone
def _get_version_info():
"""
Return a dictionary of the installed version numbers for photutils
and its dependencies.
Returns
-------
result : dict
A dictionary containing the version numbers for photutils and
its depende... |
a346eb2b19f3a0b72dc6565e9d0c4fabf3c5784a | migrations/versions/0014_add_template_version.py | migrations/versions/0014_add_template_version.py |
# revision identifiers, used by Alembic.
revision = '0014_add_template_version'
down_revision = '0013_add_loadtest_client'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True))
... |
# revision identifiers, used by Alembic.
revision = '0014_add_template_version'
down_revision = '0013_add_loadtest_client'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.add_column('jobs', sa.Column('template_version', sa.Integer(), nullable=True))
... | Add a update query to fix templates_history where the created_by_id is missing. | Add a update query to fix templates_history where the created_by_id is missing.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
# revision identifiers, used by Alembic.
revision = '0014_add_template_version'
down_revision = '0013_add_loadtest_client'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.add_column('jobs', sa.Column('template_version', sa.Integer(... | Add a update query to fix templates_history where the created_by_id is missing. | ## Code Before:
# revision identifiers, used by Alembic.
revision = '0014_add_template_version'
down_revision = '0013_add_loadtest_client'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
op.add_column('jobs', sa.Column('template_version', sa.Integer(), nul... |
df000e724ce1f307a478fcf4790404183df13610 | _setup_database.py | _setup_database.py |
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=True)
|
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
... | Include player data migration in setup | Include player data migration in setup
| Python | mit | leaffan/pynhldb |
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
+ from setup.create_players import migrate_players
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division c... | Include player data migration in setup | ## Code Before:
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
if __name__ == '__main__':
# migrating teams from json file to database
migrate_teams(simulation=True)
# creating divisions from division configuration file
create_divisions(simulation=Tru... |
c0d9a94899af84e8a075cfc7cfb054a934470e3a | static_precompiler/tests/test_templatetags.py | static_precompiler/tests/test_templatetags.py | import django.template
import django.template.loader
import pretend
def test_compile_filter(monkeypatch):
compile_static = pretend.call_recorder(lambda source_path: "compiled")
monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static)
template = django.template.loader.get_template_fr... | import django.template
import pretend
def test_compile_filter(monkeypatch):
compile_static = pretend.call_recorder(lambda source_path: "compiled")
monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static)
template = django.template.Template("""{% load compile_static %}{{ "source"|com... | Fix tests for Django 1.8 | Fix tests for Django 1.8
| Python | mit | liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler,jaheba/django-static-precompiler | import django.template
- import django.template.loader
import pretend
def test_compile_filter(monkeypatch):
compile_static = pretend.call_recorder(lambda source_path: "compiled")
monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static)
- template = django.template.lo... | Fix tests for Django 1.8 | ## Code Before:
import django.template
import django.template.loader
import pretend
def test_compile_filter(monkeypatch):
compile_static = pretend.call_recorder(lambda source_path: "compiled")
monkeypatch.setattr("static_precompiler.utils.compile_static", compile_static)
template = django.template.loader... |
eaa4de2ecbcf29c9e56ebf2fa69099055e469fbc | tests/test_conversion.py | tests/test_conversion.py | from asciisciit import conversions as conv
import numpy as np
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.apply_lut_pil(img... | import itertools
from asciisciit import conversions as conv
import numpy as np
import pytest
@pytest.mark.parametrize("invert,equalize,lut,lookup_func",
itertools.product((True, False),
(True, False),
("simp... | Add tests to minimally exercise basic conversion functionality | Add tests to minimally exercise basic conversion functionality
| Python | mit | derricw/asciisciit | + import itertools
from asciisciit import conversions as conv
import numpy as np
+ import pytest
+
+
+ @pytest.mark.parametrize("invert,equalize,lut,lookup_func",
+ itertools.product((True, False),
+ (True, False),
+ ... | Add tests to minimally exercise basic conversion functionality | ## Code Before:
from asciisciit import conversions as conv
import numpy as np
def test_lookup_method_equivalency():
img = np.random.randint(0, 255, (300,300), dtype=np.uint8)
pil_ascii = conv.apply_lut_pil(img)
np_ascii = conv.apply_lut_numpy(img)
assert(pil_ascii == np_ascii)
pil_ascii = conv.a... |
a0420b066e0a5064ebe0944a16348debf107a9a4 | speech.py | speech.py |
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
say("Computer Science is one of the coolest subjects to study in the\
modern world.", tts)
say("Programming is a tool used by Scie... |
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
say("I'm Leyva and I will teach you how to program in a programming\
language called python", tts)
say("Computer Science is one of... | Make Nao say its name and the programming language | Make Nao say its name and the programming language
| Python | mit | AliGhahraei/nao-classroom |
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
+ say("I'm Leyva and I will teach you how to program in a programming\
+ language called python", tts)
s... | Make Nao say its name and the programming language | ## Code Before:
import time
from say import say
def introduction(tts):
"""Make Nao introduce itself.
Keyword arguments:
tts - Nao proxy.
"""
say("Hello world!", tts)
say("Computer Science is one of the coolest subjects to study in the\
modern world.", tts)
say("Programming is a t... |
40122e169e6a887caa6371a0ff3029c35ce265d5 | third_party/node/node.py | third_party/node/node.py |
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', 'node'),
'Wind... |
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', 'node'),
'Wind... | Fix line ending printing on Python 3 | Fix line ending printing on Python 3
To reflect the changes in
https://chromium-review.googlesource.com/c/chromium/src/+/2896248/8/third_party/node/node.py
R=993fcadce4d04090da2fefd557a0995e7966c8d5@chromium.org
Bug: none
Change-Id: I25ba29042f537bfef57fba93115be2c194649864
Reviewed-on: https://chromium-review.googl... | Python | bsd-3-clause | ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend,ChromeDevTools/devtools-frontend |
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', ... | Fix line ending printing on Python 3 | ## Code Before:
from os import path as os_path
import platform
import subprocess
import sys
import os
def GetBinaryPath():
return os_path.join(
os_path.dirname(__file__), *{
'Darwin': ('mac', 'node-darwin-x64', 'bin', 'node'),
'Linux': ('linux', 'node-linux-x64', 'bin', 'node'),
... |
91b0bcad27f12c29681235079960ee272275e0bd | src/main/python/dlfa/solvers/__init__.py | src/main/python/dlfa/solvers/__init__.py | from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
concrete_solvers = { # pylint: disable=invalid-name
'LSTMSolver': LSTMSolver,
'... | from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver
concrete_solvers =... | Add MCMemoryNetwork as a usable solver | Add MCMemoryNetwork as a usable solver
| Python | apache-2.0 | allenai/deep_qa,matt-gardner/deep_qa,DeNeutoy/deep_qa,allenai/deep_qa,DeNeutoy/deep_qa,matt-gardner/deep_qa | from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
+ from .multiple_choice_memory_network import MultipleChoiceMemoryNetworkSolver
co... | Add MCMemoryNetwork as a usable solver | ## Code Before:
from .nn_solver import NNSolver
from .lstm_solver import LSTMSolver
from .tree_lstm_solver import TreeLSTMSolver
from .memory_network import MemoryNetworkSolver
from .differentiable_search import DifferentiableSearchSolver
concrete_solvers = { # pylint: disable=invalid-name
'LSTMSolver': LSTMS... |
68e51fd9772aaf4bd382ffe05721e27da6bddde6 | argus/exceptions.py | argus/exceptions.py | """Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusError):
pass
class ArgusEnvironmentE... | """Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusError):
pass
class ArgusEnvironmentE... | Add exception for Logic Errors | Add exception for Logic Errors
| Python | apache-2.0 | stefan-caraiman/cloudbase-init-ci,cloudbase/cloudbase-init-ci,micumatei/cloudbase-init-ci | """Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusEr... | Add exception for Logic Errors | ## Code Before:
"""Various exceptions that can be raised by the CI project."""
class ArgusError(Exception):
pass
class ArgusTimeoutError(ArgusError):
pass
class ArgusCLIError(ArgusError):
pass
class ArgusPermissionDenied(ArgusError):
pass
class ArgusHeatTeardown(ArgusError):
pass
class A... |
2eb4fcb2d75e6f93f33b1ae41098919f6d4ebc92 | neovim/__init__.py | neovim/__init__.py | from client import Client
from uv_stream import UvStream
__all__ = ['Client', 'UvStream', 'c']
| from client import Client
from uv_stream import UvStream
__all__ = ['connect']
def connect(address, port=None):
client = Client(UvStream(address, port))
client.discover_api()
return client.vim
| Add helper function for connecting with Neovim | Add helper function for connecting with Neovim
| Python | apache-2.0 | fwalch/python-client,Shougo/python-client,bfredl/python-client,brcolow/python-client,starcraftman/python-client,traverseda/python-client,justinmk/python-client,neovim/python-client,meitham/python-client,meitham/python-client,0x90sled/python-client,justinmk/python-client,zchee/python-client,traverseda/python-client,bfre... | from client import Client
from uv_stream import UvStream
- __all__ = ['Client', 'UvStream', 'c']
+ __all__ = ['connect']
+ def connect(address, port=None):
+ client = Client(UvStream(address, port))
+ client.discover_api()
+ return client.vim
+ | Add helper function for connecting with Neovim | ## Code Before:
from client import Client
from uv_stream import UvStream
__all__ = ['Client', 'UvStream', 'c']
## Instruction:
Add helper function for connecting with Neovim
## Code After:
from client import Client
from uv_stream import UvStream
__all__ = ['connect']
def connect(address, port=None):
client = Cl... |
f71897270d9a040930bfb41801bf955ea3d0a36e | slave/skia_slave_scripts/android_run_gm.py | slave/skia_slave_scripts/android_run_gm.py |
""" Run GM on an Android device. """
from android_build_step import AndroidBuildStep
from build_step import BuildStep
from run_gm import RunGM
import sys
class AndroidRunGM(AndroidBuildStep, RunGM):
def _Run(self):
self._gm_args.append('--nopdf')
RunGM._Run(self)
if '__main__' == __name__:
sys.exit(Bu... |
""" Run GM on an Android device. """
from android_build_step import AndroidBuildStep
from build_step import BuildStep
from run_gm import RunGM
import sys
class AndroidRunGM(AndroidBuildStep, RunGM):
def __init__(self, timeout=9600, **kwargs):
super(AndroidRunGM, self).__init__(timeout=timeout, **kwargs)
de... | Increase timeout for GM on Android | Increase timeout for GM on Android
Unreviewed.
(SkipBuildbotRuns)
Review URL: https://codereview.chromium.org/18845002
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9906 2bbb7eff-a529-9590-31e7-b0007b416f81
| Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... |
""" Run GM on an Android device. """
from android_build_step import AndroidBuildStep
from build_step import BuildStep
from run_gm import RunGM
import sys
class AndroidRunGM(AndroidBuildStep, RunGM):
+ def __init__(self, timeout=9600, **kwargs):
+ super(AndroidRunGM, self).__init__(timeout=... | Increase timeout for GM on Android | ## Code Before:
""" Run GM on an Android device. """
from android_build_step import AndroidBuildStep
from build_step import BuildStep
from run_gm import RunGM
import sys
class AndroidRunGM(AndroidBuildStep, RunGM):
def _Run(self):
self._gm_args.append('--nopdf')
RunGM._Run(self)
if '__main__' == __name_... |
3e1033637d0bb5dd8856052ffd1667df0ccceb5d | entity.py | entity.py | from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and physically, as well as its behaviour.
Since it inherits from PyGame's Sprite class, it can be added to
any Groups y... | from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and physically, as well as its behaviour.
Since it inherits from PyGame's Sprite class, it can be added to
any Groups y... | Remove components as class attribute | Entity: Remove components as class attribute
It is meant to be an instance attribute and should be defined in
init() instead.
| Python | unlicense | MarquisLP/gamehappy | from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and physically, as well as its behaviour.
Since it inherits from PyGame's Sprite class, it can be added... | Remove components as class attribute | ## Code Before:
from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and physically, as well as its behaviour.
Since it inherits from PyGame's Sprite class, it can be added to
... |
368e2d6407cb021d80fe3679c65737581c3cc221 | bliski_publikator/institutions/serializers.py | bliski_publikator/institutions/serializers.py | from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
'url',... | from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
'url',... | Make user field read-only in InstitutionSerializer | Make user field read-only in InstitutionSerializer
| Python | mit | watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator,watchdogpolska/bliski_publikator | from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
... | Make user field read-only in InstitutionSerializer | ## Code Before:
from rest_framework import serializers
from .models import Institution
class InstitutionSerializer(serializers.HyperlinkedModelSerializer):
on_site = serializers.CharField(source='get_absolute_url', read_only=True)
class Meta:
model = Institution
fields = ('on_site',
... |
5cadfe1b0a8da0f46950ff63786bf79c42af9b90 | tutorials/forms.py | tutorials/forms.py | from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
fields = ('title', 'html', 'markdown') | from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
fields = ('category', 'title', 'markdown', 'level')
| Add new model fields to form | Add new model fields to form
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
- fields = ('title', 'html', 'markdown')
+ fields = ('category', 'title', 'markdown', 'level')
+ | Add new model fields to form | ## Code Before:
from django import forms
from .models import Tutorial
class TutorialForm(forms.ModelForm):
# ToDO: Set required fields??
class Meta:
model = Tutorial
fields = ('title', 'html', 'markdown')
## Instruction:
Add new model fields to form
## Code After:
from django import forms
fro... |
1abb838a1fa56af25b9c6369dff93c65e17fbc3a | manage.py | manage.py | import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
app.config.from_object(os.ge... | import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
app.config.from_object(os.ge... | Remove erase of coverage file as it's needed by coveralls | Remove erase of coverage file as it's needed by coveralls
| Python | apache-2.0 | atindale/business-glossary,atindale/business-glossary | import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
... | Remove erase of coverage file as it's needed by coveralls | ## Code Before:
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db
from config import BASE_DIR
app.config.f... |
1be8c268f2da618e9e9e13d55d53599d637d3a6a | abel/tests/test_tools.py | abel/tests/test_tools.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from numpy.testing import assert_allclose
from abel.tools import calculate_speeds
DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data')
def assert_equal(x, y, messa... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from abel.tools import calculate_speeds, center_image
DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data')
... | Test to enforce that center_image preserves shape | Test to enforce that center_image preserves shape
| Python | mit | rth/PyAbel,huletlab/PyAbel,DhrubajyotiDas/PyAbel,PyAbel/PyAbel,stggh/PyAbel | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
- from numpy.testing import assert_allclose
+ from numpy.testing import assert_allclose, assert_equal
- from abel.tools import calculate_speeds
+ from abel.to... | Test to enforce that center_image preserves shape | ## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import numpy as np
from numpy.testing import assert_allclose
from abel.tools import calculate_speeds
DATA_DIR = os.path.join(os.path.split(__file__)[0], 'data')
def assert_e... |
85a873c79e3c3c7289a23da6fe3673259fac9cbd | sympy/sets/conditionset.py | sympy/sets/conditionset.py | from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.logic.boolalg import And, Or, Not, true, false
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
FiniteSet)
from sympy.core.singleton import Singleton, S
from sympy.core.s... | from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.logic.boolalg import And, Or, Not, true, false
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
FiniteSet)
from sympy.core.singleton import Singleton, S
from sympy.core.s... | Remove redundant _is_multivariate in ConditionSet | Remove redundant _is_multivariate in ConditionSet
Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>
| Python | bsd-3-clause | sampadsaha5/sympy,VaibhavAgarwalVA/sympy,mcdaniel67/sympy,MechCoder/sympy,farhaanbukhsh/sympy,abhiii5459/sympy,MechCoder/sympy,madan96/sympy,kaushik94/sympy,jaimahajan1997/sympy,skidzo/sympy,ahhda/sympy,abhiii5459/sympy,mafiya69/sympy,Curious72/sympy,shikil/sympy,aktech/sympy,hargup/sympy,Vishluck/sympy,oliverlee/sympy... | from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.logic.boolalg import And, Or, Not, true, false
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
FiniteSet)
from sympy.core.singleton import Singleton, S
f... | Remove redundant _is_multivariate in ConditionSet | ## Code Before:
from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.logic.boolalg import And, Or, Not, true, false
from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union,
FiniteSet)
from sympy.core.singleton import Singleton, S
f... |
14c86e3c93bd5114b74c125fdb8213b22342c95c | tests/manual_cleanup.py | tests/manual_cleanup.py | from globus_cli.services.transfer import get_client as get_tc
from tests.framework.cli_testcase import default_test_config
try:
from mock import patch
except ImportError:
from unittest.mock import patch
def cleanup_bookmarks(tc):
for bm in tc.bookmark_list():
tc.delete_bookmark(bm['id'])
@patch... | import click
from globus_cli.services.transfer import get_client as get_tc
from tests.framework.cli_testcase import default_test_config
try:
from mock import patch
except ImportError:
from unittest.mock import patch
def cleanup_bookmarks(tc):
for bm in tc.bookmark_list():
tc.delete_bookmark(bm['... | Add `--cancel-jobs` to manual cleanup script | Add `--cancel-jobs` to manual cleanup script
Add an option to this script to cancel all ACTIVE,INACTIVE tasks (i.e.
not SUCCEDED,FAILED).
While this can disrupt a run of the tests pretty badly if you run it
while the tets are running, it's pretty much the only way to "fix it" if
the tests go off the rails because of a... | Python | apache-2.0 | globus/globus-cli,globus/globus-cli | + import click
+
from globus_cli.services.transfer import get_client as get_tc
from tests.framework.cli_testcase import default_test_config
try:
from mock import patch
except ImportError:
from unittest.mock import patch
def cleanup_bookmarks(tc):
for bm in tc.bookmark_list():
... | Add `--cancel-jobs` to manual cleanup script | ## Code Before:
from globus_cli.services.transfer import get_client as get_tc
from tests.framework.cli_testcase import default_test_config
try:
from mock import patch
except ImportError:
from unittest.mock import patch
def cleanup_bookmarks(tc):
for bm in tc.bookmark_list():
tc.delete_bookmark(bm... |
a3d087b2d7ec42eb5afe9f0064785d25500af11b | bitforge/errors.py | bitforge/errors.py |
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
self.message = self.__doc__.format(**self.__dict__)
def prepare(self):
pass
def __str__(self):
return self.message
class Obje... |
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
message = self.__doc__.format(**self.__dict__)
super(BitforgeError, self).__init__(message)
def prepare(self):
pass
def __str__... | Call super constructor for BitforgeError | Call super constructor for BitforgeError
| Python | mit | muun/bitforge,coinforge/bitforge |
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
- self.message = self.__doc__.format(**self.__dict__)
+ message = self.__doc__.format(**self.__dict__)
+ super(BitforgeError, s... | Call super constructor for BitforgeError | ## Code Before:
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
self.message = self.__doc__.format(**self.__dict__)
def prepare(self):
pass
def __str__(self):
return self.mess... |
c19a64ecdbde5a387a84dec880c2ebea1013c3d6 | canopus/auth/token_factory.py | canopus/auth/token_factory.py | from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
if user.last_signed_in is None:
user.wel... | from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
user.last_signed_in = datetime.now()
token ... | Include user in create_access_token return value | Include user in create_access_token return value
| Python | mit | josuemontano/api-starter,josuemontano/API-platform,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform | from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
- if user.last_signed_in is ... | Include user in create_access_token return value | ## Code Before:
from datetime import datetime, timedelta
from ..schema import UserSchema
class TokenFactory(object):
def __init__(self, request, user):
self.user = user
self.request = request
def create_access_token(self):
user = self.user
if user.last_signed_in is None:
... |
72f03f05adc39a3d920ee8372f4108b5c8c8671c | modules/pwnchecker.py | modules/pwnchecker.py |
import requests
import pprint
import argparse
parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend')
parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True)
args = parser.parse_args()
headers = {'User-agent': 'Hav... |
import requests
import pprint
import argparse
parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend')
parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True)
parser.add_argument('-k', '--api-key', help='Your HIBP AP... | Update to the v3 api | Update to the v3 api
| Python | bsd-3-clause | L1ghtn1ng/usaf,L1ghtn1ng/usaf |
import requests
import pprint
import argparse
parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend')
parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True)
+ parser.add_argument('-k', '--api-key', he... | Update to the v3 api | ## Code Before:
import requests
import pprint
import argparse
parser = argparse.ArgumentParser(description='A tool to check if your email account has been in a breach By Jay Townsend')
parser.add_argument('-e', '--email-account', help='Email account to lookup', required=True)
args = parser.parse_args()
headers = {'U... |
31a9b285a0445c895aeff02b2abbeda12bf7f3d7 | wagtail/admin/tests/pages/test_content_type_use_view.py | wagtail/admin/tests/pages/test_content_type_use_view.py | from django.test import TestCase
from django.urls import reverse
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
self.user = self.login()
def test_content_type_use(self):
# Get use of event ... | from django.test import TestCase
from django.urls import reverse
from django.utils.http import urlencode
from wagtail.tests.testapp.models import EventPage
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
... | Add test for button URLs including a 'next' parameter | Add test for button URLs including a 'next' parameter
| Python | bsd-3-clause | torchbox/wagtail,FlipperPA/wagtail,gasman/wagtail,gasman/wagtail,mixxorz/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,torchbox/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,mixxorz/wagtail,wagtail/wagtail,takeflight/wagtail,FlipperPA/wagtail,torchbox/wagtail,zerolab/wagtail,thenewguy/wagtail,t... | from django.test import TestCase
from django.urls import reverse
+ from django.utils.http import urlencode
+ from wagtail.tests.testapp.models import EventPage
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
... | Add test for button URLs including a 'next' parameter | ## Code Before:
from django.test import TestCase
from django.urls import reverse
from wagtail.tests.utils import WagtailTestUtils
class TestContentTypeUse(TestCase, WagtailTestUtils):
fixtures = ['test.json']
def setUp(self):
self.user = self.login()
def test_content_type_use(self):
# G... |
11fd3e5c8a2c7f591dff1ba1949508d178d1e5d5 | byceps/util/irc.py | byceps/util/irc.py |
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
DELAY_IN_SECONDS = 2
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List[str], text: str) -> None:
"""Write the text to the channels ... |
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
DEFAULT_DELAY_IN_SECONDS = 2
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List[str], text: str) -> None:
"""Write the text to the cha... | Make IRC message delay configurable | Make IRC message delay configurable
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
-
- DELAY_IN_SECONDS = 2
+ DEFAULT_DELAY_IN_SECONDS = 2
-
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List... | Make IRC message delay configurable | ## Code Before:
from time import sleep
from typing import List
from flask import current_app
import requests
DEFAULT_BOT_URL = 'http://127.0.0.1:12345/'
DEFAULT_ENABLED = False
DELAY_IN_SECONDS = 2
DEFAULT_TEXT_PREFIX = '[BYCEPS] '
def send_message(channels: List[str], text: str) -> None:
"""Write the text ... |
0c42909e5649b78260d9efa4e6ff7b77c82b1934 | runtests.py | runtests.py | import sys
from os.path import abspath
from os.path import dirname
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
from django.test.simple import DjangoTestSuiteRunner
def runtests():
parent_dir = dirname(abspath(__file__))
sys.path.insert(0... | import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
# Now, imports from Django will work properly without raising errors related to
# missing or badly-co... | Allow testing of specific apps. | Allow testing of specific apps.
| Python | mit | seler/djoauth2,seler/djoauth2,vden/djoauth2-ng,Locu/djoauth2,vden/djoauth2-ng,Locu/djoauth2 | import sys
+ from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
-
+ # Now, imports from Django will work properly without raising errors related to
... | Allow testing of specific apps. | ## Code Before:
import sys
from os.path import abspath
from os.path import dirname
# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings
from django.test.simple import DjangoTestSuiteRunner
def runtests():
parent_dir = dirname(abspath(__file__))
s... |
d9844f5bcf6d48bde1a60d32998ccdaa87e99676 | cloud_browser/__init__.py | cloud_browser/__init__.py |
VERSION = (0, 2, 1)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version__ + "".join(str(v) for v in VERSION)
|
VERSION = (0, 2, 1)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version__
| Fix __version_full__ for new scheme. | Version: Fix __version_full__ for new scheme.
| Python | mit | ryan-roemer/django-cloud-browser,UrbanDaddy/django-cloud-browser,UrbanDaddy/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser |
VERSION = (0, 2, 1)
__version__ = ".".join(str(v) for v in VERSION)
- __version_full__ = __version__ + "".join(str(v) for v in VERSION)
+ __version_full__ = __version__
| Fix __version_full__ for new scheme. | ## Code Before:
VERSION = (0, 2, 1)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version__ + "".join(str(v) for v in VERSION)
## Instruction:
Fix __version_full__ for new scheme.
## Code After:
VERSION = (0, 2, 1)
__version__ = ".".join(str(v) for v in VERSION)
__version_full__ = __version_... |
e9b3865e37c1f4a275c323dcbf778696a27d69bd | testapp/testapp/management.py | testapp/testapp/management.py | from bitcategory import models
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
@receiver(post_syncdb, sender=models)
def load_test_categories(sender, **kwargs):
r1, c = models.Category.objects.get_or_create(name="root1")
r2, c = models.Category.objects.get_or_create(name=... | from bitcategory import models
from django.dispatch import receiver
from django.db.models.signals import post_migrate
@receiver(post_migrate, sender=models)
def load_test_categories(sender, **kwargs):
r1, c = models.Category.objects.get_or_create(name="root1")
r2, c = models.Category.objects.get_or_create(nam... | Update tests to work under django 1.8+ | Update tests to work under django 1.8+
| Python | bsd-3-clause | atheiste/django-bit-category,atheiste/django-bit-category,atheiste/django-bit-category | from bitcategory import models
from django.dispatch import receiver
- from django.db.models.signals import post_syncdb
+ from django.db.models.signals import post_migrate
- @receiver(post_syncdb, sender=models)
+ @receiver(post_migrate, sender=models)
def load_test_categories(sender, **kwargs):
r1, c ... | Update tests to work under django 1.8+ | ## Code Before:
from bitcategory import models
from django.dispatch import receiver
from django.db.models.signals import post_syncdb
@receiver(post_syncdb, sender=models)
def load_test_categories(sender, **kwargs):
r1, c = models.Category.objects.get_or_create(name="root1")
r2, c = models.Category.objects.get... |
5749d976dee7d8a51e25842b528448a077a8f800 | report_compassion/models/ir_actions_report.py | report_compassion/models/ir_actions_report.py |
from odoo import models, api
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
@api.multi
def behaviour(self):
"""
Change behaviour to return user preference in priority.
:return: report action for printing.
"""
result = super().behaviour()
... |
from odoo import models, api
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
@api.multi
def behaviour(self):
"""
Change behaviour to return user preference in priority.
:return: report action for printing.
"""
result = super().behaviour()
... | FIX default behaviour of printing | FIX default behaviour of printing
| Python | agpl-3.0 | CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland |
from odoo import models, api
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
@api.multi
def behaviour(self):
"""
Change behaviour to return user preference in priority.
:return: report action for printing.
"""
res... | FIX default behaviour of printing | ## Code Before:
from odoo import models, api
class IrActionsReport(models.Model):
_inherit = "ir.actions.report"
@api.multi
def behaviour(self):
"""
Change behaviour to return user preference in priority.
:return: report action for printing.
"""
result = super().... |
a1a8ef302ac24d56a36d0671eb692943d14c4ddf | whats_open/website/urls.py | whats_open/website/urls.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Django Imports
from django.conf.urls import include, url
# App Imports
from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet
# Other Imports
from rest_framework.routers import DefaultRouter
... | from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Django Imports
from django.conf.urls import include, url
from django.views.generic.base import RedirectView
# App Imports
from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet
# Other Imports... | Add a redirect for / -> /api | refactor: Add a redirect for / -> /api
- This got really annoying in development to remember to go to /api all the time
- Potentially in the future we will build a test landing page on / to test that
the API works instead of having to rely on third party tools or just manual clicks
- Until then, this will make life e... | Python | apache-2.0 | srct/whats-open,srct/whats-open,srct/whats-open | from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Django Imports
from django.conf.urls import include, url
+ from django.views.generic.base import RedirectView
# App Imports
from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSe... | Add a redirect for / -> /api | ## Code Before:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
# Django Imports
from django.conf.urls import include, url
# App Imports
from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet
# Other Imports
from rest_framework.routers import... |
d3f4d43b36b8d21a3102389d53bf3f1af4e00d79 | st2common/st2common/runners/base_action.py | st2common/st2common/runners/base_action.py |
import abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = None
def __init__(self, config=None, action_service=None):
... |
import abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
__all__ = [
'Action'
]
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = None
def __init__(self, config=None... | Add _all__ to the module. | Add _all__ to the module.
| Python | apache-2.0 | StackStorm/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2 |
import abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
+
+ __all__ = [
+ 'Action'
+ ]
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = No... | Add _all__ to the module. | ## Code Before:
import abc
import six
from st2common.runners.utils import get_logger_for_python_runner_action
@six.add_metaclass(abc.ABCMeta)
class Action(object):
"""
Base action class other Python actions should inherit from.
"""
description = None
def __init__(self, config=None, action_ser... |
ee6c7caabdfcd0bddd9b92d05cddd8b6be7cbe10 | tests/functional/test_pip_runner_script.py | tests/functional/test_pip_runner_script.py | import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's no pip installed in the e... | import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's no pip installed in the e... | Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp | Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp
| Python | mit | pradyunsg/pip,pypa/pip,pfmoore/pip,pfmoore/pip,sbidoul/pip,pradyunsg/pip,sbidoul/pip,pypa/pip | import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's... | Fix test_runner_work_in_environments_with_no_pip to work under --use-zipapp | ## Code Before:
import os
from pathlib import Path
from pip import __version__
from tests.lib import PipTestEnvironment
def test_runner_work_in_environments_with_no_pip(
script: PipTestEnvironment, pip_src: Path
) -> None:
runner = pip_src / "src" / "pip" / "__pip-runner__.py"
# Ensure there's no pip in... |
0e835c6381374c5b00b7387057d056d679f635c4 | zproject/legacy_urls.py | zproject/legacy_urls.py | from django.conf.urls import url
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These are json format views used by the web client. They r... | from django.urls import path
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These are json format views used by the web client. They requi... | Migrate legacy urls to use modern django pattern. | urls: Migrate legacy urls to use modern django pattern.
| Python | apache-2.0 | shubhamdhama/zulip,punchagan/zulip,kou/zulip,showell/zulip,hackerkid/zulip,timabbott/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,zulip/zulip,synicalsyntax/zulip,zulip/zulip,andersk/zulip,shubhamdhama/zulip,showell/zulip,kou/zulip,hackerkid/zulip,shubhamdhama/zulip,andersk/zulip,eeshangarg/zulip,brainwane/zulip,shubh... | - from django.conf.urls import url
+ from django.urls import path
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These ... | Migrate legacy urls to use modern django pattern. | ## Code Before:
from django.conf.urls import url
import zerver.views
import zerver.views.streams
import zerver.views.auth
import zerver.views.tutorial
import zerver.views.report
# Future endpoints should add to urls.py, which includes these legacy urls
legacy_urls = [
# These are json format views used by the web... |
5b9f0270aaa53a562ca65fa74769885621da4a8e | website/addons/s3/__init__.py | website/addons/s3/__init__.py | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Am... | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'
FULL_NAME = 'Am... | Change S3 full name to Amazon S3 | Change S3 full name to Amazon S3
| Python | apache-2.0 | hmoco/osf.io,jmcarp/osf.io,abought/osf.io,amyshi188/osf.io,brandonPurvis/osf.io,sloria/osf.io,barbour-em/osf.io,lyndsysimon/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,HarryRybacki/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,wearpants/osf.io,TomBaxter/osf.io,samanehsan/osf.io,zachjanicki/osf.io,mluo613/osf.io,Zobai... | import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_N... | Change S3 full name to Amazon S3 | ## Code Before:
import os
from . import model
from . import routes
from . import views
MODELS = [model.AddonS3UserSettings, model.AddonS3NodeSettings, model.S3GuidFile]
USER_SETTINGS_MODEL = model.AddonS3UserSettings
NODE_SETTINGS_MODEL = model.AddonS3NodeSettings
ROUTES = [routes.settings_routes]
SHORT_NAME = 's3'... |
d18ff30bbddde5049ffbe23bce19288c3c47e41b | posts/views.py | posts/views.py | from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
| from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
def get_queryset(self):
"""
Order posts by the day they were added, from newest, to oldest.... | Order posts from newest to oldest | posts: Order posts from newest to oldest
| Python | mit | rtrembecky/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,matus-stehlik/roots,matus-stehlik/roots,matus-stehlik/glowing-batman,matus-stehlik/roots,matus-stehlik/glowing-batman,rtrembecky/roots,tbabej/roots | from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
+ def get_queryset(self):
+ """
+ Order posts by the day they were ad... | Order posts from newest to oldest | ## Code Before:
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
class PostDetailView(DetailView):
model = Post
context_object_name = 'post'
## Instru... |
b583c5fb00d1ebfa0458a6233be85d8b56173abf | python/printbag.py | python/printbag.py |
import sys
import logging
import numpy as np
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
from antlia.dtype import LIDAR_CONVERTED_DTYPE
def print_bag(bag, topics=None):
if topics is None:
#topics = ['/tf', '/scan']
topics = ['/scan', '/flagbu... | import sys
import logging
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
def print_bag(bag, topics=None):
for message in bag.read_messages(topics=topics):
print(message)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(('Usage: {} [top... | Add argument to specify bag topics | Add argument to specify bag topics
| Python | bsd-2-clause | oliverlee/antlia | -
import sys
import logging
-
- import numpy as np
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
- from antlia.dtype import LIDAR_CONVERTED_DTYPE
def print_bag(bag, topics=None):
- if topics is None:
- #topics = ['/tf', '/scan']
- ... | Add argument to specify bag topics | ## Code Before:
import sys
import logging
import numpy as np
# suppress logging warnings due to rospy
logging.basicConfig(filename='/dev/null')
import rosbag
from antlia.dtype import LIDAR_CONVERTED_DTYPE
def print_bag(bag, topics=None):
if topics is None:
#topics = ['/tf', '/scan']
topics = ['... |
ca06bf1d52cd51ccec178c98ad407bfe59f1ada1 | strobe.py | strobe.py | import RPi.GPIO as GPIO
from time import sleep
def onoff(period, pin):
"""Symmetric square wave, equal time on/off"""
half_cycle = period / 2.0
GPIO.output(pin, GPIO.HIGH)
sleep(half_cycle)
GPIO.output(pin, GPIO.LOW)
sleep(half_cycle)
def strobe(freq, dur, pin):
nflashes = freq * dur
s... |
import RPi.GPIO as GPIO
from time import sleep
def onoff(ontime, offtime, pin):
GPIO.output(pin, GPIO.HIGH)
sleep(ontime)
GPIO.output(pin, GPIO.LOW)
sleep(offtime)
def strobe(freq, dur, pin):
nflashes = freq * dur
period = 1.0 / freq
# Use Raspberry-Pi board pin numbers. In other words, ... | Make onoff function more versatile | Make onoff function more versatile
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie | +
import RPi.GPIO as GPIO
from time import sleep
+ def onoff(ontime, offtime, pin):
- def onoff(period, pin):
- """Symmetric square wave, equal time on/off"""
- half_cycle = period / 2.0
GPIO.output(pin, GPIO.HIGH)
- sleep(half_cycle)
+ sleep(ontime)
GPIO.output(pin, GPIO.LOW)
- ... | Make onoff function more versatile | ## Code Before:
import RPi.GPIO as GPIO
from time import sleep
def onoff(period, pin):
"""Symmetric square wave, equal time on/off"""
half_cycle = period / 2.0
GPIO.output(pin, GPIO.HIGH)
sleep(half_cycle)
GPIO.output(pin, GPIO.LOW)
sleep(half_cycle)
def strobe(freq, dur, pin):
nflashes = ... |
a08de1d3c7f7dfc72c8b3b8e9019d1b7b5ad004e | mdtraj/tests/test_load.py | mdtraj/tests/test_load.py |
from mdtraj import load
from mdtraj.testing import get_fn
def test_load_single():
"""
Just check for any raised errors coming from loading a single file.
"""
load(get_fn('frame0.pdb'))
def test_load_single_list():
"""
See if a single-element list of files is successfully loaded.
"""
l... | from mdtraj import load
from mdtraj.testing import get_fn
def test_load_single():
"""
Just check for any raised errors coming from loading a single file.
"""
load(get_fn('frame0.pdb'))
def test_load_single_list():
"""
See if a single-element list of files is successfully loaded.
"""
lo... | Fix test for loading multiple trajectories. | Fix test for loading multiple trajectories.
| Python | lgpl-2.1 | msultan/mdtraj,rmcgibbo/mdtraj,tcmoore3/mdtraj,mdtraj/mdtraj,jchodera/mdtraj,msultan/mdtraj,ctk3b/mdtraj,ctk3b/mdtraj,mdtraj/mdtraj,msultan/mdtraj,mattwthompson/mdtraj,jchodera/mdtraj,jchodera/mdtraj,leeping/mdtraj,gph82/mdtraj,rmcgibbo/mdtraj,gph82/mdtraj,jchodera/mdtraj,mdtraj/mdtraj,leeping/mdtraj,tcmoore3/mdtraj,ct... | -
from mdtraj import load
from mdtraj.testing import get_fn
def test_load_single():
"""
Just check for any raised errors coming from loading a single file.
"""
load(get_fn('frame0.pdb'))
def test_load_single_list():
"""
See if a single-element list of files is successf... | Fix test for loading multiple trajectories. | ## Code Before:
from mdtraj import load
from mdtraj.testing import get_fn
def test_load_single():
"""
Just check for any raised errors coming from loading a single file.
"""
load(get_fn('frame0.pdb'))
def test_load_single_list():
"""
See if a single-element list of files is successfully loade... |
b3400070d47d95bfa2eeac3a9f696b8957d88128 | conjureup/controllers/clouds/tui.py | conjureup/controllers/clouds/tui.py | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is no... | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(controller) is no... | Fix issue where non localhost headless clouds werent calling finish | Fix issue where non localhost headless clouds werent calling finish
Signed-off-by: Adam Stokes <49c255c1d074742f60d19fdba5e2aa5a34add567@users.noreply.github.com>
| Python | mit | conjure-up/conjure-up,Ubuntu-Solutions-Engineering/conjure,ubuntu/conjure-up,Ubuntu-Solutions-Engineering/conjure,conjure-up/conjure-up,ubuntu/conjure-up | from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controll... | Fix issue where non localhost headless clouds werent calling finish | ## Code Before:
from conjureup import controllers, events, juju, utils
from conjureup.app_config import app
from conjureup.consts import cloud_types
from .common import BaseCloudController
class CloudsController(BaseCloudController):
def __controller_exists(self, controller):
return juju.get_controller(c... |
b123001ea0d4fb475184727c39eafd5b46cc0964 | shopit_app/urls.py | shopit_app/urls.py | from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
from authentication_app.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpattern... | from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
from authentication_app.views import AccountViewSet, LoginView, LogoutView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)... | Add the endpoint for the logout. | Add the endpoint for the logout.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
- from authentication_app.views import AccountViewSet, LoginView
+ from authentication_app.views import AccountViewSet, LoginView, LogoutVie... | Add the endpoint for the logout. | ## Code Before:
from django.conf import settings
from django.conf.urls import include, patterns, url
from rest_framework_nested import routers
from shopit_app.views import IndexView
from authentication_app.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'accounts', AccountView... |
0d7921b4dcf5e3b511fdb54fc30ebc0547b14d47 | django_dzenlog/urls.py | django_dzenlog/urls.py | from django.conf.urls.defaults import *
from models import GeneralPost
from feeds import LatestPosts
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
'all': LatestPosts,
}
urlpatterns = patterns('django.views.generic',
(r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail', post_list, 'd... | from django.conf.urls.defaults import *
from models import GeneralPost
from feeds import latest
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
'all': latest(GeneralPost, 'dzenlog-post-list'),
}
urlpatterns = patterns('django.views.generic',
(r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.objec... | Use 'latest' to generate feed for GeneralPost. | Use 'latest' to generate feed for GeneralPost.
| Python | bsd-3-clause | svetlyak40wt/django-dzenlog | from django.conf.urls.defaults import *
from models import GeneralPost
- from feeds import LatestPosts
+ from feeds import latest
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
- 'all': LatestPosts,
+ 'all': latest(GeneralPost, 'dzenlog-post-list'),
}
urlpatterns =... | Use 'latest' to generate feed for GeneralPost. | ## Code Before:
from django.conf.urls.defaults import *
from models import GeneralPost
from feeds import LatestPosts
post_list = {
'queryset': GeneralPost.objects.all(),
}
feeds = {
'all': LatestPosts,
}
urlpatterns = patterns('django.views.generic',
(r'^(?P<slug>[a-z0-9-]+)/$', 'list_detail.object_detail... |
cab0f9ea3471cf88dd03da7a243ae55579b44b65 | client.py | client.py |
import RPi.GPIO as io
import requests
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
switches = set()
def has_free():
global switches
... |
import RPi.GPIO as io
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
server_url = sys.argv[1]
switches = set()
def has_free():
global swi... | Set server URL with command line argument | Set server URL with command line argument
| Python | mit | madebymany/isthetoiletfree |
import RPi.GPIO as io
- import requests
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
+ server_url = sys.argv[1... | Set server URL with command line argument | ## Code Before:
import RPi.GPIO as io
import requests
import sys
class Switch(object):
def __init__(self, **kwargs):
self.pin = kwargs["pin"]
io.setup(self.pin, io.IN)
@property
def is_on(self):
return io.input(self.pin)
PINS = (8, 16, 18)
switches = set()
def has_free():
glo... |
384beaa77e2eaad642ec7f764acd09c2c3e04350 | res_company.py | res_company.py | from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remittance Letter '
... | from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remittance Letter '
... | Make Remittance Letter config messages translatable | Make Remittance Letter config messages translatable
| Python | agpl-3.0 | xcgd/account_streamline | from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top o... | Make Remittance Letter config messages translatable | ## Code Before:
from openerp.osv import osv, fields
from openerp.tools.translate import _
class res_company(osv.Model):
_inherit = "res.company"
_columns = {
'remittance_letter_top': fields.text(
_('Remittance Letter - top message'),
help=_('Message to write at the top of Remi... |
813dd27a2057d2e32726ff6b43ab8ca1411303c7 | fabfile.py | fabfile.py | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('python sana_builder/manage... | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('python sana_builder/manage... | Prepare for deploy in deploy script. | Prepare for deploy in deploy script.
| Python | bsd-3-clause | SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder | from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('pyth... | Prepare for deploy in deploy script. | ## Code Before:
from fabric.api import *
from fabric.colors import *
env.colorize_errors = True
env.hosts = ['sanaprotocolbuilder.me']
env.user = 'root'
env.project_root = '/opt/sana.protocol_builder'
def prepare_deploy():
local('python sana_builder/manage.py syncdb')
local('python san... |
0ef346389b680e81ab618d4d782239640c1926f5 | tests/test_collection.py | tests/test_collection.py | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
... | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("test_root")
... | Remove unnecessary test of collection children | Remove unnecessary test of collection children
| Python | agpl-3.0 | UMD-DRASTIC/drastic | import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collectio... | Remove unnecessary test of collection children | ## Code Before:
import unittest
from indigo.models import Collection
from indigo.models.errors import UniqueException
from nose.tools import raises
class NodeTest(unittest.TestCase):
def test_a_create_root(self):
Collection.create(name="test_root", parent=None, path="/")
coll = Collection.find("... |
6858e4a2e2047c906a3b8f69b7cd7b04a0cbf666 | pivoteer/writer/censys.py | pivoteer/writer/censys.py |
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Censys Records using the given writer.
:... |
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Censys Records using the given writer.
:... | Resolve issues with exporting empty dataset for certificate list | Resolve issues with exporting empty dataset for certificate list
| Python | mit | gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID |
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Censys Records using the ... | Resolve issues with exporting empty dataset for certificate list | ## Code Before:
from pivoteer.writer.core import CsvWriter
class CensysCsvWriter(CsvWriter):
"""
A CsvWriter implementation for IndicatorRecords with a record type of "CE" (Censys Record)
"""
def __init__(self, writer):
"""
Create a new CsvWriter for Censys Records using the given wr... |
87d1801fefcd048f60c944c28bfc005101c5704b | dynd/tests/test_nd_groupby.py | dynd/tests/test_nd_groupby.py | import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dtype='{A: string; B: int32}'... | import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dtype='{A: string; B: int32}'... | Add some more simple nd.groupby tests | Add some more simple nd.groupby tests
| Python | bsd-2-clause | cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,insertinterestingnamehere/dynd-python,aterrel/dynd-python,cpcloud/dynd-python,cpcloud/dynd-python,izaid/dynd-python,aterrel/dynd-python,mwiebe/dynd-python,michaelpacer/dynd-python,mwiebe/dynd-python,pombredanne/dynd-py... | import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dty... | Add some more simple nd.groupby tests | ## Code Before:
import sys
import unittest
from dynd import nd, ndt
class TestGroupBy(unittest.TestCase):
def test_immutable(self):
a = nd.array([
('x', 0),
('y', 1),
('x', 2),
('x', 3),
('y', 4)],
dtype='{A: st... |
7b935b23e17ef873a060fdfbefbfdf232fe8b8de | git_release/release.py | git_release/release.py | import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
new_minor = 0
else... | import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
new_minor = 0
else... | Add missing argument to _increment_tag call | Add missing argument to _increment_tag call
| Python | mit | Authentise/git-release | import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
... | Add missing argument to _increment_tag call | ## Code Before:
import subprocess
from git_release import errors, git_helpers
def _parse_tag(tag):
major, minor = tag.split('.')
return int(major), int(minor)
def _increment_tag(tag, release_type):
major, minor = _parse_tag(tag)
if release_type == 'major':
new_major = major + 1
new_mi... |
11aab47e3c8c0d4044042aead7c01c990a152bea | tests/integration/customer/test_dispatcher.py | tests/integration/customer/test_dispatcher.py | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCa... | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestDispatcher(TestCa... | Add tests for sending messages to emails without account. | Add tests for sending messages to emails without account.
| Python | bsd-3-clause | sonofatailor/django-oscar,solarissmoke/django-oscar,okfish/django-oscar,okfish/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,okfish/django-oscar,sonofatailor/django-oscar,okfish... | from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
c... | Add tests for sending messages to emails without account. | ## Code Before:
from django.test import TestCase
from django.core import mail
from oscar.core.compat import get_user_model
from oscar.apps.customer.utils import Dispatcher
from oscar.apps.customer.models import CommunicationEventType
from oscar.test.factories import create_order
User = get_user_model()
class TestD... |
f3efb01c530db87f48d813b118f80a2ee1fd5996 | dthm4kaiako/users/apps.py | dthm4kaiako/users/apps.py | """Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon intialising application."""... | """Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon intialising application."""... | Exclude import from style checking | Exclude import from style checking
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | """Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon i... | Exclude import from style checking | ## Code Before:
"""Application configuration for the chapters application."""
from django.apps import AppConfig
class UsersAppConfig(AppConfig):
"""Configuration object for the chapters application."""
name = "users"
verbose_name = "Users"
def ready(self):
"""Import signals upon intialising... |
6454372da6550455735cbcb3a86a966e61c134a1 | elasticsearch/__init__.py | elasticsearch/__init__.py | from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
RoundRobinSelec... | from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
RoundRobinSelec... | Allow people to import ThriftConnection from elasticsearch package itself | Allow people to import ThriftConnection from elasticsearch package itself
| Python | apache-2.0 | veatch/elasticsearch-py,chrisseto/elasticsearch-py,Garrett-R/elasticsearch-py,brunobell/elasticsearch-py,tailhook/elasticsearch-py,AlexMaskovyak/elasticsearch-py,brunobell/elasticsearch-py,mjhennig/elasticsearch-py,thomdixon/elasticsearch-py,kelp404/elasticsearch-py,gardsted/elasticsearch-py,elastic/elasticsearch-py,el... | from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
... | Allow people to import ThriftConnection from elasticsearch package itself | ## Code Before:
from __future__ import absolute_import
VERSION = (0, 4, 3)
__version__ = VERSION
__versionstr__ = '.'.join(map(str, VERSION))
from elasticsearch.client import Elasticsearch
from elasticsearch.transport import Transport
from elasticsearch.connection_pool import ConnectionPool, ConnectionSelector, \
... |
56446567f764625e88d8efdbfa2849e0a579d5c4 | indra/tests/test_rest_api.py | indra/tests/test_rest_api.py | import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "ME... | import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"}, "name": "ME... | Update REST API address in test | Update REST API address in test
| Python | bsd-2-clause | sorgerlab/belpy,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,pvtodorov/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,johnbachman/indra | import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "MEK"},... | Update REST API address in test | ## Code Before:
import requests
from nose.plugins.attrib import attr
@attr('webservice')
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "FPLX": "ME... |
6bdbbf4d5e100856acbaba1c5fc024a9f7f78718 | tests/tools.py | tests/tools.py |
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)])
... |
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
from brandon import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--por... | Test tool to create temporary devpi index. | Test tool to create temporary devpi index.
| Python | bsd-3-clause | tylerdave/devpi-builder |
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
+ from brandon import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--start', '--serverdi... | Test tool to create temporary devpi index. | ## Code Before:
__author__ = 'mbach'
import contextlib
import shutil
import subprocess
import tempfile
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_call(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.form... |
6d291571dca59243c0a92f9955776e1acd2e87da | falmer/content/queries.py | falmer/content/queries.py | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_... | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
def resolve_... | Return empty result rather than graphql error | Return empty result rather than graphql error
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.Strin... | Return empty result rather than graphql error | ## Code Before:
import graphene
from django.http import Http404
from graphql import GraphQLError
from wagtail.core.models import Page
from . import types
class Query(graphene.ObjectType):
page = graphene.Field(types.Page, path=graphene.String())
all_pages = graphene.List(types.Page, path=graphene.String())
... |
d63905158f5148b07534e823d271326262369d42 | pavement.py | pavement.py | import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
VERSION = eval(re.search(... | import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
VERSION = eval(re.search(... | Use context manager to read README | Use context manager to read README
| Python | mit | jaraco/irc | import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
... | Use context manager to read README | ## Code Before:
import os
import re
from paver.easy import *
from paver.setuputils import setup
def get_version():
"""
Grab the version from irclib.py.
"""
here = os.path.dirname(__file__)
irclib = os.path.join(here, 'irclib.py')
with open(irclib) as f:
content = f.read()
VERSION =... |
d407f1bcd95daf4f4bd8dfe8ae3b4b9e68061cb5 | cref/sequence/fragment.py | cref/sequence/fragment.py |
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
for i in range(len(sequence) - size + 1):
... |
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
if size > 0:
for i in range(len(sequence)... | Handle sliding window with size 0 | Handle sliding window with size 0
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 |
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
+ if size > 0:
- for i in... | Handle sliding window with size 0 | ## Code Before:
def fragment(sequence, size=5):
"""
Fragment a string sequence using a sliding window given by size
:param sequence: String containing the sequence
:param size: Size of the window
:return: a fragment of the sequence with the given size
"""
for i in range(len(sequence) - si... |
2f16eb25db856b72138f6dfb7d19e799bd460287 | tests/test_helpers.py | tests/test_helpers.py | import pytest
from os.path import basename
from helpers import utils, fixture
@pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
class TestHelpers():
def test_wildcards1():
d = utils.get_wildcards([('"{prefix}.bam"', "medium.... | import pytest
from os.path import basename
from helpers import utils, fixture
pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
def test_wildcards1():
d = utils.get_wildcards([('"{prefix}.bam"', "medium.bam")], {})
... | Use global pytestmark to skip tests; deprecate class | Use global pytestmark to skip tests; deprecate class
| Python | mit | percyfal/snakemake-rules,percyfal/snakemake-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules,percyfal/snakemakelib-rules | import pytest
from os.path import basename
from helpers import utils, fixture
-
- @pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
+ pytestmark = pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason=... | Use global pytestmark to skip tests; deprecate class | ## Code Before:
import pytest
from os.path import basename
from helpers import utils, fixture
@pytest.mark.skipif(pytest.config.getoption("--application") is not False, reason="application passed; skipping base module tests")
class TestHelpers():
def test_wildcards1():
d = utils.get_wildcards([('"{prefix}... |
723d7410b48fd4fc42ed9afe470ba3b37381599a | noxfile.py | noxfile.py | """Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
",".join(extras),
si... | """Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
",".join(extras),
si... | Add docs-live to perform demo-runs | Add docs-live to perform demo-runs
| Python | mit | GaretJax/sphinx-autobuild | """Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
... | Add docs-live to perform demo-runs | ## Code Before:
"""Development automation."""
import nox
def _install_this_editable(session, *, extras=None):
if extras is None:
extras = []
session.install("flit")
session.run(
"flit",
"install",
"-s",
"--deps=production",
"--extras",
",".join(ext... |
41209aa3e27673f003ed62a46c9bfae0c19d0bf3 | il2fb/ds/airbridge/typing.py | il2fb/ds/airbridge/typing.py |
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.parsers.events.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringOrNone = Optional... |
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.commons.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringOrNone = Optional[str]
S... | Update import of Event class | Update import of Event class
| Python | mit | IL2HorusTeam/il2fb-ds-airbridge |
from pathlib import Path
from typing import Callable, Optional, List, Union
- from il2fb.parsers.events.events import Event
+ from il2fb.commons.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], ... | Update import of Event class | ## Code Before:
from pathlib import Path
from typing import Callable, Optional, List, Union
from il2fb.parsers.events.events import Event
EventOrNone = Optional[Event]
EventHandler = Callable[[Event], None]
IntOrNone = Optional[int]
StringProducer = Callable[[], str]
StringHandler = Callable[[str], None]
StringO... |
7ee86e9b52292a8824dfa7bab632526cbb365b51 | routes.py | routes.py |
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid='
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
userco... |
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate'
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
... | Use new OpenAM token validation endpoint | Use new OpenAM token validation endpoint
| Python | unlicense | timhberry/openam-flask-decorator |
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
- validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid='
+ validTokenAPI = amURL + 'openam/json/sessions/{token}?_action=validate'
loginURL = amURL + 'openam/UI/Login'
... | Use new OpenAM token validation endpoint | ## Code Before:
from flask import request, redirect
import requests
cookiename = 'openAMUserCookieName'
amURL = 'https://openam.example.com/'
validTokenAPI = amURL + 'openam/identity/istokenvalid?tokenid='
loginURL = amURL + 'openam/UI/Login'
def session_required(f):
@wraps(f)
def decorated_function(*args, **kwa... |
463abcce738ca1c47729cc0e465da9dc399e21dd | examples/remote_download.py | examples/remote_download.py |
from xunleipy.remote import XunLeiRemote
def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0):
remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy)
remote_client.login()
peer_list = remote_client.get_remote... | import sys
import os
from xunleipy.remote import XunLeiRemote
sys.path.append('/Users/gunner/workspace/xunleipy')
def remote_download(username,
password,
rk_username,
rk_password,
download_links,
proxy=None,
... | Change example style for python3 | Change example style for python3
| Python | mit | lazygunner/xunleipy | + import sys
+ import os
from xunleipy.remote import XunLeiRemote
+ sys.path.append('/Users/gunner/workspace/xunleipy')
- def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0):
+ def remote_download(username,
+ password,
+ ... | Change example style for python3 | ## Code Before:
from xunleipy.remote import XunLeiRemote
def remote_download(username, password, rk_username, rk_password, download_links, proxy=None, path='C:/TD/', peer=0):
remote_client = XunLeiRemote(username, password, rk_username, rk_password, proxy=proxy)
remote_client.login()
peer_list = remote_c... |
ab47c678b37527a7b8a970b365503b65ffccda87 | populous/cli.py | populous/cli.py | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
... | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickException(e.message)
... | Handle unexpected errors properly in load_blueprint | Handle unexpected errors properly in load_blueprint
| Python | mit | novafloss/populous | import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.Cli... | Handle unexpected errors properly in load_blueprint | ## Code Before:
import click
from .loader import load_yaml
from .blueprint import Blueprint
from .exceptions import ValidationError, YAMLError
def get_blueprint(*files):
try:
return Blueprint.from_description(load_yaml(*files))
except (YAMLError, ValidationError) as e:
raise click.ClickExcept... |
0485e6dcaf19061812d0e571890e58b85b5dea12 | lava_results_app/utils.py | lava_results_app/utils.py | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class Stre... | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_length)
class Stre... | Return an empty dict if no data | Return an empty dict if no data
Avoids a HTTP500 on slow instances where the file
may be created before data is written, causing the
YAML parser to return None.
Change-Id: I13b92941f3e368839a9665fe3197c706babd9335
| Python | agpl-3.0 | Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server | import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(... | Return an empty dict if no data | ## Code Before:
import os
import yaml
import logging
from django.utils.translation import ungettext_lazy
from django.conf import settings
def help_max_length(max_length):
return ungettext_lazy(
u"Maximum length: {0} character",
u"Maximum length: {0} characters",
max_length).format(max_leng... |
28c6af1381a1fc38b20ce05e85f494f3ae2beeb4 | arcutils/masquerade/templatetags/masquerade.py | arcutils/masquerade/templatetags/masquerade.py | from django import template
from .. import perms
from ..settings import get_user_attr
register = template.Library()
@register.filter
def is_masquerading(user):
info = getattr(user, get_user_attr())
return info['is_masquerading']
@register.filter
def can_masquerade(user):
return perms.can_masquerade(u... | from django import template
from .. import perms
from ..settings import get_user_attr, is_enabled
register = template.Library()
@register.filter
def is_masquerading(user):
if not is_enabled():
return False
info = getattr(user, get_user_attr(), None)
return info['is_masquerading']
@register.fi... | Make is_masquerading template tag more robust | Make is_masquerading template tag more robust
When masquerading is not enabled, immediately return False to avoid
checking for a request attribute that won't be present.
| Python | mit | PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils | from django import template
from .. import perms
- from ..settings import get_user_attr
+ from ..settings import get_user_attr, is_enabled
register = template.Library()
@register.filter
def is_masquerading(user):
+ if not is_enabled():
+ return False
- info = getattr(user, get_u... | Make is_masquerading template tag more robust | ## Code Before:
from django import template
from .. import perms
from ..settings import get_user_attr
register = template.Library()
@register.filter
def is_masquerading(user):
info = getattr(user, get_user_attr())
return info['is_masquerading']
@register.filter
def can_masquerade(user):
return perms.... |
263e517004df36938b430d8802d4fc80067fadf5 | djangoreact/urls.py | djangoreact/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^$', views.index),
url(r'^ap... | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^api/auth/', include('rest_auth.... | Fix to use react-router for all unmatched routes. | Fix to use react-router for all unmatched routes.
| Python | mit | willy-claes/django-react,willy-claes/django-react,willy-claes/django-react | from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
- url(r'^$', views... | Fix to use react-router for all unmatched routes. | ## Code Before:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from server import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^$', views.index... |
f83282b1747e255d35e18e9fecad1750d1564f9e | do_record/record.py | do_record/record.py | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
... | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname = hostname
... | Remove Code That Doesn't Have a Test | Remove Code That Doesn't Have a Test
| Python | apache-2.0 | Jitsusama/lets-do-dns | """DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.... | Remove Code That Doesn't Have a Test | ## Code Before:
"""DigitalOcean DNS Records."""
from certbot_dns_auth.printer import printer
from do_record import http
class Record(object):
"""Handle DigitalOcean DNS records."""
def __init__(self, api_key, domain, hostname):
self._number = None
self.domain = domain
self.hostname =... |
413c3e9e8a093e3f336e27a663f347f5ea9866a6 | performanceplatform/collector/ga/__init__.py | performanceplatform/collector/ga/__init__.py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, end_at):
clien... | Allow the 'dataType' field to be overriden | Allow the 'dataType' field to be overriden
The 'dataType' field in records predates data groups and data types. As
such they don't always match the new world order of data types. It's
fine to change in all cases other than Licensing which is run on
limelight, that we don't really want to touch.
| Python | mit | alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at... | Allow the 'dataType' field to be overriden | ## Code Before:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from performanceplatform.collector.ga.core \
import create_client, query_documents_for, send_data
from performanceplatform.collector.write import DataSet
def main(credentials, data_set_config, query, options, start_at, en... |
95542ab1b7c22a6e0160e242349c66f2cef7e390 | syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py | syntacticframes_project/syntacticframes/management/commands/check_correspondance_errors.py | from django.core.management.base import BaseCommand
from syntacticframes.models import VerbNetClass
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
for vn_class in VerbNetClass.objects.all():
try:
... | from django.core.management.base import BaseCommand
from syntacticframes.models import VerbNetFrameSet
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
for frameset in VerbNetFrameSet.objects.all():
print("{}:... | Check correspondances in framesets now | Check correspondances in framesets now
| Python | mit | aymara/verbenet-editor,aymara/verbenet-editor,aymara/verbenet-editor | from django.core.management.base import BaseCommand
- from syntacticframes.models import VerbNetClass
+ from syntacticframes.models import VerbNetFrameSet
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
- f... | Check correspondances in framesets now | ## Code Before:
from django.core.management.base import BaseCommand
from syntacticframes.models import VerbNetClass
from parsecorrespondance import parse
from loadmapping import mapping
class Command(BaseCommand):
def handle(self, *args, **options):
for vn_class in VerbNetClass.objects.all():
... |
6c54fc230e8c889a2351f20b524382a5c6e29d1c | examples/apps.py | examples/apps.py | import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN.')
sys.exit(1)
api = TsuruClient(TSURU_TARGET, TSURU_TOKEN)
# L... | import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN env variables.')
sys.exit(1)
# Creating TsuruClient instance
tsu... | Update examples to match docs | Update examples to match docs
Use the interface defined in the docs in the examples scripts.
| Python | mit | rcmachado/pysuru | import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
- print('You must set TSURU_TARGET and TSURU_TOKEN.')
+ print('You must set TSURU_TARGET and T... | Update examples to match docs | ## Code Before:
import os
import sys
from pysuru import TsuruClient
TSURU_TARGET = os.environ.get('TSURU_TARGET', None)
TSURU_TOKEN = os.environ.get('TSURU_TOKEN', None)
if not TSURU_TARGET or not TSURU_TOKEN:
print('You must set TSURU_TARGET and TSURU_TOKEN.')
sys.exit(1)
api = TsuruClient(TSURU_TARGET, T... |
b5a8e7b6926bf7224abed6bd335d62b3f1ad1fb1 | performance_testing/command_line.py | performance_testing/command_line.py | import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
from datetime import datetime as date
from time import time
class Tool:
def __init__(self, config='config.yml', result_directory='result'):
self.read_config(config_file=config)
... | import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
from performance_testing.config import Config
from performance_testing.result import Result
class Tool:
def __init__(self, config='config.yml', result_directory='result'):
self.... | Use Config and Result class in Tool | Use Config and Result class in Tool
| Python | mit | BakeCode/performance-testing,BakeCode/performance-testing | import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
- from datetime import datetime as date
- from time import time
+ from performance_testing.config import Config
+ from performance_testing.result import Result
class Tool:
... | Use Config and Result class in Tool | ## Code Before:
import os
import yaml
from performance_testing.errors import ConfigFileError, ConfigKeyError
from performance_testing import web
from datetime import datetime as date
from time import time
class Tool:
def __init__(self, config='config.yml', result_directory='result'):
self.read_config(conf... |
5fc699b89eae0c41923a813ac48281729c4d80b8 | orderable_inlines/inlines.py | orderable_inlines/inlines.py | from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
... | from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.js',
)
... | Make this hack compatible with Django 1.9 | Make this hack compatible with Django 1.9
| Python | bsd-2-clause | frx0119/django-orderable-inlines,frx0119/django-orderable-inlines | from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inl... | Make this hack compatible with Django 1.9 | ## Code Before:
from django.contrib.admin import StackedInline, TabularInline
from django.template.defaultfilters import slugify
class OrderableInlineMixin(object):
class Media:
js = (
'js/jquery.browser.min.js',
'js/orderable-inline-jquery-ui.js',
'js/orderable-inline.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.