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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
e905334869af72025592de586b81650cb3468b8a | sentry/queue/client.py | sentry/queue/client.py | from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
def d... | from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
wi... | Declare queues when broker is instantiated | Declare queues when broker is instantiated
| Python | bsd-3-clause | imankulov/sentry,BuildingLink/sentry,zenefits/sentry,korealerts1/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,ngonzalvez/sentry,mvaled/sentry,Kronuz/django-sentry,ngonzalvez/sentry,looker/sentry,felixbuenemann/sentry,ngonzalvez/sentry,nicholasserra/sentry,camilonova/sentry,jokey2k/sentry,llonchj/sentry,... | from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnectio... | Declare queues when broker is instantiated | ## Code Before:
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**co... |
950ac9130bafe1fced578bf61d746b047830bfa0 | automata/base/exceptions.py | automata/base/exceptions.py | """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
... | """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(AutomatonException):
... | Remove "validation" from RejectionException docstring | Remove "validation" from RejectionException docstring
| Python | mit | caleb531/automata | """Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidS... | Remove "validation" from RejectionException docstring | ## Code Before:
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolError(Autom... |
c3f8860c717a139d396b0d902db989ab7b8369ba | stock_inventory_hierarchical/__openerp__.py | stock_inventory_hierarchical/__openerp__.py |
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_invento... |
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["views/stock_invento... | Fix image path in manifest | Fix image path in manifest
| Python | agpl-3.0 | kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse |
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["v... | Fix image path in manifest | ## Code Before:
{
"name": "Hierarchical Inventory adjustments",
"summary": "Group several Inventory adjustments in a master inventory",
"version": "8.0.2.0.0",
"depends": ["stock"],
"author": u"Numérigraphe,Odoo Community Association (OCA)",
"category": "Warehouse Management",
"data": ["vie... |
70a642c0597fb2f929fc83d821c8b1f095ed1328 | proxy/plugins/plugins.py | proxy/plugins/plugins.py | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
packetFunctions[(self.pktType, self.pktSubtype)] = f
c... | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
if (self.pktType, self.pktSubtype) not in packetFunctio... | Allow mutiple hooks for packets | Allow mutiple hooks for packets
| Python | agpl-3.0 | alama/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,cyberkitsune/PSO2Proxy | packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
+ if (self.pktType, self.pktS... | Allow mutiple hooks for packets | ## Code Before:
packetFunctions = {}
commands = {}
onStart = []
onConnection = []
onConnectionLoss = []
class packetHook(object):
def __init__(self, pktType, pktSubtype):
self.pktType = pktType
self.pktSubtype = pktSubtype
def __call__(self, f):
global packetFunctions
packetFunctions[(self.pktType, self.pkt... |
af91b7c2612fab598ba50c0c0256f7e552098d92 | reportlab/docs/genAll.py | reportlab/docs/genAll.py | """Runs the three manual-building scripts"""
if __name__=='__main__':
import os, sys
d = os.path.dirname(sys.argv[0])
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
if not d: d = '.'
if not os.path.isabs(d):
... | import os
def _genAll(d=None,quiet=''):
if not d: d = '.'
if not os.path.isabs(d):
d = os.path.normpath(os.path.join(os.getcwd(),d))
for p in ('reference/genreference.py',
'userguide/genuserguide.py',
'graphguide/gengraphguide.py',
'../tools/docco/graphdocpy.py'):
os.chdir(d)
os.chdir(os.path.di... | Allow for use in daily.py | Allow for use in daily.py
| Python | bsd-3-clause | makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile | + import os
+ def _genAll(d=None,quiet=''):
+ if not d: d = '.'
+ if not os.path.isabs(d):
+ d = os.path.normpath(os.path.join(os.getcwd(),d))
+ for p in ('reference/genreference.py',
+ 'userguide/genuserguide.py',
+ 'graphguide/gengraphguide.py',
+ '../tools/docco/graphdocpy.py'):
+ os.chdir(d)
+... | Allow for use in daily.py | ## Code Before:
"""Runs the three manual-building scripts"""
if __name__=='__main__':
import os, sys
d = os.path.dirname(sys.argv[0])
#need a quiet mode for the test suite
if '-s' in sys.argv: # 'silent
quiet = '-s'
else:
quiet = ''
if not d: d = '.'
if not os.p... |
e34969db596ff3dfa4bf78efb3f3ccfe771d9ef9 | setup.py | setup.py | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.2'
data_files = [
(
'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ],
),
]
se... | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.4'
package_data = {
'exceptional_middleware': [ 'templates/http_responses/*.html' ],
}
setup(
name=PACKAGE, version=VERSION,
description="Django m... | Fix templates install. Bump to version 0.4 in the process (which is really my laziness). | Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
| Python | mit | jaylett/django_exceptional_middleware | try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
- VERSION = '0.2'
+ VERSION = '0.4'
+ package_data = {
+ 'exceptional_middleware': [ 'templates/http_responses/*.html' ],
+ }
- data_files = [
- (
- ... | Fix templates install. Bump to version 0.4 in the process (which is really my laziness). | ## Code Before:
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_exceptional_middleware'
VERSION = '0.2'
data_files = [
(
'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html'... |
c6265c2112ee9985af8b6b80fe0bee1811dc6abd | setup.py | setup.py | from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.6',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
author_email='mail@andreaspoehlmann.de',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python driver for Ocean Op... | from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.7',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams',
author_email='mail@andreaspoehlmann.de',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python ... | Add author and increase version number | Add author and increase version number
| Python | mit | ap--/python-oceanoptics | from distutils.core import setup
setup(
name='oceanoptics',
- version='0.2.6',
+ version='0.2.7',
- author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
+ author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams',
au... | Add author and increase version number | ## Code Before:
from distutils.core import setup
setup(
name='oceanoptics',
version='0.2.6',
author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter',
author_email='mail@andreaspoehlmann.de',
packages=['oceanoptics', 'oceanoptics.spectrometers'],
description='A Python dri... |
5bb9b2c9d5df410c85f4736c17224aeb2f05dd33 | s2v3.py | s2v3.py | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actu... | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actu... | Update print result to use "," instead of "+" for context text | Update print result to use "," instead of "+" for context text
| Python | mit | alexmilesyounger/ds_basics | from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip... | Update print result to use "," instead of "+" for context text | ## Code Before:
from s2v2 import *
def calculate_sum(data_sample):
total = 0
for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed t... |
3ba5b6491bf61e2d2919f05bbf5cef088a754aeb | molecule/default/tests/test_installation.py | molecule/default/tests/test_installation.py |
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if package... |
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
Test if package... | Add nologin in expected user shell test | Add nologin in expected user shell test
| Python | mit | infOpen/ansible-role-vsftpd |
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):... | Add nologin in expected user shell test | ## Code Before:
import os
import pytest
from testinfra.utils.ansible_runner import AnsibleRunner
testinfra_hosts = AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('vsftpd'),
('db5.3-util'),
])
def test_installed_packages(host, name):
"""
... |
b4c9b76d132668695b77d37d7db3071e629fcba7 | makerscience_admin/models.py | makerscience_admin/models.py | from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = models.TextField... | from django.db import models
from django.db.models.signals import post_delete
from solo.models import SingletonModel
from accounts.models import ObjectProfileLink
from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=Tr... | Allow to clear useless instances | Allow to clear useless instances
| Python | agpl-3.0 | atiberghien/makerscience-server,atiberghien/makerscience-server | from django.db import models
+ from django.db.models.signals import post_delete
+
from solo.models import SingletonModel
+
+ from accounts.models import ObjectProfileLink
+
+ from makerscience_forum.models import MakerSciencePost
class MakerScienceStaticContent (SingletonModel):
about = models.TextFie... | Allow to clear useless instances | ## Code Before:
from django.db import models
from solo.models import SingletonModel
class MakerScienceStaticContent (SingletonModel):
about = models.TextField(null=True, blank=True)
about_team = models.TextField(null=True, blank=True)
about_contact = models.TextField(null=True, blank=True)
about_faq = ... |
c713273fe145418113d750579f8b135dc513c3b8 | config.py | config.py | import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| import os
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| Delete default case for SQLALCHEMY_DATABASE_URI | Delete default case for SQLALCHEMY_DATABASE_URI
if user doesn't set it, he coud have some problems with SQLite
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | import os
- if os.environ.get('DATABASE_URL') is None:
- SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
- else:
- SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
+ SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
-
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
| Delete default case for SQLALCHEMY_DATABASE_URI | ## Code Before:
import os
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db'
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
## Instruction:
Delete default case for SQLALCHEMY_DATABASE_UR... |
c61d5e84863dd67b5b76ec8031e624642f4c957c | main.py | main.py | from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
from .ide.utility import *
| from .ide.auto_complete import *
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
| Fix issue with wrong import | Fix issue with wrong import
| Python | mit | b123400/purescript-ide-sublime | + from .ide.auto_complete import *
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
- from .ide.utility import *
| Fix issue with wrong import | ## Code Before:
from .ide.command import plugin_unloaded
from .ide.error import *
from .ide.rebuild import *
from .ide.server import *
from .ide.settings import plugin_loaded
from .ide.text_command import *
from .ide.type_hints import *
from .ide.utility import *
## Instruction:
Fix issue with wrong import
## Code Aft... |
4e75e742475236cf7358b4481a29a54eb607dd4d | spacy/tests/regression/test_issue850.py | spacy/tests/regression/test_issue850.py | '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
@pytest.mark.xfail
def test_issue850():
matcher = Matcher(Vocab())
IS_ANY_TOKEN ... | '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
def test_basic_case():
matcher = Matcher(Vocab... | Update regression test for variable-length pattern problem in the matcher. | Update regression test for variable-length pattern problem in the matcher.
| Python | mit | aikramer2/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howa... | '''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
+ from __future__ import print_function
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
+ def test_basic_case():... | Update regression test for variable-length pattern problem in the matcher. | ## Code Before:
'''
Test Matcher matches with '*' operator and Boolean flag
'''
from __future__ import unicode_literals
import pytest
from ...matcher import Matcher
from ...vocab import Vocab
from ...attrs import LOWER
from ...tokens import Doc
@pytest.mark.xfail
def test_issue850():
matcher = Matcher(Vocab())
... |
fa8783f3307582dafcf636f5c94a7e4cff05724b | bin/tree_print_fasta_names.py | bin/tree_print_fasta_names.py |
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
def process_node(self,n... |
import os
import shutil
import datetime
import sys
from ete3 import Tree
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=Tree(tree_newick_fn,format=format)
def process_node(self,node):
if node.is_leaf():
if hasatt... | Fix error in loading trees | Fix error in loading trees
Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda | Python | mit | karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle |
import os
import shutil
import datetime
import sys
- import argparse
from ete3 import Tree
-
- import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
- self.tree=read_newick(tree_newick_fn,form... | Fix error in loading trees | ## Code Before:
import os
import shutil
import datetime
import sys
import argparse
from ete3 import Tree
import logging
DEFAULT_FORMAT = 1
class TreeIndex:
def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT):
self.tree_newick_fn=tree_newick_fn
self.tree=read_newick(tree_newick_fn,format=format)
def pro... |
a20c6d072d70c535ed1f116fc04016c834ea9c14 | doc/en/_getdoctarget.py | doc/en/_getdoctarget.py |
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line:
return eval(line.split("=")[-1])
def get_minor_version_string():
return ".".join(ge... |
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line and not line.strip().startswith('#'):
return eval(line.split("=")[-1])
def get_minor_ver... | Fix getdoctarget to ignore comment lines | Fix getdoctarget to ignore comment lines
| Python | mit | etataurov/pytest,gabrielcnr/pytest,mbirtwell/pytest,vodik/pytest,The-Compiler/pytest,omarkohl/pytest,Bjwebb/pytest,davidszotten/pytest,gabrielcnr/pytest,mdboom/pytest,ionelmc/pytest,malinoff/pytest,hpk42/pytest,tareqalayan/pytest,userzimmermann/pytest,rouge8/pytest,tgoodlet/pytest,abusalimov/pytest,bukzor/pytest,icemac... |
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
- if "version" in line:
+ if "version" in line and not line.strip().startswith('#'):
r... | Fix getdoctarget to ignore comment lines | ## Code Before:
import py
def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line:
return eval(line.split("=")[-1])
def get_minor_version_string():
re... |
efd6fad89131c4d3070c68013ace77f11647bd68 | opal/core/search/__init__.py | opal/core/search/__init__.py | from opal.core.search import urls
from opal.core import plugins
from opal.core import celery # NOQA
class SearchPlugin(plugins.OpalPlugin):
"""
The plugin entrypoint for OPAL's core search functionality
"""
urls = urls.urlpatterns
javascripts = {
'opal.services': [
'js/searc... | from opal.core import celery # NOQA
from opal.core.search import plugin
| Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor | Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | + from opal.core import celery # NOQA
- from opal.core.search import urls
+ from opal.core.search import plugin
- from opal.core import plugins
-
- from opal.core import celery # NOQA
-
-
- class SearchPlugin(plugins.OpalPlugin):
- """
- The plugin entrypoint for OPAL's core search functionality
- "... | Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor | ## Code Before:
from opal.core.search import urls
from opal.core import plugins
from opal.core import celery # NOQA
class SearchPlugin(plugins.OpalPlugin):
"""
The plugin entrypoint for OPAL's core search functionality
"""
urls = urls.urlpatterns
javascripts = {
'opal.services': [
... |
56a8b900570200e63ee460dd7e2962cba2450b16 | preparation/tools/build_assets.py | preparation/tools/build_assets.py | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(expla... | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(expla... | Fix bug with 'all' argument | Fix bug with 'all' argument
| Python | mit | hatbot-team/hatbot_resources | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
... | Fix bug with 'all' argument | ## Code Before:
from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
... |
6167215e4ed49e8a4300f327d5b4ed4540d1a420 | numba/tests/npyufunc/test_parallel_env_variable.py | numba/tests/npyufunc/test_parallel_env_variable.py | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test... | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_numba_parallel_test... | Fix the parallel env variable test to reset the env correctly | Fix the parallel env variable test to reset the env correctly
| Python | bsd-2-clause | seibert/numba,seibert/numba,stonebig/numba,cpcloud/numba,sklam/numba,gmarkall/numba,stuartarchibald/numba,numba/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,sklam/numba,sklam/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,numba/numba,stuar... | from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
... | Fix the parallel env variable test to reset the env correctly | ## Code Before:
from numba.np.ufunc.parallel import get_thread_count
from os import environ as env
from numba.core import config
import unittest
class TestParallelEnvVariable(unittest.TestCase):
"""
Tests environment variables related to the underlying "parallel"
functions for npyufuncs.
"""
_num... |
504205d02ef2f5b66da225390fdb34b8b736ce57 | ideascube/migrations/0009_add_a_system_user.py | ideascube/migrations/0009_add_a_system_user.py | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import migrations
def add_user(*args):
User = get_user_model()
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ide... | from __future__ import unicode_literals
from django.db import migrations
def add_user(apps, *args):
User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies = [
('ideascube', '0008_user_sd... | Load user from migration registry when creating system user | Load user from migration registry when creating system user
Always load models from the registry in migration files.
I hate the idea of touching a migration already released, but
this one prevents us from adding new properties to User.
If we load the User directly (not from registry) when creating
the user model, we'l... | Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from __future__ import unicode_literals
- from django.contrib.auth import get_user_model
from django.db import migrations
- def add_user(*args):
+ def add_user(apps, *args):
- User = get_user_model()
+ User = apps.get_model('ideascube', 'User')
User(serial='__system__', full_name='System', pa... | Load user from migration registry when creating system user | ## Code Before:
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import migrations
def add_user(*args):
User = get_user_model()
User(serial='__system__', full_name='System', password='!!').save()
class Migration(migrations.Migration):
dependencies =... |
d8d2e4b763fbd7cedc42046f6f45395bf15caa79 | samples/plugins/scenario/scenario_plugin.py | samples/plugins/scenario/scenario_plugin.py |
from rally.task.scenarios import base
class ScenarioPlugin(base.Scenario):
"""Sample plugin which lists flavors."""
@base.atomic_action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients and self.clients ... |
from rally.plugins.openstack import scenario
from rally.task import atomic
class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
@atomic.action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.... | Fix the scenario plugin sample | Fix the scenario plugin sample
We forgot to fix scenario plugin sample when we were doing
rally.task.scenario refactoring
Change-Id: Iadbb960cf168bd3b9cd6c1881a5f7a8dffd7036f
| Python | apache-2.0 | group-policy/rally,eayunstack/rally,openstack/rally,amit0701/rally,paboldin/rally,eonpatapon/rally,cernops/rally,afaheem88/rally,yeming233/rally,vganapath/rally,gluke77/rally,aforalee/RRally,yeming233/rally,openstack/rally,gluke77/rally,gluke77/rally,eayunstack/rally,openstack/rally,aforalee/RRally,cernops/rally,group-... |
- from rally.task.scenarios import base
+ from rally.plugins.openstack import scenario
+ from rally.task import atomic
- class ScenarioPlugin(base.Scenario):
+ class ScenarioPlugin(scenario.OpenStackScenario):
"""Sample plugin which lists flavors."""
- @base.atomic_action_timer("list_flavors")
+ ... | Fix the scenario plugin sample | ## Code Before:
from rally.task.scenarios import base
class ScenarioPlugin(base.Scenario):
"""Sample plugin which lists flavors."""
@base.atomic_action_timer("list_flavors")
def _list_flavors(self):
"""Sample of usage clients - list flavors
You can use self.context, self.admin_clients a... |
68a621005c5a520b7a97c4cad462d43fb7f3aaed | paws/views.py | paws/views.py |
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
request = Request(event, context)
resp = self.prepare(request)
if resp:
return resp
kwargs = event.get('path... |
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
kwargs = event.get('pathParameters') or {}
self.dispatch(request, **kwargs)
def dispatch(self, request, **kwargs):
func = g... | Break out dispatch, and drop prepare. Easier testing | Break out dispatch, and drop prepare. Easier testing
| Python | bsd-3-clause | funkybob/paws |
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
- request = Request(event, context)
- resp = self.prepare(request)
- if resp:
- return resp
... | Break out dispatch, and drop prepare. Easier testing | ## Code Before:
from .request import Request
from .response import Response, response
import logging
log = logging.getLogger()
class View:
def __call__(self, event, context):
request = Request(event, context)
resp = self.prepare(request)
if resp:
return resp
kwargs =... |
d4d448adff71b609d5efb269d1a9a2ea4aba3590 | radio/templatetags/radio_js_config.py | radio/templatetags/radio_js_config.py | import random
import json
from django import template
from django.conf import settings
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_settings:
fo... | import random
import json
from django import template
from django.conf import settings
from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_jso... | Allow SiteOption to load into the JS | Allow SiteOption to load into the JS
| Python | mit | ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player | import random
import json
from django import template
from django.conf import settings
+
+ from radio.models import SiteOption
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS... | Allow SiteOption to load into the JS | ## Code Before:
import random
import json
from django import template
from django.conf import settings
register = template.Library()
# Build json value to pass as js config
@register.simple_tag()
def trunkplayer_js_config(user):
js_settings = getattr(settings, 'JS_SETTINGS', None)
js_json = {}
if js_sett... |
0a13a9a8a779102dbcb2beead7d8aa9143f4c79b | tests/pytests/unit/client/ssh/test_shell.py | tests/pytests/unit/client/ssh/test_shell.py | import os
import subprocess
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
@pytest.mark.skip_on_windows(reason="Windows ... | import subprocess
import types
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key)
@pytest.mark.skip_on_windows(reason=... | Use commit suggestion to use types | Use commit suggestion to use types
Co-authored-by: Pedro Algarvio <4410d99cefe57ec2c2cdbd3f1d5cf862bb4fb6f8@algarvio.me>
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | - import os
import subprocess
+ import types
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
- yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
+ re... | Use commit suggestion to use types | ## Code Before:
import os
import subprocess
import pytest
import salt.client.ssh.shell as shell
@pytest.fixture
def keys(tmp_path):
pub_key = tmp_path / "ssh" / "testkey.pub"
priv_key = tmp_path / "ssh" / "testkey"
yield {"pub_key": str(pub_key), "priv_key": str(priv_key)}
@pytest.mark.skip_on_windows(... |
09d780474d00f3a8f4c2295154d74dae2023c1d3 | samples/storage_sample/storage/__init__.py | samples/storage_sample/storage/__init__.py | """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| Drop the CLI from the sample storage client imports. | Drop the CLI from the sample storage client imports.
| Python | apache-2.0 | cherba/apitools,craigcitro/apitools,b-daniels/apitools,betamos/apitools,kevinli7/apitools,houglum/apitools,pcostell/apitools,thobrla/apitools,google/apitools | """Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
- from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| Drop the CLI from the sample storage client imports. | ## Code Before:
"""Common imports for generated storage client library."""
# pylint:disable=wildcard-import
import pkgutil
from apitools.base.py import *
from storage_v1 import *
from storage_v1_client import *
from storage_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
## Instruction:
Drop... |
08d838e87bd92dacbbbfe31b19c628b9d3b271a8 | src/plone.example/plone/example/todo.py | src/plone.example/plone/example/todo.py | from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapt... | from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapt... | Set default values for fields | Set default values for fields
| Python | bsd-2-clause | plone/plone.server,plone/plone.server | from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDCAn... | Set default values for fields | ## Code Before:
from plone.dexterity.interfaces import IDexterityContent
from plone.dexterity.interfaces import IFormFieldProvider
from plone.server.api.service import Service
from plone.supermodel import model
from zope import schema
from zope.component import adapter
from zope.dublincore.annotatableadapter import ZDC... |
29a964a64230e26fca550e81a1ecba3dd782dfb1 | python/vtd.py | python/vtd.py | import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
| import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
if 'my_system' not in globals():
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
my_system.Refresh()
| Refresh system instead of clobbering it | Refresh system instead of clobbering it
Otherwise, if we set the Contexts, they'll be gone before we can request the
NextActions!
| Python | apache-2.0 | chiphogg/vim-vtd | import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
+ if 'my_system' not in globals():
- my_system = libvtd.trusted_system.TrustedSystem()
+ my_system = libvtd.trusted_system.TrustedSystem()
- ... | Refresh system instead of clobbering it | ## Code Before:
import libvtd.trusted_system
def UpdateTrustedSystem(file_name):
"""Make sure the TrustedSystem object is up to date."""
global my_system
my_system = libvtd.trusted_system.TrustedSystem()
my_system.AddFile(file_name)
## Instruction:
Refresh system instead of clobbering it
## Code Afte... |
b532ffff18e95b6014921d88b6df075e8ac2c4ec | problib/example1/__init__.py | problib/example1/__init__.py | from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers... | from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three random integers... | Update mathdeck problib for new Answer refactoring | Update mathdeck problib for new Answer refactoring
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck | from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# ... | Update mathdeck problib for new Answer refactoring | ## Code Before:
from sympy import symbols, cos, sin, latex
from mathdeck import rand, answer
metadata = {
'author': 'Bob Hope',
'institution': 'University of Missouri',
'subject': 'algebra',
'minor subject': 'polynomial equations',
'tags': ['simplify','roots','intervals']
}
r = rand.Random()
# choose three... |
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.P... | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.P... | Fix zulipinternal migration corner case. | migrations: Fix zulipinternal migration corner case.
It's theoretically possible to have configured a Zulip server where
the system bots live in the same realm as normal users (and may have
in fact been the default in early Zulip releases? Unclear.). We
should handle these without the migration intended to clean up ... | Python | apache-2.0 | brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,br... | from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
i... | Fix zulipinternal migration corner case. | ## Code Before:
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
i... |
97e3b202bbe6726a4056facb8b4690b0710029a9 | handroll/tests/test_site.py | handroll/tests/test_site.py |
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, 'template.html'), 'w').close()... |
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = os.path.realpath(tempfile.mkdtemp())
open(os.path.join(valid_site, 'template.ht... | Use a real path when testing sites. | Use a real path when testing sites.
Mac OS X returns link paths when calling `mkdtemp`. Calling realpath
allows the site path comparison to be consistent across platforms.
| Python | bsd-2-clause | handroll/handroll |
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
- valid_site = tempfile.mkdtemp()
+ valid_site = os.path.realpath(te... | Use a real path when testing sites. | ## Code Before:
import os
import tempfile
from handroll.site import Site
from handroll.tests import TestCase
class TestSite(TestCase):
def test_finds_valid_site_root_from_templates(self):
original = os.getcwd()
valid_site = tempfile.mkdtemp()
open(os.path.join(valid_site, 'template.html... |
7e44a8bd38105144111624710819a1ee54891222 | campos_checkin/__openerp__.py | campos_checkin/__openerp__.py |
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
... |
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transportation',
... | Fix order for menu ref | Fix order for menu ref | Python | agpl-3.0 | sl2017/campos |
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_... | Fix order for menu ref | ## Code Before:
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
'website': 'www.steingabelgaard.dk',
'depends': [
'campos_jobber_final',
'campos_transpor... |
3cd99c23099a625da711e3ac458a46a7b364d83c | hystrix/pool.py | hystrix/pool.py | from __future__ import absolute_import
from concurrent.futures import ThreadPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cls... | from __future__ import absolute_import
from concurrent.futures import ProcessPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
if name in cl... | Change Pool to use ProcessPoolExecutor | Change Pool to use ProcessPoolExecutor
| Python | apache-2.0 | wiliamsouza/hystrix-py,wiliamsouza/hystrix-py | from __future__ import absolute_import
- from concurrent.futures import ThreadPoolExecutor
+ from concurrent.futures import ProcessPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'Poo... | Change Pool to use ProcessPoolExecutor | ## Code Before:
from __future__ import absolute_import
from concurrent.futures import ThreadPoolExecutor
import logging
import six
log = logging.getLogger(__name__)
class PoolMetaclass(type):
__instances__ = dict()
__blacklist__ = ('Pool', 'PoolMetaclass')
def __new__(cls, name, bases, attrs):
... |
c52edc120f38acb079fa364cdb684fc2052d4727 | corehq/messaging/smsbackends/trumpia/urls.py | corehq/messaging/smsbackends/trumpia/urls.py | from django.conf.urls import url
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
name=TrumpiaIncomingView.urlname),
]
| from django.conf.urls import url
from corehq.apps.hqwebapp.decorators import waf_allow
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()),
name=TrumpiaIncomingView.urlna... | Annotate trumpia url to say it allows XML in the querystring | Annotate trumpia url to say it allows XML in the querystring
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from django.conf.urls import url
+
+ from corehq.apps.hqwebapp.decorators import waf_allow
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
- url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
+ url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow(... | Annotate trumpia url to say it allows XML in the querystring | ## Code Before:
from django.conf.urls import url
from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView
urlpatterns = [
url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(),
name=TrumpiaIncomingView.urlname),
]
## Instruction:
Annotate trumpia url to say it allows XML in ... |
d159f8201b9d9aeafd24f07a9e39855fc537182d | cocoscore/tools/data_tools.py | cocoscore/tools/data_tools.py | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame will be sorted ... | import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data... | Add match_distance flag to load_data_frame() | Add match_distance flag to load_data_frame()
| Python | mit | JungeAlexander/cocoscore | import pandas as pd
- def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
+ def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path:... | Add match_distance flag to load_data_frame() | ## Code Before:
import pandas as pd
def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True):
"""
Load a sentence data set as pandas DataFrame from a given path.
:param data_frame_path: the path to load the pandas DataFrame from
:param sort_reindex: if True, the returned data frame... |
920e2fbb7e99c17dbe8d5b71e9c9b26a718ca444 | ideascube/search/apps.py | ideascube/search/apps.py | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
if isinstanc... | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reinde... | Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
Django run (pre|post)_migrate script once per database.
As we have two databases, the create_index is launch twice with different
kwargs['using'] ('default' and 'transient'). We should try to create
the index table only when we are wor... | Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
- if isinstance(sender, SearchConfig):
+ if (kwargs['using'] == 'transient' and isinstance(sender, SearchCo... | Make (pre|post)_migrate scripts for the index table only if working on 'transient'. | ## Code Before:
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if isinstance(sender, SearchConfig):
create_index_table(force=True)
def reindex(sender, **kwargs):
... |
360efe51bc45f189c235bed6b2b7bfdd4fd1bfbd | flask-restful/api.py | flask-restful/api.py | from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):
def post(se... | import json
from bottle import route, run, request, post, default_app
from indra import trips, reach, bel, biopax
from indra.statements import *
@route('/trips/process_text', method='POST')
def trips_process_text():
body = json.load(request.body)
text = body.get('text')
tp = trips.process_text(text)
i... | Reimplement using bottle and add 3 endpoints | Reimplement using bottle and add 3 endpoints
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra | - from flask import Flask, request
- from flask_restful import Resource, Api, reqparse
- from indra import reach
+ import json
+ from bottle import route, run, request, post, default_app
+ from indra import trips, reach, bel, biopax
from indra.statements import *
- import json
- app = Flask(__name__)
- api = Api(a... | Reimplement using bottle and add 3 endpoints | ## Code Before:
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from indra import reach
from indra.statements import *
import json
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('txt')
parser.add_argument('json')
class InputText(Resource):... |
e78910c8b9ecf48f96a693dae3c15afa32a12da1 | casexml/apps/phone/views.py | casexml/apps/phone/views.py | from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):
user = User... | from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
... | Revert "moving httpresponse to view" | Revert "moving httpresponse to view"
This reverts commit a6f501bb9de6382e35372996851916adac067fa0.
| Python | bsd-3-clause | SEL-Columbia/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,di... | + from django.http import HttpResponse
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
... | Revert "moving httpresponse to view" | ## Code Before:
from django_digest.decorators import *
from casexml.apps.phone import xml
from casexml.apps.case.models import CommCareCase
from casexml.apps.phone.restore import generate_restore_response
from casexml.apps.phone.models import User
from casexml.apps.case import const
@httpdigest
def restore(request):... |
63f6e4d50116d5ca2bfc82c1c608e08040055b5e | subdue/core/__init__.py | subdue/core/__init__.py | __all__ = [
'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_|... | __all__ = [
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| | |_) | (_| | |_| | __/
|___/\__,_|_.__/ \__,_|... | Remove old exports from subdue.core | Remove old exports from subdue.core
| Python | mit | jdevera/subdue | __all__ = [
- 'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
- 'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |... | Remove old exports from subdue.core | ## Code Before:
__all__ = [
'color',
'BANNER',
'DEFAULT_DRIVER_CODE'
'die',
'verbose',
'use_colors',
'set_color_policy',
]
import sys as _sys
from . import color as _color
BANNER = """\
_ _
___ _ _| |__ __| |_ _ ___
/ __| | | | '_ \ / _` | | | |/ _ \\
\__ \ |_| |... |
459bf08b9fe4ae5a879a138bd2497abb23bf5910 | modules/expansion/cve.py | modules/expansion/cve.py | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveapi_ur... | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfig = []
cveap... | Return a text attribute for an hover only module | Return a text attribute for an hover only module
| Python | agpl-3.0 | VirusTotal/misp-modules,MISP/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,Rafiot/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules | import json
import requests
misperrors = {'error': 'Error'}
- mispattributes = {'input': ['vulnerability'], 'output': ['']}
+ mispattributes = {'input': ['vulnerability'], 'output': ['text']}
- moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand i... | Return a text attribute for an hover only module | ## Code Before:
import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['vulnerability'], 'output': ['']}
moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion hover module to expand information about CVE id.', 'module-type': ['hover']}
moduleconfi... |
03380a1042443465d6f1d74afb5fd120dbc3379b | manage.py | manage.py | from manager import Manager
manager = Manager()
@manager.command
def build(threads=1):
print("Starting a build with %d threads ..." % threads)
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
| from manager import Manager
from multiprocessing import Pool
manager = Manager()
def func(period):
from time import sleep
sleep(period)
@manager.command
def build(threads=1):
pool = Pool(threads)
print("Starting a build with %d threads ..." % threads)
pool.map(func, [1, 1, 1, 1, 1])
@manager.... | Add parallelizing code to build | Add parallelizing code to build
| Python | mit | tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website,tanayseven/personal_website | from manager import Manager
+ from multiprocessing import Pool
manager = Manager()
+ def func(period):
+ from time import sleep
+ sleep(period)
+
+
@manager.command
def build(threads=1):
+ pool = Pool(threads)
print("Starting a build with %d threads ..." % threads)
+ pool.map(fu... | Add parallelizing code to build | ## Code Before:
from manager import Manager
manager = Manager()
@manager.command
def build(threads=1):
print("Starting a build with %d threads ..." % threads)
@manager.command
def clean():
pass
if __name__ == '__main__':
manager.main()
## Instruction:
Add parallelizing code to build
## Code After:
fro... |
a5003b6f45d262923a1c00bd9a9c1addb3854178 | lapostesdk/apis/apibase.py | lapostesdk/apis/apibase.py | import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
... | import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % {
... | Move object creation outside of get method | Move object creation outside of get method
| Python | mit | geelweb/laposte-python-sdk | import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(ve... | Move object creation outside of get method | ## Code Before:
import requests
from importlib import import_module
class ApiBase(object):
def __init__(self, api_key, product, version='v1', entity=None):
self.product = product
self.version = version
self.entity = entity
self.api_url = 'https://api.laposte.fr/%(product)s/%(versio... |
1b385ce127f0a1802b0effa0054b44f58b3317b0 | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/accounts/urls.py | from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
... | from django.contrib.auth import views
from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
na... | Fix webapp password reset link | DEVOPS-42: Fix webapp password reset link
| Python | isc | thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template | from django.contrib.auth import views
- from django.urls import path, re_path
+ from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/lo... | Fix webapp password reset link | ## Code Before:
from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginF... |
9b10f600b5611380f72fe2aeacfe2ee6f02e4e3a | kicad_footprint_load.py | kicad_footprint_load.py | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] ==... | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] ==... | Switch to old invocation of FootprintEnumerate | Switch to old invocation of FootprintEnumerate
| Python | mit | monostable/haskell-kicad-data,monostable/haskell-kicad-data,kasbah/haskell-kicad-data | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.s... | Switch to old invocation of FootprintEnumerate | ## Code Before:
import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(... |
f5fd283497afb5030632108ce692e8acde526188 | datalake_ingester/reporter.py | datalake_ingester/reporter.py | import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
... | import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_key = report_key
self.logger = logging.getLogger(self._log_name)
@... | Allow the ingester to work without a report key | Allow the ingester to work without a report key
| Python | apache-2.0 | planetlabs/datalake-ingester,planetlabs/atl,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake,planetlabs/datalake | import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
- from datalake_common.errors import InsufficientConfiguration
-
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
sel... | Allow the ingester to work without a report key | ## Code Before:
import boto.sns
import simplejson as json
import logging
from memoized_property import memoized_property
import os
from datalake_common.errors import InsufficientConfiguration
class SNSReporter(object):
'''report ingestion events to SNS'''
def __init__(self, report_key):
self.report_k... |
f45fc8854647754b24df5f9601920368cd2d3c49 | tests/chainerx_tests/unit_tests/test_cuda.py | tests/chainerx_tests/unit_tests/test_cuda.py | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs)... | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess(self, **kwargs)... | Add safety checks in test | Add safety checks in test
| Python | mit | wkentaro/chainer,hvy/chainer,niboshi/chainer,okuta/chainer,chainer/chainer,wkentaro/chainer,chainer/chainer,keisuke-umezawa/chainer,keisuke-umezawa/chainer,hvy/chainer,pfnet/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,okuta/chainer,chainer/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer... | import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
... | Add safety checks in test | ## Code Before:
import pytest
from chainerx import _cuda
try:
import cupy
except Exception:
cupy = None
class CupyTestMemoryHook(cupy.cuda.memory_hook.MemoryHook):
name = 'CupyTestMemoryHook'
def __init__(self):
self.used_bytes = 0
self.acquired_bytes = 0
def alloc_preprocess... |
429f38497da0fd520e5bc5bd82e6d4ed5a405521 | real_estate_agency/real_estate_agency/views.py | real_estate_agency/real_estate_agency/views.py | from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request... | from django.shortcuts import render
from new_buildings.models import ResidentalComplex
from new_buildings.forms import NewBuildingsSearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
return render(request, 'corporation_benefit_plan.html')
def index(request):
# Only 2 requ... | Use NewBuildingsSearchForm as main page search form. | Use NewBuildingsSearchForm as main page search form.
intead of non-complete SearchForm.
| Python | mit | Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency | - from django.shortcuts import render, render_to_response
+ from django.shortcuts import render
- from django.template import RequestContext
- from new_buildings.models import Builder, ResidentalComplex, NewApartment
+ from new_buildings.models import ResidentalComplex
- from new_buildings.forms import SearchForm
+ ... | Use NewBuildingsSearchForm as main page search form. | ## Code Before:
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
def corporation_benefit_plan(request):
retur... |
fe317230b6d2636b8a736c63be7769dd82663914 | libraries/SwitchManager.py | libraries/SwitchManager.py | class SwitchManager(object):
def extract_all_nodes(self, content):
return [e['node'] for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
| class SwitchManager(object):
def extract_all_nodes(self, content):
"""
Return all nodes.
"""
if isinstance(content,dict) or not content.has_key('nodeProperties'):
return None
else:
return [e.get('node') for e in content['nodeProperties']]
def extr... | Add input check when getting all nodes. | Add input check when getting all nodes.
| Python | epl-1.0 | yeasy/robot_tool | class SwitchManager(object):
def extract_all_nodes(self, content):
+ """
+ Return all nodes.
+ """
+ if isinstance(content,dict) or not content.has_key('nodeProperties'):
+ return None
+ else:
- return [e['node'] for e in content['nodeProperties']]
+ ... | Add input check when getting all nodes. | ## Code Before:
class SwitchManager(object):
def extract_all_nodes(self, content):
return [e['node'] for e in content['nodeProperties']]
def extract_all_properties(self, content):
pass
## Instruction:
Add input check when getting all nodes.
## Code After:
class SwitchManager(object):
def e... |
99177cdc64bdec740557007800b610bff07ce46a | shivyc.py | shivyc.py |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of ... |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of ... | Improve commenting on main function | Improve commenting on main function
| Python | mit | ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files."... | Improve commenting on main function | ## Code Before:
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# T... |
a34c9628c3f383e7b6f5eb521a9493f2b51d8811 | plata/reporting/views.py | plata/reporting/views.py | from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
... | from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.reporting.order
... | Remove hardcoded shipping modification in order PDF view | Remove hardcoded shipping modification in order PDF view
| Python | bsd-3-clause | stefanklug/plata,armicron/plata,armicron/plata,allink/plata,armicron/plata | from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import... | Remove hardcoded shipping modification in order PDF view | ## Code Before:
from decimal import Decimal
import StringIO
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from pdfdocument.utils import pdf_response
import plata
import plata.reporting.product
import plata.r... |
7b1a0022b41dbf17de352e4686458e5250b28e49 | quantityfield/widgets.py | quantityfield/widgets.py | import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=No... | import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init__(self, attrs=No... | Fix indentation error from conversion to spaces | Fix indentation error from conversion to spaces
| Python | mit | bharling/django-pint,bharling/django-pint | import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
... | Fix indentation error from conversion to spaces | ## Code Before:
import re
from django.forms.widgets import MultiWidget, Select, NumberInput
from . import ureg
class QuantityWidget(MultiWidget):
def get_choices(self, allowed_types=None):
allowed_types = allowed_types or dir(ureg)
return [(x, x) for x in allowed_types]
def __init_... |
9ced61716167505875d3938ae01c08b61acc9392 | randterrainpy/terrain.py | randterrainpy/terrain.py | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map... | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height_map (list): Map... | Add addition method to Terrain | Add addition method to Terrain
| Python | mit | jackromo/RandTerrainPy | """This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
he... | Add addition method to Terrain | ## Code Before:
"""This module is for the Terrain class, used for storing randomly generated terrain."""
class Terrain(object):
"""Container for a randomly generated area of terrain.
Attributes:
width (int): Width of generated terrain.
length (int): Length of generated terrain.
height... |
2e845dfd2695b1913f4603d88039049fa1eef923 | repositories.py | repositories.py | repositories = [
{
"owner": "talk-to",
"name": "Knock"
}
] | REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] | Use capitalised name for constant | Use capitalised name for constant
| Python | mit | ayushgoel/LongShot | - repositories = [
+ REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] | Use capitalised name for constant | ## Code Before:
repositories = [
{
"owner": "talk-to",
"name": "Knock"
}
]
## Instruction:
Use capitalised name for constant
## Code After:
REPOSITORIES = [
{
"owner": "talk-to",
"name": "Knock"
}
] |
aa7109d038a86f6a19a9fb4af96bd1199cd81330 | functest/opnfv_tests/openstack/snaps/snaps_utils.py | functest/opnfv_tests/openstack/snaps/snaps_utils.py |
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_utils.get_external... |
from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the configured external network name or
the first retrieved external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
... | Support to specify the valid external network name | Support to specify the valid external network name
In some deployments, the retrieved external network by the
def get_external_networks in Snaps checked by "router:external"
is not available. So it is necessary to specify the available
external network as an env by user.
Change-Id: I333e91dd106ed307541a9a197280199fde... | Python | apache-2.0 | opnfv/functest,mywulin/functest,opnfv/functest,mywulin/functest | +
+ from functest.utils.constants import CONST
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
- Returns the first external network name
+ Returns the configured external network name or
+ the first retrieved external network name
:pa... | Support to specify the valid external network name | ## Code Before:
from snaps.openstack.utils import neutron_utils, nova_utils
def get_ext_net_name(os_creds):
"""
Returns the first external network name
:param: os_creds: an instance of snaps OSCreds object
:return:
"""
neutron = neutron_utils.neutron_client(os_creds)
ext_nets = neutron_ut... |
acd4238dce39464e99964227dca7758cffedca39 | gaphor/UML/classes/tests/test_containmentconnect.py | gaphor/UML/classes/tests/test_containmentconnect.py | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue to two packa... | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment glue t... | Add test for connecting containment to package and a class | Add test for connecting containment to package and a class [skip ci]
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | """Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
- from gaphor.UML.classes import PackageItem
+ from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_c... | Add test for connecting containment to package and a class | ## Code Before:
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.diagram.tests.fixtures import allow, connect
from gaphor.UML.classes import PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment_package_glue(create):
"""Test containment g... |
413ba364dc35a7186953d02bb7cc8cf705371873 | contentious/constants.py | contentious/constants.py | from django.conf import settings
SELF_CLOSING_HTML_TAGS = getattr(settings,
'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'sele... | from django.conf import settings
SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta']
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS', ['div', 'select', 'ul'])
| Remove SELF_CLOSING_HTML_TAGS as a configurable option | Remove SELF_CLOSING_HTML_TAGS as a configurable option
| Python | bsd-2-clause | potatolondon/contentious,potatolondon/contentious | from django.conf import settings
- SELF_CLOSING_HTML_TAGS = getattr(settings,
- 'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
+ SELF_CLOSING_HTML_TAGS = ['img', 'br', 'hr', 'meta']
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = geta... | Remove SELF_CLOSING_HTML_TAGS as a configurable option | ## Code Before:
from django.conf import settings
SELF_CLOSING_HTML_TAGS = getattr(settings,
'CONTENTIOUS_SELF_CLOSING_HTML_TAGS', ['img', 'br', 'hr', 'meta'])
#Note, the Javascript plugin has its own seprate copy of this:
TREAT_CONTENT_AS_HTML_TAGS = getattr(settings,
'CONTENTIOUS_TREAT_CONTENT_AS_HTML_TAGS... |
182cd3b73382bb150111198e5fcbfa43a6bd416f | cbagent/collectors/libstats/typeperfstats.py | cbagent/collectors/libstats/typeperfstats.py | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typ... | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typeperf_cmd = "typ... | Add missing methods to TPStats | Add missing methods to TPStats
Change-Id: I332a83f3816ee30597288180ed344da3161861f8
Reviewed-on: http://review.couchbase.org/79675
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
| Python | apache-2.0 | pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner | from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
... | Add missing methods to TPStats | ## Code Before:
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task
class TPStats(RemoteStats):
METRICS = (
("rss", 1), # already in bytes
)
def __init__(self, hosts, workers, user, password):
super().__init__(hosts, workers, user, password)
self.typ... |
c45fc698da9783b561cca69363ec4998622e9ac0 | mint/rest/db/capsulemgr.py | mint/rest/db/capsulemgr.py |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.configLine("store sql... |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
dbDriver = self.db.db.dri... | Use the mint database for capsule data | Use the mint database for capsule data
| Python | apache-2.0 | sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint |
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
- cfg... | Use the mint database for capsule data | ## Code Before:
from conary.lib import util
from mint.rest.db import manager
import rpath_capsule_indexer
class CapsuleManager(manager.Manager):
def getIndexerConfig(self):
capsuleDataDir = util.joinPaths(self.cfg.dataPath, 'capsules')
cfg = rpath_capsule_indexer.IndexerConfig()
cfg.confi... |
21059428d95c27cf043ada2e299a4cf3982a4233 | python/printbag.py | python/printbag.py |
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def decode_bag... |
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag
def print_bag(... | Print out bag contents for lidar and button topics | Print out bag contents for lidar and button topics
| Python | bsd-2-clause | oliverlee/antlia |
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
i... | Print out bag contents for lidar and button topics | ## Code Before:
"""LIDAR datatype format is:
(
timestamp (long),
flag (bool saved as int),
accelerometer[3] (double),
gps[3] (double),
distance[LIDAR_NUM_ANGLES] (long),
)
'int' and 'long' are the same size on the raspberry pi (32 bits).
"""
import sys
import rosbag... |
78cca16df6a5cdd90ec92e64455215c4b7292fae | report_coverage.py | report_coverage.py | import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
... | import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
js_report = []
... | Sort line coverage info when reporting | Sort line coverage info when reporting
| Python | apache-2.0 | exekias/django-achilles,exekias/django-achilles | import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))... | Sort line coverage info when reporting | ## Code Before:
import json
import os
import sys
from coveralls import Coveralls, cli
# Patch coveralls to get javascript coverage from mocha
orig_get_coverage = Coveralls.get_coverage
def get_coverage_with_js(self):
report = orig_get_coverage(self)
js_files = json.load(open('.coverage-js'))['files']
... |
4ae8302a3d91ca1e9601e0c51cb58a69f1c08cb5 | setup.py | setup.py | """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutil... | """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[1:-1]
distutil... | Remove 'bibpy.parsers' from package list | Remove 'bibpy.parsers' from package list
| Python | mit | MisanthropicBit/bibpy,MisanthropicBit/bibpy | """bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1... | Remove 'bibpy.parsers' from package list | ## Code Before:
"""bibpy module setup script for distribution."""
from __future__ import with_statement
import os
import distutils.core
def get_version(filename):
with open(filename) as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip()[... |
73f7502f1fda11bc23469c6f3e8f79b0e375c928 | setup.py | setup.py |
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='oleg@bsdpower.com',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
)
|
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='oleg@bsdpower.com',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
data_files=['LICENSE', 'README.rst'],
)
| Add license and readme to the packages | Add license and readme to the packages
| Python | bsd-2-clause | hyunchel/redis-dump-load,p/redis-dump-load,p/redis-dump-load,hyunchel/redis-dump-load |
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='oleg@bsdpower.com',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
+ data_files=['LICENS... | Add license and readme to the packages | ## Code Before:
from distutils.core import setup
setup(name='redis-dump-load',
version='0.2.0',
description='Dump and load redis databases',
author='Oleg Pudeyev',
author_email='oleg@bsdpower.com',
url='http://github.com/p/redis-dump-load',
py_modules=['redisdl'],
)
## Instruction:
Add licens... |
c987ed375da13f53928157f14528bed0c148eeac | tasks.py | tasks.py | import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambda: func(*args, *... | import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
asyncio.set_event_loop(cls.loop)
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
... | Set implicit loop for Python <3.6 | Set implicit loop for Python <3.6 | Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
+ asyncio.set_event_loop(cls.loop)
+
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do... | Set implicit loop for Python <3.6 | ## Code Before:
import asyncio
import threading
class Tasks:
loop = asyncio.new_event_loop()
@classmethod
def _run(cls):
try:
cls.loop.run_forever()
finally:
cls.loop.close()
@classmethod
def do(cls, func, *args, **kwargs):
cls.loop.call_soon(lambd... |
7dcd2c2aa1e2fd8f17e0b564f9b77375675ccd9a | metakernel/pexpect.py | metakernel/pexpect.py | from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
| from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import spawn
import pty
except ImportError:
pty = None
def which(filename):
'''This takes a given filename; tries to find it in the environment path;
then c... | Add handling of which on Windows | Add handling of which on Windows
| Python | bsd-3-clause | Calysto/metakernel | from __future__ import absolute_import
- from pexpect import spawn, which, EOF, TIMEOUT
+ from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
+ import os
+ try:
+ from pexpect import spawn
+ import pty
+ except ImportError:
+ pty = None
+
+
+ def which(filename):
+ '''This t... | Add handling of which on Windows | ## Code Before:
from __future__ import absolute_import
from pexpect import spawn, which, EOF, TIMEOUT
## Instruction:
Add handling of which on Windows
## Code After:
from __future__ import absolute_import
from pexpect import which as which_base, is_executable_file, EOF, TIMEOUT
import os
try:
from pexpect import ... |
6defa096b3dae109bf50ab32cdee7062c8b4327b | _python/config/settings/settings_pytest.py | _python/config/settings/settings_pytest.py |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
|
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | Add placeholder CAPAPI key for tests.
| Python | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o |
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
+ CAPAPI_API_KEY = '12345'
| Add placeholder CAPAPI key for tests. | ## Code Before:
from .settings_dev import *
# Don't use whitenoise for tests. Including whitenoise causes it to rescan static during each test, which greatly
# increases test time.
MIDDLEWARE.remove('whitenoise.middleware.WhiteNoiseMiddleware')
## Instruction:
Add placeholder CAPAPI key for tests.
## Code After:
f... |
d413747e996326e62fdf942426f170f66d5acb7c | osf_tests/test_preprint_summary.py | osf_tests/test_preprint_summary.py | import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint... | import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixture()
def preprint... | Make sure test dates are rounded properly by making they are over a day in the past. | Make sure test dates are rounded properly by making they are over a day in the past.
| Python | apache-2.0 | binoculars/osf.io,TomBaxter/osf.io,sloria/osf.io,adlius/osf.io,Johnetordoff/osf.io,mattclark/osf.io,adlius/osf.io,sloria/osf.io,HalcyonChimera/osf.io,adlius/osf.io,laurenrevere/osf.io,erinspace/osf.io,sloria/osf.io,binoculars/osf.io,mfraezz/osf.io,TomBaxter/osf.io,icereval/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,crc... | import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@p... | Make sure test dates are rounded properly by making they are over a day in the past. | ## Code Before:
import datetime
from osf_tests.factories import PreprintFactory, PreprintProviderFactory
from osf.models import PreprintService
from nose.tools import * # PEP8 asserts
import mock
import pytest
import pytz
import requests
from scripts.analytics.preprint_summary import PreprintSummary
@pytest.fixtur... |
7d6ad23cd8435eac9b48a4ea63bb9a2e83239c4a | scent.py | scent.py |
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# All lists in this... | from __future__ import unicode_literals
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = t... | Fix sniffer support for python 3.x | Fix sniffer support for python 3.x
| Python | bsd-3-clause | thomasballinger/tmuxp,thomasballinger/tmuxp,mexicarne/tmuxp,tony/tmuxp,mexicarne/tmuxp | + from __future__ import unicode_literals
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = terms... | Fix sniffer support for python 3.x | ## Code Before:
import os
import termstyle
from sniffer.api import file_validator, runnable
from tmuxp.testsuite import main
# you can customize the pass/fail colors like this
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
# A... |
ec96c3173a770949c13e560b16272bc265a80da4 | setup.py | setup.py |
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
|
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
packages=['mass_api_client', ],
)
| Add mass_api_client as Package; fix typo | Add mass_api_client as Package; fix typo
| Python | mit | mass-project/mass_api_client,mass-project/mass_api_client |
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
- install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
+ install_requires=['requests==2.13.0', 'marshmallow==2.12.2'],
+ packages=['mass_api_client', ],
+ )
| Add mass_api_client as Package; fix typo | ## Code Before:
from distutils.core import setup
setup(name='mass_api_client',
version=0.1,
install_required=['requests==2.13.0', 'marshmallow==2.12.2'])
## Instruction:
Add mass_api_client as Package; fix typo
## Code After:
from distutils.core import setup
setup(name='mass_api_client',
version=... |
596613c964311104098e64eeb349216bc7cd0023 | saleor/demo/views.py | saleor/demo/views.py | from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax... | from django.conf import settings
from django.shortcuts import render
from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
# and live syntax and valid... | Fix playground CSP for demo if deployed under proxied domain | Fix playground CSP for demo if deployed under proxied domain
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | from django.conf import settings
from django.shortcuts import render
- from ..graphql.views import API_PATH, GraphQLView
+ from ..graphql.views import GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeahead... | Fix playground CSP for demo if deployed under proxied domain | ## Code Before:
from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
#
# Type queries into this side of the screen, and you will see
# intelligent typeaheads aware of the current GraphQL type schema
#... |
53594f372a45e425076e5dbf36f399503df1972c | salt/output/yaml_out.py | salt/output/yaml_out.py | '''
YAML Outputter
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML
'''
return yaml.dump(data)
| '''
Output data in YAML, this outputter defaults to printing in YAML block mode
for better readability.
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML using the block mode
'''
return yaml.dump(data, default_flow_style=False)
| Change the YAML outputter to use block mode and add some docs | Change the YAML outputter to use block mode and add some docs
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
- YAML Outputter
+ Output data in YAML, this outputter defaults to printing in YAML block mode
+ for better readability.
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
- Print out YAML
+ Print out YAML using the block mode
... | Change the YAML outputter to use block mode and add some docs | ## Code Before:
'''
YAML Outputter
'''
# Third Party libs
import yaml
def __virtual__():
return 'yaml'
def output(data):
'''
Print out YAML
'''
return yaml.dump(data)
## Instruction:
Change the YAML outputter to use block mode and add some docs
## Code After:
'''
Output data in YAML, this outp... |
eb5bcf3130f5fdc0d6be68e7e81555def46a53af | setup.py | setup.py | from distutils.core import setup
setup(
name = 'mstranslator',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = 'ayushgoel111@gmail.com',
url = 'https://github.com/ayushgoel/mstranslator... | from distutils.core import setup
setup(
name = 'mstranslator-2016',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = 'ayushgoel111@gmail.com',
url = 'https://github.com/ayushgoel/mstrans... | Update nemae and download URL | Update nemae and download URL
| Python | mit | ayushgoel/mstranslator | from distutils.core import setup
setup(
- name = 'mstranslator',
+ name = 'mstranslator-2016',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = 'ayushgoel111@gmail.com',
... | Update nemae and download URL | ## Code Before:
from distutils.core import setup
setup(
name = 'mstranslator',
packages = ['mstranslator'],
version = '0.0.1',
description = 'Python wrapper to consume Microsoft translator API',
author = 'Ayush Goel',
author_email = 'ayushgoel111@gmail.com',
url = 'https://github.com/ayushg... |
ccbe4a1c48765fdd9e785392dff949bcc49192a2 | setup.py | setup.py | from distutils.core import setup
setup(
name='Zinc',
version='0.1.7',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
include_package_data=True,
url='https:... | from distutils.core import setup
setup(
name='Zinc',
version='0.1.8',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'zinc/*']},
include_package_data=True,
url='https://github.c... | Remove readme from package data. | Remove readme from package data.
| Python | mit | wangjohn/zinc_cli | from distutils.core import setup
setup(
name='Zinc',
- version='0.1.7',
+ version='0.1.8',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
- package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
+ ... | Remove readme from package data. | ## Code Before:
from distutils.core import setup
setup(
name='Zinc',
version='0.1.7',
author='John Wang',
author_email='john@zinc.io',
packages=['zinc'],
package_dir={'zinc': ''},
package_data={'zinc': ['examples/*.py', 'examples/*.json', 'README', 'zinc/*']},
include_package_data=True,... |
7e88739d91cd7db35ffb36804ae59d1878eb2da3 | setup.py | setup.py | import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
packages = ['eventsocket'],
url='https://github.com/agoragames/py-events... | import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
url='https://github.com/agoragames/py-eventsocket',
license='LICENSE.txt... | Use py_modules and not packages | Use py_modules and not packages
| Python | bsd-3-clause | agoragames/py-eventsocket | import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
- packages = ['eventsocket'],
url='https://github.... | Use py_modules and not packages | ## Code Before:
import os
from distutils.core import setup
requirements = map(str.strip, open('requirements.txt').readlines())
setup(
name='py_eventsocket',
version='0.1.4',
author="Aaron Westendorf",
author_email="aaron@agoragames.com",
packages = ['eventsocket'],
url='https://github.com/agor... |
c0b9c9712e464f304bee7c63bfd6b197a1c5fb0f | cmsplugin_bootstrap_carousel/cms_plugins.py | cmsplugin_bootstrap_carousel/cms_plugins.py | import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class ... | import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelForm):
class ... | Change extra from 3 to 0. | Change extra from 3 to 0.
| Python | bsd-3-clause | 360youlun/cmsplugin-bootstrap-carousel,360youlun/cmsplugin-bootstrap-carousel | import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(Mode... | Change extra from 3 to 0. | ## Code Before:
import re
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_bootstrap_carousel.models import *
from django.utils.translation import ugettext as _
from django.contrib import admin
from django.forms import ModelForm, ValidationError
class CarouselForm(ModelF... |
554e79ada3f351ecb6287b08d0f7d1c4e5a5b5f6 | setup.py | setup.py |
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
maint... |
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica.org",
mainta... | Update version number to 1.0. | Update version number to 1.0.
| Python | bsd-3-clause | ceball/param,ioam/param |
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
- version='0.05',
+ version='1.0',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
autho... | Update version number to 1.0. | ## Code Before:
import sys
from distutils.core import setup
setup_args = {}
setup_args.update(dict(
name='param',
version='0.05',
description='Declarative Python programming using Parameters.',
long_description=open('README.txt').read(),
author= "IOAM",
author_email= "developers@topographica... |
81b6a138c476084f9ddd6063f31d3efd0ba6e2cf | start.py | start.py | import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argumen... | import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
parser.add_argumen... | Make the logging level configurable | Make the logging level configurable
| Python | mit | DesertBot/DesertBot | import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python... | Make the logging level configurable | ## Code Before:
import argparse
import logging
import os
import sys
from twisted.internet import reactor
from desertbot.config import Config, ConfigError
from desertbot.factory import DesertBotFactory
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='An IRC bot written in Python.')
pa... |
f13fc280f25996ec7f4924647fdc879779f51737 | project/tools/normalize.py | project/tools/normalize.py |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("c... |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.cell_type == ("c... | Allow two command arguments for in and out files, or none for standard filter operations | Allow two command arguments for in and out files, or none for standard filter operations
| Python | mit | holdenweb/nbtools,holdenweb/nbtools |
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
... | Allow two command arguments for in and out files, or none for standard filter operations | ## Code Before:
import os
import IPython.nbformat.current as nbf
from glob import glob
from lib import get_project_dir
import sys
def normalize(in_file, out_file):
worksheet = in_file.worksheets[0]
cell_list = []
# add graphic here & append to cell_list
for cell in worksheet.cells:
if cell.... |
7119930b662a20d9e9bbca230f8a6485efcb7c44 | flask_appconfig/middleware.py | flask_appconfig/middleware.py |
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_... |
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix {
proxy_... | Add __getattr__ passthrough on ReverseProxied. | Add __getattr__ passthrough on ReverseProxied.
| Python | mit | mbr/flask-appconfig |
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /mypre... | Add __getattr__ passthrough on ReverseProxied. | ## Code Before:
class ReverseProxied(object):
'''Wrap the application in this middleware and configure the
front-end server to add these headers, to let you quietly bind
this to a URL other than / and to an HTTP scheme that is
different than what is used locally.
In nginx:
location /myprefix ... |
ba32a22cc0cb41c4548c658a7195fab56dab6dbf | atlas/prodtask/tasks.py | atlas/prodtask/tasks.py | from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas.prodtask.open_e... | from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db... | Add remove done staged rules | Add remove done staged rules
| Python | apache-2.0 | PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas | from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
- from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
+ from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed, delete_done_staging_rules
from atlas.p... | Add remove done staged rules | ## Code Before:
from __future__ import absolute_import, unicode_literals
from atlas.celerybackend.celery import app
from atlas.prestage.views import find_action_to_execute, submit_all_tapes_processed
from atlas.prodtask.hashtag import hashtag_request_to_tasks
from atlas.prodtask.mcevgen import sync_cvmfs_db
from atlas... |
eede55d9cd39c68ef03091614096e51d7df01336 | test_scraper.py | test_scraper.py | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert t... | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_body
assert t... | Modify test_extract_listings() to account for the change in output from extract_listings() | Modify test_extract_listings() to account for the change in output from extract_listings()
| Python | mit | jefrailey/basic-scraper | from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in te... | Modify test_extract_listings() to account for the change in output from extract_listings() | ## Code Before:
from scraper import search_CL
from scraper import read_search_results
from scraper import parse_source
from scraper import extract_listings
import bs4
def test_search_CL():
test_body, test_encoding = search_CL(minAsk=100, maxAsk=100)
assert "<span class=\"desktop\">craigslist</span>" in test_b... |
b823233978f70d8e34a3653b309ee43b4b1e0c0d | fuel/transformers/defaults.py | fuel/transformers/defaults.py | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['flo... | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['flo... | Handle None axis_labels in ToBytes. | Handle None axis_labels in ToBytes.
| Python | mit | udibr/fuel,markusnagel/fuel,vdumoulin/fuel,mila-udem/fuel,dmitriy-serdyuk/fuel,udibr/fuel,markusnagel/fuel,aalmah/fuel,vdumoulin/fuel,aalmah/fuel,capybaralet/fuel,janchorowski/fuel,mila-udem/fuel,dribnet/fuel,capybaralet/fuel,dmitriy-serdyuk/fuel,janchorowski/fuel,dribnet/fuel | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
... | Handle None axis_labels in ToBytes. | ## Code Before:
"""Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
... |
beeae2daf35da275d5f9e1ad01516c917319bf00 | gapipy/resources/geo/state.py | gapipy/resources/geo/state.py | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(self):
retu... | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [
('country', 'Country'),
('place', 'Place'),
]
@enforce_strin... | Add Place reference to State model | Add Place reference to State model
| Python | mit | gadventures/gapipy | from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
- _resource_fields = [('country', 'Country')]
+ _resource_fields = [
+ (... | Add Place reference to State model | ## Code Before:
from __future__ import unicode_literals
from ..base import Resource
from ...utils import enforce_string_type
class State(Resource):
_resource_name = 'states'
_as_is_fields = ['id', 'href', 'name']
_resource_fields = [('country', 'Country')]
@enforce_string_type
def __repr__(sel... |
cedac36d38ff0bf70abc1c9193948a288e858a01 | kitsune/lib/pipeline_compilers.py | kitsune/lib/pipeline_compilers.py | import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cac... | import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
# Allow for cac... | Update BrowserifyCompiler for n Pipeline settings. | Update BrowserifyCompiler for n Pipeline settings.
| Python | bsd-3-clause | mythmon/kitsune,MikkCZ/kitsune,brittanystoroz/kitsune,anushbmx/kitsune,MikkCZ/kitsune,anushbmx/kitsune,safwanrahman/kitsune,brittanystoroz/kitsune,MikkCZ/kitsune,mozilla/kitsune,safwanrahman/kitsune,mythmon/kitsune,anushbmx/kitsune,mythmon/kitsune,safwanrahman/kitsune,mozilla/kitsune,brittanystoroz/kitsune,mythmon/kits... | import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path... | Update BrowserifyCompiler for n Pipeline settings. | ## Code Before:
import re
from django.conf import settings
from django.utils.encoding import smart_bytes
from pipeline.compilers import CompilerBase
from pipeline.exceptions import CompilerError
class BrowserifyCompiler(CompilerBase):
output_extension = 'browserified.js'
def match_file(self, path):
... |
c1f8d5817b8c94b422c0d454dcc0fa3c00e751b6 | activelink/tests/urls.py | activelink/tests/urls.py | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), name='test'),
... | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 10):
from django.conf.urls import url
elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = [
url(r'^... | Add support for Django 1.11 | Add support for Django 1.11
| Python | unlicense | j4mie/django-activelink | from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
+
+ if DJANGO_VERSION >= (1, 10):
+ from django.conf.urls import url
- if DJANGO_VERSION >= (1, 6):
+ elif DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults... | Add support for Django 1.11 | ## Code Before:
from django import VERSION as DJANGO_VERSION
from django.http import HttpResponse
if DJANGO_VERSION >= (1, 6):
from django.conf.urls import patterns, url
else:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('',
url(r'^test-url/$', lambda r: HttpResponse('ok'), ... |
c2ca03ba94349340447a316ff21bcb26631e308f | lms/djangoapps/discussion/settings/common.py | lms/djangoapps/discussion/settings/common.py | """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_TASK_DELAY': 30,
... | """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
# .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
# .. toggle_implementation: DjangoSetting
# .. toggle_default: False
# .. toggle_description: If True, it add... | Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag | Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag
| Python | agpl-3.0 | EDUlib/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,edx/edx-platform,angelapper/edx-platfor... | """Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
+ # .. toggle_name: ALLOW_HIDING_DISCUSSION_TAB
+ # .. toggle_implementation: DjangoSetting
+ # .. toggle_default: False
+ # .. toggle_descriptio... | Add annotation for ALLOW_HIDING_DISCUSSION_TAB feature flag | ## Code Before:
"""Common environment variables unique to the discussion plugin."""
def plugin_settings(settings):
"""Settings for the discussions plugin. """
settings.FEATURES['ALLOW_HIDING_DISCUSSION_TAB'] = False
settings.DISCUSSION_SETTINGS = {
'MAX_COMMENT_DEPTH': 2,
'COURSE_PUBLISH_T... |
90ca340883077f57ba63127db058a8d244ec6f4c | molecule/ui/tests/conftest.py | molecule/ui/tests/conftest.py | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDri... | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome import ChromeDri... | Switch UI tests back to google chrome. | Switch UI tests back to google chrome.
| Python | apache-2.0 | Graylog2/graylog-ansible-role | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome ... | Switch UI tests back to google chrome. | ## Code Before:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
from webdriver_manager.chrome ... |
760506e88d22d86be818017fb6075abe7af2a068 | dactyl.py | dactyl.py | from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
| from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
def url_validator(url):
try:
code = urllib.urlopen(url).getcode()
if code == 200:
return True
except:
return False
def test_url(message, url):
if url_validator(url[1:len(url... | Add url_validator function and respond aciton to test url | Add url_validator function and respond aciton to test url
| Python | mit | KrzysztofSendor/dactyl | from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
+
+ def url_validator(url):
+ try:
+ code = urllib.urlopen(url).getcode()
+ if code == 200:
+ return True
+ except:
+ return False
+
+
+ def test_url(message, url):
+ ... | Add url_validator function and respond aciton to test url | ## Code Before:
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
## Instruction:
Add url_validator function and respond aciton to test url
## Code After:
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
import urllib
def url_validator(url)... |
1b8efb09ac512622ea3541d950ffc67b0a183178 | survey/signals.py | survey/signals.py | import django.dispatch
survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
| import django.dispatch
# providing_args=["instance", "data"]
survey_completed = django.dispatch.Signal()
| Remove puyrely documental providing-args argument | Remove puyrely documental providing-args argument
See https://docs.djangoproject.com/en/4.0/releases/3.1/#id2
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey | import django.dispatch
- survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
+ # providing_args=["instance", "data"]
+ survey_completed = django.dispatch.Signal()
| Remove puyrely documental providing-args argument | ## Code Before:
import django.dispatch
survey_completed = django.dispatch.Signal(providing_args=["instance", "data"])
## Instruction:
Remove puyrely documental providing-args argument
## Code After:
import django.dispatch
# providing_args=["instance", "data"]
survey_completed = django.dispatch.Signal()
|
231657e2bbc81b8299cc91fd24dcd7394f74b4ec | python/dpu_utils/codeutils/identifiersplitting.py | python/dpu_utils/codeutils/identifiersplitting.py | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(?=[@... | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$.'\"])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9])(... | Revert to some of the previous behavior for characters that shouldn't appear in identifiers. | Revert to some of the previous behavior for characters that shouldn't appear in identifiers.
| Python | mit | microsoft/dpu-utils,microsoft/dpu-utils | from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
- "(?<=[@$])(?=[a-zA-Z0-9])|"
+ "(... | Revert to some of the previous behavior for characters that shouldn't appear in identifiers. | ## Code Before:
from functools import lru_cache
from typing import List
import sys
REGEX_TEXT = ("(?<=[a-z0-9])(?=[A-Z])|"
"(?<=[A-Z0-9])(?=[A-Z][a-z])|"
"(?<=[0-9])(?=[a-zA-Z])|"
"(?<=[A-Za-z])(?=[0-9])|"
"(?<=[@$])(?=[a-zA-Z0-9])|"
"(?<=[a-zA-Z0-9... |
81460f88ee19fb736dfc3453df2905f0ba4b3974 | common/permissions.py | common/permissions.py | from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(... | from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
if not hasattr(... | Remove debugging code, fix typo | Remove debugging code, fix typo
| Python | mit | PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans | from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
... | Remove debugging code, fix typo | ## Code Before:
from rest_framework.permissions import BasePermission
class ObjectHasTokenUser(BasePermission):
"""
The object's user matches the token's user.
"""
def has_object_permission(self, request, view, obj):
token = request.auth
if not token:
return False
... |
65336509829a42b91b000d2e423ed4581ac61c98 | app/mpv.py | app/mpv.py | import sys
import json
import struct
import subprocess
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return... |
import sys
import json
import struct
import subprocess
import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
retu... | Handle shell args in python scripts | Handle shell args in python scripts
| Python | mit | vayan/external-video,vayan/external-video,vayan/external-video,vayan/external-video | +
import sys
import json
import struct
import subprocess
+ import shlex
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
- messageLength = struct.unpack('@I', rawLength)[0]
+ messageLength ... | Handle shell args in python scripts | ## Code Before:
import sys
import json
import struct
import subprocess
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength... |
83d5cc3b4ffb4759e8e073d04299a55802df09a8 | src/ansible/views.py | src/ansible/views.py | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return "200"
| from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return HttpResponse("200")
| Fix return to use HttpResponse | Fix return to use HttpResponse
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
- return "200"
+ return HttpResponse("200")
| Fix return to use HttpResponse | ## Code Before:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from .models import Playbook
def index(request):
return "200"
## Instruction:
Fix return to use HttpResponse
## Code After:
from django.shortcuts import get_object_or_404, render
from... |
88e5ecad9966057203a9cbecaeaecdca3e76b6da | tests/fake_filesystem.py | tests/fake_filesystem.py | import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
si... | import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir'
si... | Define noop close() for FakeFile | Define noop close() for FakeFile
| Python | bsd-2-clause | kxxoling/fabric,rodrigc/fabric,qinrong/fabric,elijah513/fabric,bspink/fabric,MjAbuz/fabric,cmattoon/fabric,hrubi/fabric,felix-d/fabric,askulkarni2/fabric,SamuelMarks/fabric,mathiasertl/fabric,tekapo/fabric,StackStorm/fabric,ploxiln/fabric,kmonsoor/fabric,raimon49/fabric,haridsv/fabric,bitprophet/fabric,fernandezcuesta/... | import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
... | Define noop close() for FakeFile | ## Code Before:
import os
import stat
from StringIO import StringIO
from types import StringTypes
import paramiko as ssh
class FakeFile(StringIO):
def __init__(self, value=None, path=None):
init = lambda x: StringIO.__init__(self, x)
if value is None:
init("")
ftype = 'dir... |
f45b3e73b6258c99aed2bff2e7350f1c797ff849 | providers/provider.py | providers/provider.py | import copy
import json
import requests
import html5lib
from application import APPLICATION as APP
# Be compatible with python 2 and 3
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, ur... | import copy
import json
from urllib.parse import urlencode
import html5lib
import requests
from application import APPLICATION as APP
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cac... | Remove support for Python 2. | Remove support for Python 2.
| Python | mit | EmilStenstrom/nephele | import copy
import json
+ from urllib.parse import urlencode
+
+ import html5lib
import requests
- import html5lib
from application import APPLICATION as APP
- # Be compatible with python 2 and 3
- try:
- from urllib import urlencode
- except ImportError:
- from urllib.parse import urlencode
cl... | Remove support for Python 2. | ## Code Before:
import copy
import json
import requests
import html5lib
from application import APPLICATION as APP
# Be compatible with python 2 and 3
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def par... |
cdd32dd3e346f72f823cc5d3f59c79c027db65c8 | common.py | common.py | """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to s... | """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
"""Check to s... | Make task an optional argument. | Make task an optional argument.
| Python | bsd-2-clause | chingc/DJRivals,chingc/DJRivals | """Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def... | Make task an optional argument. | ## Code Before:
"""Functions common to other modules."""
import json
import os
import re
import time
import urllib.request
from settings import net
def clean(name):
"""Strip all [^a-zA-Z0-9_] characters and convert to lowercase."""
return re.sub(r"\W", r"", name, flags=re.ASCII).lower()
def exists(path):
... |
150e338b7d2793c434d7e2f21aef061f35634476 | openspending/test/__init__.py | openspending/test/__init__.py |
import os
import sys
from paste.deploy import appconfig
from openspending import mongo
from helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
here_dir = os.getcwd()
config = appconfig('config:test.ini', relative_to=here_dir)
mongo.configure(config)
class TestCase(object):
def setup(self):
... |
import os
import sys
from pylons import config
from openspending import mongo
from .helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
mongo.configure(config)
class TestCase(object):
def setup(self):
pass
def teardown(self):
pass
class DatabaseTestCase(TestCase):
def... | Use config given on command line | Use config given on command line
| Python | agpl-3.0 | pudo/spendb,openspending/spendb,openspending/spendb,nathanhilbert/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,johnjohndoe/spendb,USStateDept/FPA_Core,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,openspending/spendb,USStateDept/FPA_Core,spendb/spendb,nathanhilbert/FP... |
import os
import sys
- from paste.deploy import appconfig
+ from pylons import config
from openspending import mongo
- from helpers import clean_all
+ from .helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
- here_dir = os.getcwd()
- config = appconfig('config:test.ini', relativ... | Use config given on command line | ## Code Before:
import os
import sys
from paste.deploy import appconfig
from openspending import mongo
from helpers import clean_all
__all__ = ['TestCase', 'DatabaseTestCase']
here_dir = os.getcwd()
config = appconfig('config:test.ini', relative_to=here_dir)
mongo.configure(config)
class TestCase(object):
def... |
37a0cb41a88114ab9edb514e29447756b0c3e92a | tests/test_cli.py | tests/test_cli.py |
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result = runner.invoke... |
import pytest
from cibopath import __version__
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(cli_runner, version_cli_flag):
result = cli_runner([version_cli_flag])
assert result.exit_code == 0
assert result.output ... | Use cli_runner fixture in test | Use cli_runner fixture in test
| Python | bsd-3-clause | hackebrot/cibopath |
- from click.testing import CliRunner
import pytest
- from cibopath.cli import main
from cibopath import __version__
-
- runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
- def test_cli_group_version_option(version_cli_f... | Use cli_runner fixture in test | ## Code Before:
from click.testing import CliRunner
import pytest
from cibopath.cli import main
from cibopath import __version__
runner = CliRunner()
@pytest.fixture(params=['-V', '--version'])
def version_cli_flag(request):
return request.param
def test_cli_group_version_option(version_cli_flag):
result... |
f814e945d3e62c87c5f86ef5ac37c5feb733b83d | tests/test_ext.py | tests/test_ext.py | from __future__ import absolute_import, unicode_literals
import unittest
from mopidy import config, ext
class ExtensionTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.ext = ext.Extension()
def test_dist_name_is_none(self):
self.assertIsNone(self.ext.dist_name)
def test_ex... | from __future__ import absolute_import, unicode_literals
import pytest
from mopidy import config, ext
@pytest.fixture
def extension():
return ext.Extension()
def test_dist_name_is_none(extension):
assert extension.dist_name is None
def test_ext_name_is_none(extension):
assert extension.ext_name is N... | Convert ext test to pytests | tests: Convert ext test to pytests
| Python | apache-2.0 | mokieyue/mopidy,bencevans/mopidy,ZenithDK/mopidy,jodal/mopidy,quartz55/mopidy,pacificIT/mopidy,pacificIT/mopidy,quartz55/mopidy,ali/mopidy,swak/mopidy,tkem/mopidy,bencevans/mopidy,mopidy/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,hkariti/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,ali/mopidy,bacontext/mopidy,glogiotatidis/... | from __future__ import absolute_import, unicode_literals
- import unittest
+ import pytest
from mopidy import config, ext
- class ExtensionTest(unittest.TestCase):
+ @pytest.fixture
+ def extension():
+ return ext.Extension()
- def setUp(self): # noqa: N802
- self.ext = ext.Extension... | Convert ext test to pytests | ## Code Before:
from __future__ import absolute_import, unicode_literals
import unittest
from mopidy import config, ext
class ExtensionTest(unittest.TestCase):
def setUp(self): # noqa: N802
self.ext = ext.Extension()
def test_dist_name_is_none(self):
self.assertIsNone(self.ext.dist_name)
... |
27ffcae96c5dce976517035b25a5c72f10e2ec99 | tool_spatialdb.py | tool_spatialdb.py |
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
... |
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibrary('spatialdb')
... | Use GLOBAL_TOOLs rather than Export/Import for project wide configuration. | Use GLOBAL_TOOLs rather than Export/Import for project wide configuration.
| Python | bsd-3-clause | ncareol/spatialdb,ncareol/spatialdb |
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env... | Use GLOBAL_TOOLs rather than Export/Import for project wide configuration. | ## Code Before:
import os
import sys
import eol_scons
tools = ['sqlitedb','doxygen','prefixoptions']
env = Environment(tools = ['default'] + tools)
platform = env['PLATFORM']
thisdir = env.Dir('.').srcnode().abspath
# define the tool
def spatialdb(env):
env.AppendUnique(CPPPATH =[thisdir,])
env.AppendLibra... |
da59d7481668a7133eebcd12b4d5ecfb655296a6 | test/test_blob_filter.py | test/test_blob_filter.py | """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, stage_type, path, expected... | """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, path, expected_result', [
... | Remove stage type as parameter from blob filter test | Remove stage type as parameter from blob filter test
| Python | bsd-3-clause | gitpython-developers/GitPython,gitpython-developers/gitpython,gitpython-developers/GitPython,gitpython-developers/gitpython | """Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
- @pytest.mark.parametrize('paths... | Remove stage type as parameter from blob filter test | ## Code Before:
"""Test the blob filter."""
from pathlib import Path
from typing import Sequence, Tuple
from unittest.mock import MagicMock
import pytest
from git.index.typ import BlobFilter, StageType
from git.objects import Blob
from git.types import PathLike
# fmt: off
@pytest.mark.parametrize('paths, stage_type... |
431ca4f2d44656ef9f97be50718712c6f3a0fa9b | qtawesome/tests/test_qtawesome.py | qtawesome/tests/test_qtawesome.py | # Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
'; qtawesome.icon(... | # Standard library imports
import subprocess
import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
... | Make the test more comprehensive. | Make the test more comprehensive.
| Python | mit | spyder-ide/qtawesome | # Standard library imports
import subprocess
+ import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
... | Make the test more comprehensive. | ## Code Before:
# Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
';... |
3d8ec94e61735b84c3b24b44d79fcd57611a93ee | mndeps.py | mndeps.py | from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
... | from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': SingleSwitchTopo,
... | Fix bug after removing torus | Fix bug after removing torus
| Python | apache-2.0 | ravel-net/ravel,ravel-net/ravel | from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': Si... | Fix bug after removing torus | ## Code Before:
from mininet.topo import ( SingleSwitchTopo, LinearTopo,
SingleSwitchReversedTopo )
from mininet.topolib import TreeTopo
from mininet.util import buildTopo
import psycopg2
TOPOS = { 'linear': LinearTopo,
'reversed': SingleSwitchReversedTopo,
'single': Sing... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.