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
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
2a0a29effa48caf5d95ed892d85cee235ebe1624
lamvery/utils.py
lamvery/utils.py
import os import sys import re import shlex import subprocess from termcolor import cprint ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): return None ret = {} ...
import os import sys import re import shlex import subprocess ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): return None ret = {} for e in env: match...
Fix error when import lamvery in function
Fix error when import lamvery in function
Python
mit
marcy-terui/lamvery,marcy-terui/lamvery
import os import sys import re import shlex import subprocess - from termcolor import cprint ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): ...
Fix error when import lamvery in function
## Code Before: import os import sys import re import shlex import subprocess from termcolor import cprint ENV_PATTERN = re.compile('^(?P<name>[^\s]+)\s*=\s*(?P<value>.+)$') def previous_alias(alias): return '{}-pre'.format(alias) def parse_env_args(env): if not isinstance(env, list): return None ...
... import subprocess ... if os.path.exists(path): print('Overwrite {}? [y/n]: '.format(path)) y_n = sys.stdin.readline() ...
293d50438fab81e74ab4559df7a4f7aa7cfd8f03
etcdocker/container.py
etcdocker/container.py
import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=False): # Ensure container is runn...
import ast import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=False): # Ensure contai...
Convert port list to dict
Convert port list to dict
Python
mit
CloudBrewery/docrane
+ import ast import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=F...
Convert port list to dict
## Code Before: import docker from etcdocker import util class Container: def __init__(self, name, params): self.name = name self.params = params def set_or_create_param(self, key, value): self.params[key] = value def ensure_running(self, force_restart=False): # Ensure c...
// ... existing code ... import ast import docker // ... modified code ... # Convert our ports into a dict if necessary ports = ast.literal_eval(self.params.get('ports')) # Create container with specified args ... volumes=self.params.get('volumes'), ports=...
6d72a1d3b4bd2e1a11e2fb9744353e5d2d9c8863
setup.py
setup.py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup(cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]), Extension("ccomp", ["ccomp.pyx"])])
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy def cext(name): return Extension(name, [name + ".pyx"], include_dirs=[numpy.get_include()]) setup(cmdclass = {'build_ext': build_ext}, ext_modules = [cext('lulu...
Add NumPy includes dir for Cython builds.
Add NumPy includes dir for Cython builds.
Python
bsd-3-clause
stefanv/lulu
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext + import numpy + + def cext(name): + return Extension(name, [name + ".pyx"], + include_dirs=[numpy.get_include()]) setup(cmdclass = {'build_ext': build_ext}, + ext...
Add NumPy includes dir for Cython builds.
## Code Before: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup(cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]), Extension("ccomp", ["ccomp.pyx"])]) ## Instruction: Add NumP...
... from Cython.Distutils import build_ext import numpy def cext(name): return Extension(name, [name + ".pyx"], include_dirs=[numpy.get_include()]) ... setup(cmdclass = {'build_ext': build_ext}, ext_modules = [cext('lulu_base'), cext('ccomp')]) ...
14a085f787f5fe80a0737d97515b71adaf05d1cd
checker/checker/contest.py
checker/checker/contest.py
from checker.abstract import AbstractChecker import base64 import sys import codecs class ContestChecker(AbstractChecker): def __init__(self, tick, team, service, ip): AbstractChecker.__init__(self, tick, team, service, ip) def _rpc(self, function, *args): sys.stdout.write("%s %s\n" % (funct...
from checker.abstract import AbstractChecker import base64 import sys import codecs class ContestChecker(AbstractChecker): def __init__(self, tick, team, service, ip): AbstractChecker.__init__(self, tick, team, service, ip) def _rpc(self, function, *args): sys.stdout.write("%s %s\n" % (funct...
Fix double-encoding of binary blobs
Fix double-encoding of binary blobs
Python
isc
fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver
from checker.abstract import AbstractChecker import base64 import sys import codecs class ContestChecker(AbstractChecker): def __init__(self, tick, team, service, ip): AbstractChecker.__init__(self, tick, team, service, ip) def _rpc(self, function, *args): sys.stdou...
Fix double-encoding of binary blobs
## Code Before: from checker.abstract import AbstractChecker import base64 import sys import codecs class ContestChecker(AbstractChecker): def __init__(self, tick, team, service, ip): AbstractChecker.__init__(self, tick, team, service, ip) def _rpc(self, function, *args): sys.stdout.write("%...
# ... existing code ... data = base64.b64encode(blob) return self._rpc("STORE", ident, data.decode('latin-1')) # ... rest of the code ...
e50aee5973a2593546d1308b5ba77cd0905dd2be
app/models.py
app/models.py
import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' ...
import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ = 'weather_data' ...
Fix excessive fields in conversion
Fix excessive fields in conversion
Python
agpl-3.0
rschiang/ntu-weather,rschiang/ntu-weather
import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __table...
Fix excessive fields in conversion
## Code Before: import dataclasses from ntuweather import Weather from sqlalchemy import Table, Column, DateTime, Integer, Float from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class WeatherData(Base): """Represents a weather record saved in the database.""" __tablename__ =...
# ... existing code ... del fields['provider'] # We don’t store provider name as there would be only one. del fields['valid'] # We only store valid weather data, hence. return cls(**fields) # ... rest of the code ...
da59d4334eb1a6f77bd0a9599614a6289ef843e4
pytest-server-fixtures/tests/integration/test_mongo_server.py
pytest-server-fixtures/tests/integration/test_mongo_server.py
import pytest def test_mongo_server(mongo_server): assert mongo_server.check_server_up() assert mongo_server.delete mongo_server.api.db.test.insert_one({'a': 'b', 'c': 'd'}) assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'} @pytest.mark.parametrize('count',...
import pytest def test_mongo_server(mongo_server): assert mongo_server.check_server_up() assert mongo_server.delete mongo_server.api.db.test.insert({'a': 'b', 'c': 'd'}) assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'} @pytest.mark.parametrize('count', ran...
Revert "fix deprecation warnings in mongo"
Revert "fix deprecation warnings in mongo" This reverts commit 5d449ff9376e7c0a3c78f2b2d631ab0ecd08fe81.
Python
mit
manahl/pytest-plugins,manahl/pytest-plugins
import pytest def test_mongo_server(mongo_server): assert mongo_server.check_server_up() assert mongo_server.delete - mongo_server.api.db.test.insert_one({'a': 'b', 'c': 'd'}) + mongo_server.api.db.test.insert({'a': 'b', 'c': 'd'}) assert mongo_server.api.db.test.find_one({'a': 'b'},...
Revert "fix deprecation warnings in mongo"
## Code Before: import pytest def test_mongo_server(mongo_server): assert mongo_server.check_server_up() assert mongo_server.delete mongo_server.api.db.test.insert_one({'a': 'b', 'c': 'd'}) assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'} @pytest.mark.para...
# ... existing code ... assert mongo_server.delete mongo_server.api.db.test.insert({'a': 'b', 'c': 'd'}) assert mongo_server.api.db.test.find_one({'a': 'b'}, {'_id': False}) == {'a': 'b', 'c': 'd'} # ... modified code ... coll = mongo_server.api.some_database.some_collection assert coll.coun...
a1bcb99691f5a0238f6a34a5579df3e89e8d6823
child_sync_gp/model/project_compassion.py
child_sync_gp/model/project_compassion.py
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, ...
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, ...
Fix bug in write project.
Fix bug in write project.
Python
agpl-3.0
CompassionCH/compassion-switzerland,ndtran/compassion-switzerland,MickSandoz/compassion-switzerland,eicher31/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,Secheron/compassion-switzerland,CompassionCH/compassion-switzerland,MickSandoz/compassion-switzerland,ecino/compassion-s...
from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ...
Fix bug in write project.
## Code Before: from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, ...
# ... existing code ... context) if not isinstance(ids, list): ids = [ids] gp_connect = gp_connector.GPConnect() # ... rest of the code ...
8235a217b50520093d549115fe09a8d4ff5e9191
webmanager/default_settings.py
webmanager/default_settings.py
INSTALLED_APPS += ( 'simplemenu', 'webmanager', 'bootstrapform', 'userenabootstrap', 'userena', # 'social_auth', 'provider.oauth2', ) TEMPLATE_CONTEXT_PROCESSORS += ( 'django.contrib.auth.context_processors.auth', ) AUTHENTICATION_BACKENDS += ( 'userena.backends.UserenaAuthenticati...
INSTALLED_APPS += ( 'provider', 'provider.oauth2', 'simplemenu', 'webmanager', 'bootstrapform', 'userenabootstrap', 'userena', # 'social_auth', ) TEMPLATE_CONTEXT_PROCESSORS += ( 'django.contrib.auth.context_processors.auth', ) AUTHENTICATION_BACKENDS += ( 'userena.backends.Use...
Fix provider oauth2 warning by import provider before oauth2 as described in the manual
Fix provider oauth2 warning by import provider before oauth2 as described in the manual
Python
bsd-3-clause
weijia/webmanager,weijia/webmanager,weijia/webmanager
INSTALLED_APPS += ( + 'provider', + 'provider.oauth2', 'simplemenu', 'webmanager', 'bootstrapform', 'userenabootstrap', 'userena', # 'social_auth', - 'provider.oauth2', ) TEMPLATE_CONTEXT_PROCESSORS += ( 'django.contrib.auth.context_processors.auth', ) ...
Fix provider oauth2 warning by import provider before oauth2 as described in the manual
## Code Before: INSTALLED_APPS += ( 'simplemenu', 'webmanager', 'bootstrapform', 'userenabootstrap', 'userena', # 'social_auth', 'provider.oauth2', ) TEMPLATE_CONTEXT_PROCESSORS += ( 'django.contrib.auth.context_processors.auth', ) AUTHENTICATION_BACKENDS += ( 'userena.backends.Use...
... INSTALLED_APPS += ( 'provider', 'provider.oauth2', 'simplemenu', ... # 'social_auth', ) ...
3fbca600b1b90ad3499d941e178aae89d1c7df70
regulations/generator/layers/external_citation.py
regulations/generator/layers/external_citation.py
from django.template import loader import utils from regulations.generator.layers.base import SearchReplaceLayer class ExternalCitationLayer(SearchReplaceLayer): shorthand = 'external' data_source = 'external-citations' def __init__(self, layer): self.layer = layer self.template = loader...
from django.template import loader from regulations.generator.layers import utils from regulations.generator.layers.base import SearchReplaceLayer class ExternalCitationLayer(SearchReplaceLayer): shorthand = 'external' data_source = 'external-citations' def __init__(self, layer): self.layer = la...
Make external citations Python3 compatible
Make external citations Python3 compatible
Python
cc0-1.0
18F/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site,18F/regulations-site,tadhg-ohiggins/regulations-site,eregs/regulations-site
from django.template import loader - import utils + from regulations.generator.layers import utils from regulations.generator.layers.base import SearchReplaceLayer class ExternalCitationLayer(SearchReplaceLayer): shorthand = 'external' data_source = 'external-citations' def __init__(...
Make external citations Python3 compatible
## Code Before: from django.template import loader import utils from regulations.generator.layers.base import SearchReplaceLayer class ExternalCitationLayer(SearchReplaceLayer): shorthand = 'external' data_source = 'external-citations' def __init__(self, layer): self.layer = layer self.t...
# ... existing code ... from django.template import loader from regulations.generator.layers import utils from regulations.generator.layers.base import SearchReplaceLayer # ... rest of the code ...
30f8317838a2e984e54fe22042fd3ffff10f82e6
waterbutler/core/streams/file.py
waterbutler/core/streams/file.py
import os import asyncio from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application/o...
import os from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type = 'application/octet-stream' ...
Update FileStreamReader for new python 3.5 async
Update FileStreamReader for new python 3.5 async
Python
apache-2.0
RCOSDP/waterbutler,felliott/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,TomBaxter/waterbutler,Johnetordoff/waterbutler
import os - import asyncio from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.c...
Update FileStreamReader for new python 3.5 async
## Code Before: import os import asyncio from waterbutler.core.streams import BaseStream class FileStreamReader(BaseStream): def __init__(self, file_pointer): super().__init__() self.file_gen = None self.file_pointer = file_pointer self.read_size = None self.content_type ...
// ... existing code ... import os // ... modified code ... while True: chunk = self.file_pointer.read(self.read_size) if not chunk: self.feed_eof() chunk = b'' yield chunk ... self.file_gen = self.file_gen or self.read_...
30044f8272557dbd367eab3dbe7c1ba1076484e9
readux/pages/models.py
readux/pages/models.py
from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent # Page.register_extensions('datepub...
from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent from feincms.content.video.models im...
Enable video content for cms pages
Enable video content for cms pages [#110289088]
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent + from feincms.con...
Enable video content for cms pages
## Code Before: from django.db import models # Create your models here. from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent # Page.register_ext...
// ... existing code ... from feincms.content.medialibrary.models import MediaFileContent from feincms.content.video.models import VideoContent // ... modified code ... )) Page.create_content_type(VideoContent) // ... rest of the code ...
65e6c8466482464333e77a2892fd0ac33ab5c3cb
q_and_a/apps/token_auth/views.py
q_and_a/apps/token_auth/views.py
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): d...
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_...
Fix indent, PEP-8 style and remove dup import.
Fix indent, PEP-8 style and remove dup import.
Python
bsd-3-clause
DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin - from django.contrib.auth import login, authenticate, login + from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reve...
Fix indent, PEP-8 style and remove dup import.
## Code Before: from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, Redir...
// ... existing code ... from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied // ... modified code ... def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated(...
b4d9fb47e040b199f88cffb4a0b761c443f390b4
dduplicated/cli.py
dduplicated/cli.py
from os import path as opath, getcwd from pprint import pprint from sys import argv from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths.append(path) return pat...
from os import path as opath, getcwd from pprint import pprint from sys import argv from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths.append(path) return pa...
Update in output to terminal.
Update in output to terminal. Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com>
Python
mit
messiasthi/dduplicated-cli
from os import path as opath, getcwd from pprint import pprint from sys import argv + from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths....
Update in output to terminal.
## Code Before: from os import path as opath, getcwd from pprint import pprint from sys import argv from dduplicated import commands def get_paths(params): paths = [] for param in params: path = opath.join(getcwd(), param) if opath.exists(path) and opath.isdir(path) and not opath.islink(path): paths.append(pa...
... from sys import argv from dduplicated import commands ... commands.help() exit() ...
536211012be24a20c34ef0af1fcc555672129354
byceps/util/system.py
byceps/util/system.py
import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' def get_config_env_name_from_env(*, default=None): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_ENV_VAR_NAME) if env is None: if defaul...
import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' def get_config_env_name_from_env(): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_ENV_VAR_NAME) if not env: raise Exception( ...
Remove default argument from function that reads the configuration name from the environment
Remove default argument from function that reads the configuration name from the environment
Python
bsd-3-clause
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' - def get_config_env_name_from_env(*, default=None): + def get_config_env_name_from_env(): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.envir...
Remove default argument from function that reads the configuration name from the environment
## Code Before: import os CONFIG_ENV_VAR_NAME = 'BYCEPS_CONFIG' def get_config_env_name_from_env(*, default=None): """Return the configuration environment name set via environment variable. Raise an exception if it isn't set. """ env = os.environ.get(CONFIG_ENV_VAR_NAME) if env is None: ...
// ... existing code ... def get_config_env_name_from_env(): """Return the configuration environment name set via environment // ... modified code ... if not env: raise Exception( "No configuration environment was specified via the '{}' " "environment variable.".format(...
a8a56f20dd76f61ec1ea6e99037490922d5cbcb1
setup.py
setup.py
from distutils.core import setup setup( name='grammpy', version='1.1.1', packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions'], url='https://github.com/PatrikValkovic/grammpy', license='GNU General Public License v3.0', author='Patrik Valkovic', download_url='https://github.com/P...
from distutils.core import setup setup( name='grammpy', version='1.1.1', packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions', 'grammpy.Rules'], url='https://github.com/PatrikValkovic/grammpy', license='GNU General Public License v3.0', author='Patrik Valkovic', download_url='htt...
FIX missing Rules directory in package
FIX missing Rules directory in package
Python
mit
PatrikValkovic/grammpy
from distutils.core import setup setup( name='grammpy', version='1.1.1', - packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions'], + packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions', 'grammpy.Rules'], url='https://github.com/PatrikValkovic/grammpy', lice...
FIX missing Rules directory in package
## Code Before: from distutils.core import setup setup( name='grammpy', version='1.1.1', packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions'], url='https://github.com/PatrikValkovic/grammpy', license='GNU General Public License v3.0', author='Patrik Valkovic', download_url='http...
... version='1.1.1', packages=['grammpy', 'grammpy.Grammars', 'grammpy.exceptions', 'grammpy.Rules'], url='https://github.com/PatrikValkovic/grammpy', ...
6c564ebe538d2723cc5f9397e09e5945796a257e
pyelevator/message.py
pyelevator/message.py
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), ...
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_uid'), ...
Fix : Range of len(1) have to be a tuple of tuples
Fix : Range of len(1) have to be a tuple of tuples
Python
mit
oleiade/py-elevator
import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kw...
Fix : Range of len(1) have to be a tuple of tuples
## Code Before: import msgpack import logging from .constants import FAILURE_STATUS class MessageFormatError(Exception): pass class Request(object): """Handler objects for frontend->backend objects messages""" def __new__(cls, *args, **kwargs): content = { 'DB_UID': kwargs.pop('db_u...
// ... existing code ... if hasattr(self, '_datas') and self._datas is not None: if (len(self._datas) == 1) and not isinstance(self._datas[0], (tuple, list)): return self._datas[0] // ... rest of the code ...
464bc1b511415459e99700b94101776d00b23796
indra/pre_assemble_for_db/pre_assemble_script.py
indra/pre_assemble_for_db/pre_assemble_script.py
import indra.tools.assemble_corpus as ac def process_statements(stmts): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False) return stmts
import indra.tools.assemble_corpus as ac from indra.db.util import get_statements, insert_pa_stmts def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False, poolsize=num...
Create function to handle full pipeline.
Create function to handle full pipeline.
Python
bsd-2-clause
bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra
import indra.tools.assemble_corpus as ac + from indra.db.util import get_statements, insert_pa_stmts + - def process_statements(stmts): + def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) - stmts = ac.run_preassembly(stmts, return_toplevel=F...
Create function to handle full pipeline.
## Code Before: import indra.tools.assemble_corpus as ac def process_statements(stmts): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False) return stmts ## Instruction: Create function to handle full pipeline. ## Code After: import in...
// ... existing code ... import indra.tools.assemble_corpus as ac from indra.db.util import get_statements, insert_pa_stmts def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) // ... modified code ... stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_t...
5b7a1a40ea43834feb5563f566d07bd5b31c589d
tests/test-recipes/metadata/always_include_files_glob/run_test.py
tests/test-recipes/metadata/always_include_files_glob/run_test.py
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
Add error messages to the asserts
Add error messages to the asserts
Python
bsd-3-clause
ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,da...
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'd...
Add error messages to the asserts
## Code Before: import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': ...
... if sys.platform == 'darwin': assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files'] elif sys.platform.startswith('linux'): assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16....
114eae527cce97423ec5cc5896a4728dc0764d2c
chunsabot/modules/images.py
chunsabot/modules/images.py
import os import json import shutil import subprocess import string import random from chunsabot.database import Database from chunsabot.botlogic import brain RNN_PATH = Database.load_config('rnn_library_path') MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7") def id_generator(size=12, chars=stri...
import os import json import shutil import subprocess import string import random from chunsabot.database import Database from chunsabot.botlogic import brain RNN_PATH = Database.load_config('rnn_library_path') MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7") def id_generator(size=12, chars=stri...
Fix some confusion of creating folders
Fix some confusion of creating folders
Python
mit
susemeee/Chunsabot-framework
import os import json import shutil import subprocess import string import random from chunsabot.database import Database from chunsabot.botlogic import brain RNN_PATH = Database.load_config('rnn_library_path') MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7") def id_g...
Fix some confusion of creating folders
## Code Before: import os import json import shutil import subprocess import string import random from chunsabot.database import Database from chunsabot.botlogic import brain RNN_PATH = Database.load_config('rnn_library_path') MODEL_PATH = os.path.join(RNN_PATH, "models/checkpoint_v1.t7_cpu.t7") def id_generator(siz...
# ... existing code ... path = os.path.join(brain.__temppath__, "{}_{}".format(id_generator(), 'image_processing')) if not os.path.isdir(path): # ... rest of the code ...
c266fbd7a3478d582dc0d6c88fc5e3d8b7a8f62f
survey/views/survey_result.py
survey/views/survey_result.py
import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) try: latest_answer...
import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) try: latest_answer...
Fix - Apache error AH02429
Fix - Apache error AH02429 Response header name 'mimetype=' contains invalid characters, aborting request
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) ...
Fix - Apache error AH02429
## Code Before: import datetime import os from django.http.response import HttpResponse from django.shortcuts import get_object_or_404 from survey.management.survey2csv import Survey2CSV from survey.models import Survey def serve_result_csv(request, pk): survey = get_object_or_404(Survey, pk=pk) try: ...
... response = HttpResponse(f.read(), content_type='text/csv') cd = u'attachment; filename="{}.csv"'.format(survey.name) ...
3a6d76201104b928c1b9053317c9e61804814ff5
pyresticd.py
pyresticd.py
import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print "\nStarting Backup at " + str(time.ctime()) os....
import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print('Starting Backup at {}'.format(time.ctime())) o...
Use py3-style print and string-formatting
Use py3-style print and string-formatting
Python
mit
Mebus/pyresticd,Mebus/pyresticd
import os import getpass import time from twisted.internet import task from twisted.internet import reactor - # Configuration + # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program + def do_restic_backup(): - pr...
Use py3-style print and string-formatting
## Code Before: import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print "\nStarting Backup at " + str(time....
# ... existing code ... # Configuration # ... modified code ... def do_restic_backup(): print('Starting Backup at {}'.format(time.ctime())) os.system(restic_command) ... print('Restic Scheduler') print('-' * 30) print('Timeout: {}'.format(timeout)) restic_password = getpass.getpass(prompt="Pl...
5d332259e16758bc43201073db91409390be9134
UM/Operations/GroupedOperation.py
UM/Operations/GroupedOperation.py
from . import Operation ## An operation that groups several other operations together. # # The intent of this operation is to hide an underlying chain of operations # from the user if they correspond to only one interaction with the user, such # as an operation applied to multiple scene nodes or a re-arrangeme...
from . import Operation ## An operation that groups several other operations together. # # The intent of this operation is to hide an underlying chain of operations # from the user if they correspond to only one interaction with the user, such # as an operation applied to multiple scene nodes or a re-arrangeme...
Remove removeOperation from grouped operation
Remove removeOperation from grouped operation This function is never used and actually should never be used. The operation may not be modified after it is used, so removing an operation from the list makes no sense.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
from . import Operation ## An operation that groups several other operations together. # # The intent of this operation is to hide an underlying chain of operations # from the user if they correspond to only one interaction with the user, such # as an operation applied to multiple scene nodes o...
Remove removeOperation from grouped operation
## Code Before: from . import Operation ## An operation that groups several other operations together. # # The intent of this operation is to hide an underlying chain of operations # from the user if they correspond to only one interaction with the user, such # as an operation applied to multiple scene nodes o...
# ... existing code ... ## Undo all operations in this group. # ... rest of the code ...
3864ef6773000d516ee6542a11db3c3b636d5b49
test/framework/killer.py
test/framework/killer.py
from __future__ import print_function import sys, os, signal, time, subprocess32 def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) print("\nKiller woke up") for ii in range(0, num_kills): os.kill(pid, signal.SIGTERM) ...
from __future__ import print_function import sys, os, signal, time, subprocess32 sys.path.append('../../..') from jenkinsflow.mocked import hyperspeed def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) print("\nKiller woke up") ...
Prepare kill test for mock - use hyperspeed
Prepare kill test for mock - use hyperspeed
Python
bsd-3-clause
lhupfeldt/jenkinsflow,lechat/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow
from __future__ import print_function import sys, os, signal, time, subprocess32 + + sys.path.append('../../..') + from jenkinsflow.mocked import hyperspeed def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) pr...
Prepare kill test for mock - use hyperspeed
## Code Before: from __future__ import print_function import sys, os, signal, time, subprocess32 def _killer(pid, sleep_time, num_kills): print("\nKiller going to sleep for", sleep_time, "seconds") time.sleep(sleep_time) print("\nKiller woke up") for ii in range(0, num_kills): os.kill(pid, s...
// ... existing code ... import sys, os, signal, time, subprocess32 sys.path.append('../../..') from jenkinsflow.mocked import hyperspeed // ... modified code ... print("\nKiller sent", ii + 1, "of", num_kills, "SIGTERM signals to ", pid) hyperspeed.sleep(1) // ... rest of the code ...
f2005fadb9fb2e2bcad32286a9d993c291c1992e
lazyblacksmith/models/api/industry_index.py
lazyblacksmith/models/api/industry_index.py
from . import db from lazyblacksmith.models import Activity class IndustryIndex(db.Model): solarsystem_id = db.Column( db.Integer, db.ForeignKey('solar_system.id'), primary_key=True ) solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes')) activity = db.Column(db.Integer,...
from . import db from lazyblacksmith.models import Activity class IndustryIndex(db.Model): solarsystem_id = db.Column( db.Integer, db.ForeignKey('solar_system.id'), primary_key=True ) solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes')) activity = db.Column(db.Integer,...
Fix celery task for industry indexes by adding missing field
Fix celery task for industry indexes by adding missing field
Python
bsd-3-clause
Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith
from . import db from lazyblacksmith.models import Activity class IndustryIndex(db.Model): solarsystem_id = db.Column( db.Integer, db.ForeignKey('solar_system.id'), primary_key=True ) solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes')) activity...
Fix celery task for industry indexes by adding missing field
## Code Before: from . import db from lazyblacksmith.models import Activity class IndustryIndex(db.Model): solarsystem_id = db.Column( db.Integer, db.ForeignKey('solar_system.id'), primary_key=True ) solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes')) activity = db.Co...
// ... existing code ... return Activity.COPYING if activity_string == 'reaction': return Activity.REACTIONS // ... rest of the code ...
497313620772c1cb0d520be1a0024c12ca02742e
tests/python_tests/fontset_test.py
tests/python_tests/fontset_test.py
from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.Map(256,256) mapnik.loa...
from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.Map(256,256) mapnik.loa...
Add a test (currently failing) ensuring that named fontsets created in python are propertly serialized
Add a test (currently failing) ensuring that named fontsets created in python are propertly serialized
Python
lgpl-2.1
Mappy/mapnik,qianwenming/mapnik,tomhughes/mapnik,jwomeara/mapnik,pnorman/mapnik,davenquinn/python-mapnik,yiqingj/work,pnorman/mapnik,Mappy/mapnik,yohanboniface/python-mapnik,mapycz/python-mapnik,jwomeara/mapnik,Mappy/mapnik,yiqingj/work,strk/mapnik,kapouer/mapnik,Mappy/mapnik,qianwenming/mapnik,lightmare/mapnik,garnert...
from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.M...
Add a test (currently failing) ensuring that named fontsets created in python are propertly serialized
## Code Before: from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.Map(256,256...
... def test_loading_fontset_from_python(): m = mapnik.Map(256,256) fset = mapnik.FontSet('my-set') fset.add_face_name('Comic Sans') fset.add_face_name('Papyrus') m.append_fontset('my-set', fset) sty = mapnik.Style() rule = mapnik.Rule() tsym = mapnik.TextSymbolizer() tsym.fonts...
85c509913cc9a6b22036c33eccb07277b39260e3
pygraphc/anomaly/AnomalyScore.py
pygraphc/anomaly/AnomalyScore.py
import csv from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction from pygraphc.clustering.ClusterUtility import ClusterUtility class AnomalyScore(object): """A class to calculate anomaly score in a cluster. """ def __init__(self, graph, clusters, filename): """The constructor of ...
import csv from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction from pygraphc.clustering.ClusterUtility import ClusterUtility class AnomalyScore(object): """A class to calculate anomaly score in a cluster. """ def __init__(self, graph, clusters, filename): """The constructor of c...
Add description of Parameters section in docstring
Add description of Parameters section in docstring
Python
mit
studiawan/pygraphc
import csv - from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction from pygraphc.clustering.ClusterUtility import ClusterUtility class AnomalyScore(object): """A class to calculate anomaly score in a cluster. """ def __init__(self, graph, clusters, filename): ...
Add description of Parameters section in docstring
## Code Before: import csv from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction from pygraphc.clustering.ClusterUtility import ClusterUtility class AnomalyScore(object): """A class to calculate anomaly score in a cluster. """ def __init__(self, graph, clusters, filename): """The...
... import csv from pygraphc.abstraction.ClusterAbstraction import ClusterAbstraction ... graph : graph A graph to be analyzed for its anomaly. clusters : dict[list] Dictionary of list containing node identifier for each clusters. filename : str ...
7539a5445d24193395eed5dc658a4e69d8782736
buffpy/tests/test_profile.py
buffpy/tests/test_profile.py
from nose.tools import eq_ from mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.g...
from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { "name": "me", "service": "twiter", "id": 1 } def test_profile_schedules_getter(): """ Should retrieve profiles from buffer's API. """ mocked_api = MagicMock() mocked_api.get.retu...
Migrate profile tests to pytest
Migrate profile tests to pytest
Python
mit
vtemian/buffpy
- from nose.tools import eq_ - from mock import MagicMock, patch + from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS + mocked_response = { - 'name': 'me', + "name": "me", - 'service': 'twiter', + "service": "twiter", - 'id': 1 + "id": 1 } + ...
Migrate profile tests to pytest
## Code Before: from nose.tools import eq_ from mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock(...
// ... existing code ... from unittest.mock import MagicMock, patch // ... modified code ... mocked_response = { "name": "me", "service": "twiter", "id": 1 } ... def test_profile_schedules_getter(): """ Should retrieve profiles from buffer's API. """ mocked_api = MagicMock() ...
959897478bbda18f02aa6e38f2ebdd837581f1f0
tests/test_sct_verify_signature.py
tests/test_sct_verify_signature.py
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signa...
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb').read() signa...
Fix test for changed SctVerificationResult
Fix test for changed SctVerificationResult
Python
mit
theno/ctutlz,theno/ctutlz
from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin')...
Fix test for changed SctVerificationResult
## Code Before: from os.path import join, dirname from utlz import flo from ctutlz.sct.verification import verify_signature def test_verify_signature(): basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature') signature_input = \ open(flo('{basedir}/signature_input_valid.bin'), 'rb')....
# ... existing code ... assert verify_signature(signature_input, signature, pubkey) is True # ... modified code ... assert verify_signature(signature_input, signature, pubkey) is False # ... rest of the code ...
dbec204b242ab643de162046ba73dca32043c6c2
space-age/space_age.py
space-age/space_age.py
class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0.2408467, 2) def on_venus(self): ...
class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_neptune": 164.79132} def...
Implement __getattr__ to reduce code
Implement __getattr__ to reduce code
Python
agpl-3.0
CubicComet/exercism-python-solutions
class SpaceAge(object): + YEARS = {"on_earth": 1, + "on_mercury": 0.2408467, + "on_venus": 0.61519726, + "on_mars": 1.8808158, + "on_jupiter": 11.862615, + "on_saturn": 29.447498, + "on_uranus": 84.016846, + "on_neptune": 1...
Implement __getattr__ to reduce code
## Code Before: class SpaceAge(object): def __init__(self, seconds): self.seconds = seconds @property def years(self): return self.seconds/31557600 def on_earth(self): return round(self.years, 2) def on_mercury(self): return round(self.years/0.2408467, 2) def ...
# ... existing code ... class SpaceAge(object): YEARS = {"on_earth": 1, "on_mercury": 0.2408467, "on_venus": 0.61519726, "on_mars": 1.8808158, "on_jupiter": 11.862615, "on_saturn": 29.447498, "on_uranus": 84.016846, "on_ne...
3c65881633daee8d5b19760e5c887dce25ab69c3
froide/helper/db_utils.py
froide/helper/db_utils.py
from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'): ...
from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_format='-{count}'): ...
Fix bad initial count in slug creation helper
Fix bad initial count in slug creation helper
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide
from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_form...
Fix bad initial count in slug creation helper
## Code Before: from django.db import IntegrityError from django.template.defaultfilters import slugify def save_obj_with_slug(obj, attribute='title', **kwargs): obj.slug = slugify(getattr(obj, attribute)) return save_obj_unique(obj, 'slug', **kwargs) def save_obj_unique(obj, attr, count=0, postfix_format='...
... first_round = False count = max( klass.objects.filter(**{ '%s__startswith' % attr: base_attr }).count(), initial_count ) else: ... ...
b06f0e17541f7d424e73fd200ae10db0722b1a5a
organizer/views.py
organizer/views.py
from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', {'star...
from django.shortcuts import ( get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html', ...
Create and redirect to Tag in tag_create().
Ch09: Create and redirect to Tag in tag_create().
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.shortcuts import ( - get_object_or_404, render) + get_object_or_404, redirect, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( ...
Create and redirect to Tag in tag_create().
## Code Before: from django.shortcuts import ( get_object_or_404, render) from .forms import TagForm from .models import Startup, Tag def startup_detail(request, slug): startup = get_object_or_404( Startup, slug__iexact=slug) return render( request, 'organizer/startup_detail.html'...
# ... existing code ... from django.shortcuts import ( get_object_or_404, redirect, render) # ... modified code ... if form.is_valid(): new_tag = form.save() return redirect(new_tag) else: # empty data or invalid data # ... rest of the code ...
37b8cf1af7818fe78b31ed25622f3f91805ade01
test_bert_trainer.py
test_bert_trainer.py
import unittest import time import shutil import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBERT, self).__init__(*args, **kwargs) self.output_dir = 'test_{}'.format(str(int(time.time()))) ...
import unittest import time import shutil import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBERT, self).__init__(*args, **kwargs) self.output_dir = 'test_{}'.format(str(int(time.time()))) ...
Fix merge conflict in bert_trainer_example.py
Fix merge conflict in bert_trainer_example.py
Python
apache-2.0
googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings
import unittest import time import shutil import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBERT, self).__init__(*args, **kwargs) self.output_dir = 'test_{}'.format(...
Fix merge conflict in bert_trainer_example.py
## Code Before: import unittest import time import shutil import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBERT, self).__init__(*args, **kwargs) self.output_dir = 'test_{}'.format(str(int(...
// ... existing code ... def test_train_and_predict(self): // ... rest of the code ...
a1bf03f69b9cadddcc7e0015788f23f9bad0f862
apps/splash/views.py
apps/splash/views.py
import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) return render(request, 'splash/base.html', {'splas...
import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) splash_year.events = _merge_events(splash_year.sp...
Append event merging on splash_events
Append event merging on splash_events
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) + + splash_year.events = _merge_e...
Append event merging on splash_events
## Code Before: import datetime from django.shortcuts import render from apps.splash.models import SplashEvent, SplashYear def index(request): # I'm really sorry ... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) return render(request, 'splash/bas...
... splash_year = SplashYear.objects.get(start_date__gt=str(datetime.date.today() - datetime.timedelta(180))) splash_year.events = _merge_events(splash_year.splash_events.all()) return render(request, 'splash/base.html', {'splash_year': splash_year }) ...
969fcfa12bcb734720c3e48c508329b687f91bf6
Cogs/Message.py
Cogs/Message.py
import asyncio import discord import textwrap from discord.ext import commands async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000): """A helper function to get the bot to cut his text into chunks.""" if not bot or not msg or not target: return False ...
import asyncio import discord import textwrap from discord.ext import commands async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000): """A helper function to get the bot to cut his text into chunks.""" if not bot or not msg or not target: return False ...
Create dm channel if it doesn't exist
Create dm channel if it doesn't exist
Python
mit
corpnewt/CorpBot.py,corpnewt/CorpBot.py
import asyncio import discord import textwrap from discord.ext import commands async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000): """A helper function to get the bot to cut his text into chunks.""" if not bot or not msg or not target: ...
Create dm channel if it doesn't exist
## Code Before: import asyncio import discord import textwrap from discord.ext import commands async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000): """A helper function to get the bot to cut his text into chunks.""" if not bot or not msg or not target: return Fal...
# ... existing code ... if not requestor.dm_channel: # No dm channel - create it await requestor.create_dm() dmChannel = requestor.dm_channel if len(textList) > maxMessage and dmChannel.id != target.id : # ... rest of the code ...
edc8248e6122dcfc1c4e6972ae0a4866de5c0d42
modules/urbandictionary.py
modules/urbandictionary.py
import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _register_events(self): ""...
import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _register_events(self): ""...
Fix new lines in definition of UD module
Fix new lines in definition of UD module
Python
mit
billyvg/piebot
import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _registe...
Fix new lines in definition of UD module
## Code Before: import requests import json from modules import * class Urbandictionary(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://www.urbandictionary.com/iphone/search/define?term=%s" def _register_events(s...
// ... existing code ... definition = ur['list'][0] definition['definition'] = definition['definition'].replace("\r", " ").replace("\n", " ") definition['example'] = definition['example'].replace("\r", " ").replace("\n", " ") message = "%(word)s (%(thum...
910fd1b323f05b695cccf6d3250b340c46cc2db5
venvctrl/cli/relocate.py
venvctrl/cli/relocate.py
"""Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the virtual environment settings...
"""Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the virtual environment settings...
Fix cli module for new lint detection
Fix cli module for new lint detection Since the last commit (2015), some of the test dependencies have updated. This commit specifically addresses updates in PyLint which result in more lint being detected in the project that previous test runs.
Python
mit
kevinconway/venvctrl
"""Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the ...
Fix cli module for new lint detection
## Code Before: """Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the virtual envi...
# ... existing code ... venv.move(destination) return None # ... rest of the code ...
c2d7f4c6ae9042d1cc7f11fa82d7133e9b506ad7
src/main/scripts/data_exports/export_json.py
src/main/scripts/data_exports/export_json.py
from lib.harvester import Harvester from lib.cli_helper import is_writable_directory import argparse import logging import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") logging.basicConfig(format="%(asctime...
from lib.harvester import Harvester from lib.cli_helper import is_writable_directory import argparse import logging import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") logging.basicConfig(format="%(asctime...
Fix UTF-8 encoding for json exports
Fix UTF-8 encoding for json exports
Python
apache-2.0
dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer,dainst/gazetteer
from lib.harvester import Harvester from lib.cli_helper import is_writable_directory import argparse import logging import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") logging.basicCo...
Fix UTF-8 encoding for json exports
## Code Before: from lib.harvester import Harvester from lib.cli_helper import is_writable_directory import argparse import logging import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") logging.basicConfig(f...
# ... existing code ... with open(options['target'], 'w', encoding='utf-8') as outfile: json.dump(places, outfile, ensure_ascii=False) # ... rest of the code ...
fe9e11af28e2ffe2b3da5ebb0971cd712136284c
nodeconductor/iaas/migrations/0011_cloudprojectmembership_availability_zone.py
nodeconductor/iaas/migrations/0011_cloudprojectmembership_availability_zone.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iaas', '0010_auto_20150118_1834'), ] operations = [ migrations.AddField( model_name='cloudprojectmembership', name='availabi...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iaas', '0010_auto_20150118_1834'), ] operations = [ migrations.AddField( model_name='cloudprojectmembership', name='availabi...
Add help_text to availability_zone field (nc-327)
Add help_text to availability_zone field (nc-327)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iaas', '0010_auto_20150118_1834'), ] operations = [ migrations.AddField( model_name='cloudprojectmembership'...
Add help_text to availability_zone field (nc-327)
## Code Before: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iaas', '0010_auto_20150118_1834'), ] operations = [ migrations.AddField( model_name='cloudprojectmembership', ...
... name='availability_zone', field=models.CharField(help_text='Optional availability group. Will be used for all instances provisioned in this tenant', max_length=100, blank=True), preserve_default=True, ...
23ab67f74fc7c09310638529ccf804ec2271fd6c
pynads/writer.py
pynads/writer.py
from .monad import Monad from .functor import fmap class Writer(Monad): """Stores a value as well as a log of events that have transpired with the value. """ def __init__(self, v, log): self.v = v if not isinstance(log, list): self.log = [log] else: self...
from .utils import _iter_but_not_str_or_map from .monad import Monad from .functor import fmap class Writer(Monad): """Stores a value as well as a log of events that have transpired with the value. """ __slots__ = ('v', 'log') def __init__(self, v, log): self.v = v if _iter_but_no...
Use utils._iter_but_not_str_or_map in Writer log creation.
Use utils._iter_but_not_str_or_map in Writer log creation.
Python
mit
justanr/pynads
+ from .utils import _iter_but_not_str_or_map from .monad import Monad from .functor import fmap class Writer(Monad): """Stores a value as well as a log of events that have transpired with the value. """ + __slots__ = ('v', 'log') + def __init__(self, v, log): self.v = v ...
Use utils._iter_but_not_str_or_map in Writer log creation.
## Code Before: from .monad import Monad from .functor import fmap class Writer(Monad): """Stores a value as well as a log of events that have transpired with the value. """ def __init__(self, v, log): self.v = v if not isinstance(log, list): self.log = [log] else: ...
... from .utils import _iter_but_not_str_or_map from .monad import Monad ... """ __slots__ = ('v', 'log') def __init__(self, v, log): ... if _iter_but_not_str_or_map(log): print("convert iter to list log...") self.log = [l for l in log] else: ...
34fda0b20a87b94d7413054bfcfc81dad0ecde19
utils/get_message.py
utils/get_message.py
import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from ...
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If t...
Revert "Remove redundant functions (one too many levels of abstraction)@"
Revert "Remove redundant functions (one too many levels of abstraction)@" This reverts commit 9c5bf06d1427db9839b1531aa08e66574c7b4582.
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
import amqp from contextlib import closing + + def __get_channel(connection): + return connection.channel() + + def __get_message_from_queue(channel, queue): + return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message fro...
Revert "Remove redundant functions (one too many levels of abstraction)@"
## Code Before: import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:...
... def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) ... with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, qu...
07ccbc36fd5148db2efc5f676fd13d4b24aa004f
hackasmlexer/hacklexer.py
hackasmlexer/hacklexer.py
import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE tokens = { 'root...
import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE tokens = { 'root...
Add register and IO addresses
Add register and IO addresses
Python
mit
cprieto/pygments_hack_asm
import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE ...
Add register and IO addresses
## Code Before: import re from pygments.lexer import RegexLexer, include from pygments.token import * class HackAsmLexer(RegexLexer): name = 'Hack Assembler' aliases = ['hack_asm'] filenames = ['*.asm'] identifier = r'[a-zA-Z$._?][a-zA-Z0-9$._?]*' flags = re.IGNORECASE | re.MULTILINE tokens =...
// ... existing code ... (r'\b(JGT|JEQ|JGE|JLT|JNE|JLE|JMP)\b', Keyword), (r'\b@(SCREEN|KBD)\b', Name.Builtin.Pseudo), # I/O addresses (r'\b@(R0|R1|R2|R3|R4|R5|R6|R7|R8|R9|R10|R11|R12|R13|R14|R15)\b', Name.Builtin.Pseudo), # RAM Addresses (r'\b@(SP|LCL|ARG|THIS|THAT)\b...
994e185e7bb8b2ffb78f20012121c441ea6b73a1
comics/views.py
comics/views.py
from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issu...
from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_name = "comics/issu...
Fix bug where arc slug could be literally anything
Fix bug where arc slug could be literally anything
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue ...
Fix bug where arc slug could be literally anything
## Code Before: from django.views import generic from gallery.models import GalleryImage from .models import Arc, Issue class IndexView(generic.ListView): model = Arc template_name = "comics/index.html" context_object_name = "arcs" class IssueView(generic.DetailView): model = Issue template_nam...
# ... existing code ... def get_queryset(self): query_set = super().get_queryset().filter(arc__slug=self.kwargs.get("arc_slug")) return query_set # ... rest of the code ...
8b5337878172df95400a708b096e012436f8a706
dags/main_summary.py
dags/main_summary.py
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['telemetry-alerts...
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 25), 'email': ['telemetry-alerts...
Prepare "Main Summary" job for backfill
Prepare "Main Summary" job for backfill Set the max number of active runs so we don't overwhelm the system, and rewind the start date by a couple of days to test that the scheduler does the right thing.
Python
mpl-2.0
opentrials/opentrials-airflow,opentrials/opentrials-airflow
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, - 'start_date': datetime(2016, 6, 27), + 'start_...
Prepare "Main Summary" job for backfill
## Code Before: from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['...
# ... existing code ... 'depends_on_past': False, 'start_date': datetime(2016, 6, 25), 'email': ['telemetry-alerts@mozilla.com', 'mreid@mozilla.com'], # ... modified code ... dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily', max_active_runs=10) ... ...
3c1e90761bf6d046c3b462dcdddb75335c259433
rnacentral/portal/tests/rna_type_tests.py
rnacentral/portal/tests/rna_type_tests.py
from django.test import TestCase from portal.models import Rna class GenericRnaTypeTest(TestCase): def rna_type_of(self, upi, taxid=None): return Rna.objects.\ get(upi=upi).\ get_rna_type(taxid=taxid, recompute=True) def assertRnaTypeIs(self, description, upi, taxid=None): ...
from django.test import TestCase from portal.models import Rna class GenericRnaTypeTest(TestCase): def rna_type_of(self, upi, taxid=None): return Rna.objects.\ get(upi=upi).\ get_rna_type(taxid=taxid, recompute=True) def assertRnaTypeIs(self, description, upi, taxid=None): ...
Add test showing issue with rna_type
Add test showing issue with rna_type
Python
apache-2.0
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
from django.test import TestCase from portal.models import Rna class GenericRnaTypeTest(TestCase): def rna_type_of(self, upi, taxid=None): return Rna.objects.\ get(upi=upi).\ get_rna_type(taxid=taxid, recompute=True) def assertRnaTypeIs(self, description,...
Add test showing issue with rna_type
## Code Before: from django.test import TestCase from portal.models import Rna class GenericRnaTypeTest(TestCase): def rna_type_of(self, upi, taxid=None): return Rna.objects.\ get(upi=upi).\ get_rna_type(taxid=taxid, recompute=True) def assertRnaTypeIs(self, description, upi, ...
# ... existing code ... taxid=6239) class HumanTests(GenericRnaTypeTest): def test_if_has_both_anti_and_lnc_likes_lnc(self): self.assertRnaTypeIs( 'lncRNA', 'URS0000732D5D', taxid=9606) # ... rest of the code ...
cc08fcbb513224aafe6c04143a150d1019c032ef
setup_py2exe.py
setup_py2exe.py
from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores plugin_data_path = 'plugins\\data\\trust_stores' plugin_data_...
from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores plugin_data_files = [] for file in os.listdir('plugins\\data\...
Fix trust stores paths for py2exe builds
Fix trust stores paths for py2exe builds
Python
agpl-3.0
nabla-c0d3/sslyze
from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores - plugin_data_path = 'plugins\\data\\tr...
Fix trust stores paths for py2exe builds
## Code Before: from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores plugin_data_path = 'plugins\\data\\trust_stor...
# ... existing code ... # Trust Stores plugin_data_files = [] for file in os.listdir('plugins\\data\\trust_stores'): file = os.path.join('plugins\\data\\trust_stores', file) if os.path.isfile(file): # skip directories # ... modified code ... data_files.append(('data\\trust_stores', plugin_data_files)) ...
6edd4114c4e715a3a0c440af455fff089a099620
scrapy/squeues.py
scrapy/squeues.py
import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self).push(s) def pop(s...
import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self).push(s) def pop(s...
Clarify comment about Pyhton versions
Clarify comment about Pyhton versions
Python
bsd-3-clause
pablohoffman/scrapy,pawelmhm/scrapy,finfish/scrapy,Ryezhang/scrapy,ssteo/scrapy,pawelmhm/scrapy,ssteo/scrapy,scrapy/scrapy,pawelmhm/scrapy,starrify/scrapy,ArturGaspar/scrapy,ssteo/scrapy,wujuguang/scrapy,dangra/scrapy,pablohoffman/scrapy,dangra/scrapy,elacuesta/scrapy,starrify/scrapy,scrapy/scrapy,kmike/scrapy,pablohof...
import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self)....
Clarify comment about Pyhton versions
## Code Before: import marshal from six.moves import cPickle as pickle from queuelib import queue def _serializable_queue(queue_class, serialize, deserialize): class SerializableQueue(queue_class): def push(self, obj): s = serialize(obj) super(SerializableQueue, self).push(s) ...
# ... existing code ... return pickle.dumps(obj, protocol=2) # Python <= 3.4 raises pickle.PicklingError here while # 3.5 <= Python < 3.6 raises AttributeError and # Python >= 3.6 raises TypeError except (pickle.PicklingError, AttributeError, TypeError) as e: # ... rest of the code ...
ac7477803739d303df8374f916748173da32cb07
test_elasticsearch/test_server/__init__.py
test_elasticsearch/test_server/__init__.py
from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase client = None def get_client(): global client if client is not None: return client # try and locate manual override in the local environment try: from test_elasticsearch.local import get_clie...
from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase client = None def get_client(**kwargs): global client if client is not None and not kwargs: return client # try and locate manual override in the local environment try: from test_elasticsearc...
Allow test client to be created with kwargs
Allow test client to be created with kwargs
Python
apache-2.0
brunobell/elasticsearch-py,elastic/elasticsearch-py,brunobell/elasticsearch-py,elastic/elasticsearch-py
from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase client = None - def get_client(): + def get_client(**kwargs): global client - if client is not None: + if client is not None and not kwargs: return client # try and locate manual over...
Allow test client to be created with kwargs
## Code Before: from elasticsearch.helpers.test import get_test_client, ElasticsearchTestCase as BaseTestCase client = None def get_client(): global client if client is not None: return client # try and locate manual override in the local environment try: from test_elasticsearch.local...
// ... existing code ... def get_client(**kwargs): global client if client is not None and not kwargs: return client // ... modified code ... from test_elasticsearch.local import get_client as local_get_client new_client = local_get_client(**kwargs) except ImportError: .....
739ae88d817cb86723b126360aaf3dd6df3045c0
tests/test_log.py
tests/test_log.py
import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "..." in message["...
import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values, _trim_message def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert ".....
Add coverage to some of log.py
Add coverage to some of log.py
Python
mit
bcb/jsonrpcclient
import json import logging from unittest.mock import Mock, patch - from jsonrpcclient.log import _trim_string, _trim_values + from jsonrpcclient.log import _trim_string, _trim_values, _trim_message def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message d...
Add coverage to some of log.py
## Code Before: import json import logging from unittest.mock import Mock, patch from jsonrpcclient.log import _trim_string, _trim_values def test_trim_string(): message = _trim_string("foo" * 100) assert "..." in message def test_trim_values(): message = _trim_values({"list": [0] * 100}) assert "....
# ... existing code ... from jsonrpcclient.log import _trim_string, _trim_values, _trim_message # ... modified code ... def test_trim_message(): message = _trim_message("foo" * 100) assert "..." in message # ... rest of the code ...
d042f4ced40d8d03bd65edf798a29058f26e98c6
test/test_wsstat.py
test/test_wsstat.py
import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1) def teardown(self): pass class TestConnectedWebsocketConn...
import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3) def test_coroutines(self): print(self.client) asse...
Add a test for running tasks
Add a test for running tasks
Python
mit
Fitblip/wsstat
import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): - self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1) + self.client = WebsocketTestingClient('wss://tes...
Add a test for running tasks
## Code Before: import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1) def teardown(self): pass class TestConnec...
// ... existing code ... def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3) def test_coroutines(self): print(self.client) assert len(self.client.tasks._children) == (1 + self.client.total_connections) // ... r...
abd0a6854c90c3647d17dfb3ea980fa49aa5372f
pwndbg/commands/segments.py
pwndbg/commands/segments.py
from __future__ import print_function import gdb import pwndbg.regs class segment(gdb.Function): """Get the flat address of memory based off of the named segment register. """ def __init__(self, name): super(segment, self).__init__(name) self.name = name def invoke(self, arg=0): ...
from __future__ import print_function import gdb import pwndbg.regs import pwndbg.commands class segment(gdb.Function): """Get the flat address of memory based off of the named segment register. """ def __init__(self, name): super(segment, self).__init__(name) self.name = name def invok...
Add fsbase and gsbase commands
Add fsbase and gsbase commands
Python
mit
cebrusfs/217gdb,anthraxx/pwndbg,chubbymaggie/pwndbg,anthraxx/pwndbg,disconnect3d/pwndbg,0xddaa/pwndbg,0xddaa/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,disconnect3d/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,anthraxx/pwndbg,cebrusfs/217gdb,zachriggle/pwndbg,pwndbg/pwndbg,pwndbg/pwndbg,anthraxx/pwndbg,chubbymaggie/pwndbg,ce...
from __future__ import print_function import gdb import pwndbg.regs + import pwndbg.commands class segment(gdb.Function): """Get the flat address of memory based off of the named segment register. """ def __init__(self, name): super(segment, self).__init__(name) self.nam...
Add fsbase and gsbase commands
## Code Before: from __future__ import print_function import gdb import pwndbg.regs class segment(gdb.Function): """Get the flat address of memory based off of the named segment register. """ def __init__(self, name): super(segment, self).__init__(name) self.name = name def invoke(self,...
// ... existing code ... import pwndbg.regs import pwndbg.commands // ... modified code ... segment('gsbase') @pwndbg.commands.OnlyWhenRunning @pwndbg.commands.ParsedCommand def fsbase(): """ Prints out the FS base address. See also $fsbase. """ print(hex(pwndbg.regs.fsbase)) @pwndbg.comman...
4a6ccb58bade2cefc7baa9424f1747275adaa166
antxetamedia/archive/filtersets.py
antxetamedia/archive/filtersets.py
from django_filters import FilterSet from antxetamedia.news.models import NewsPodcast from antxetamedia.radio.models import RadioPodcast from antxetamedia.projects.models import ProjectShow # We do not want to accidentally discard anything, so be inclusive and always # make gte and lte lookups instead of using gt or...
from django.utils.translation import ugettext_lazy as _ from django_filters import FilterSet, DateTimeFilter from antxetamedia.news.models import NewsPodcast from antxetamedia.radio.models import RadioPodcast from antxetamedia.projects.models import ProjectShow # We do not want to accidentally discard anything, so ...
Add labels to the pub_date__lte pub_date__gte filters
Add labels to the pub_date__lte pub_date__gte filters
Python
agpl-3.0
GISAElkartea/amv2,GISAElkartea/amv2,GISAElkartea/amv2
+ from django.utils.translation import ugettext_lazy as _ + - from django_filters import FilterSet + from django_filters import FilterSet, DateTimeFilter from antxetamedia.news.models import NewsPodcast from antxetamedia.radio.models import RadioPodcast from antxetamedia.projects.models import ProjectShow ...
Add labels to the pub_date__lte pub_date__gte filters
## Code Before: from django_filters import FilterSet from antxetamedia.news.models import NewsPodcast from antxetamedia.radio.models import RadioPodcast from antxetamedia.projects.models import ProjectShow # We do not want to accidentally discard anything, so be inclusive and always # make gte and lte lookups instea...
# ... existing code ... from django.utils.translation import ugettext_lazy as _ from django_filters import FilterSet, DateTimeFilter # ... modified code ... class NewsPodcastFilterSet(FilterSet): pub_date_after = DateTimeFilter('pub_date', lookup_type='gte', label=_('Published after')) pub_date_before...
931a858dc1cfde1652d21e1ccd60a82dde683ce3
moxie/butterfield.py
moxie/butterfield.py
import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events events.saferun() stream...
import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events events.saferun() stream...
Add simple "yo" bot command
Add simple "yo" bot command
Python
mit
paultag/moxie,loandy/moxie,mileswwatkins/moxie,mileswwatkins/moxie,paultag/moxie,loandy/moxie,loandy/moxie,paultag/moxie,rshorey/moxie,rshorey/moxie,rshorey/moxie,mileswwatkins/moxie
import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events ...
Add simple "yo" bot command
## Code Before: import os import json import asyncio from butterfield.utils import at_bot from aiodocker import Docker from aiocore import Service WEB_ROOT = os.environ.get("MOXIE_WEB_URL", "http://localhost:8888") @asyncio.coroutine def events(bot): docker = Docker() events = docker.events events.safer...
# ... existing code ... webroot=WEB_ROOT, job=job)) elif cmd == "yo": yield from bot.post( message['channel'], "Yo {}".format(message['user'])) # ... rest of the code ...
c955628b134586491265bc2e6b4045398072cead
allauth/socialaccount/providers/kakao/provider.py
allauth/socialaccount/providers/kakao/provider.py
from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data['properties'] ...
from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_data['properties'] ...
Handle case where email is not present
fix(kakao): Handle case where email is not present
Python
mit
pennersr/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,AltSchool/django-allauth,lukeburden/django-allauth,bittner/django-allauth,lukeburden/django-allauth,b...
from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_d...
Handle case where email is not present
## Code Before: from allauth.account.models import EmailAddress from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class KakaoAccount(ProviderAccount): @property def properties(self): return self.account.extra_dat...
# ... existing code ... email = data.get("kaccount_email") if email: verified = data.get("kaccount_email_verified") # data["kaccount_email_verified"] imply the email address is # verified ret.append(EmailAddress(email=email, ...
090bcbf8bbc32a2a8da5f0ab2be097e5a6716c3d
src/adhocracy_frontend/adhocracy_frontend/tests/integration/test_jasmine.py
src/adhocracy_frontend/adhocracy_frontend/tests/integration/test_jasmine.py
from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmine class TestJasmi...
from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmine class TestJasmi...
Mark integration tests as xfail
Mark integration tests as xfail
Python
agpl-3.0
fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocr...
from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmi...
Mark integration tests as xfail
## Code Before: from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmine ...
// ... existing code ... class TestJasmine: @mark.xfail def test_all(self, browser_igtest): // ... rest of the code ...
b7106307baf97ba32cb29fe2a4bb9ed925c194ca
custom/onse/management/commands/update_onse_facility_cases.py
custom/onse/management/commands/update_onse_facility_cases.py
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args, **options): ...
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args, **options): ...
Fix passing keyword arg to task
Fix passing keyword arg to task
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *...
Fix passing keyword arg to task
## Code Before: from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args...
# ... existing code ... def handle(self, *args, **options): update_facility_cases_from_dhis2_data_elements.apply(kwargs={ 'print_notifications': True}) # ... rest of the code ...
1994a59d3ae9d3f24445f11f3bc0dd3089042bc4
main.py
main.py
from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the FinanceServer - fetch data...
from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the FinanceServer - fetch data...
Use modify with the orderbook
Use modify with the orderbook
Python
mit
albhu/finance
from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the Fina...
Use modify with the orderbook
## Code Before: from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the FinanceServer ...
... print('strategies available: Vanilla or Strawberry') print(strategy.name, strategy.description) ... book = books[order.symbol] = OrderBook(order.symbol) if order.action == 'A': book.add(order) elif order.side == 'M': book...
23f95f0319c929006c89efdf0d113370a1a003b4
moa/factory_registers.py
moa/factory_registers.py
from kivy.factory import Factory r = Factory.register r('MoaStage', module='moa.stage.base') r('StageRender', module='moa.stage.base') r('Delay', module='moa.stage.delay') r('TreeRender', module='moa.render.treerender') r('TreeRenderExt', module='moa.render.treerender') r('StageTreeNode', module='moa.render.treerender...
from kivy.factory import Factory r = Factory.register r('MoaStage', module='moa.stage') r('Delay', module='moa.stage.delay') r('GateStage', module='moa.stage.gate') r('StageRender', module='moa.stage.base') r('TreeRender', module='moa.render.treerender') r('TreeRenderExt', module='moa.render.treerender') r('StageTree...
Update factory registers with stages.
Update factory registers with stages.
Python
mit
matham/moa
from kivy.factory import Factory r = Factory.register - r('MoaStage', module='moa.stage.base') + r('MoaStage', module='moa.stage') + r('Delay', module='moa.stage.delay') + r('GateStage', module='moa.stage.gate') + r('StageRender', module='moa.stage.base') - r('Delay', module='moa.stage.delay') r('TreeRender...
Update factory registers with stages.
## Code Before: from kivy.factory import Factory r = Factory.register r('MoaStage', module='moa.stage.base') r('StageRender', module='moa.stage.base') r('Delay', module='moa.stage.delay') r('TreeRender', module='moa.render.treerender') r('TreeRenderExt', module='moa.render.treerender') r('StageTreeNode', module='moa.r...
... r = Factory.register r('MoaStage', module='moa.stage') r('Delay', module='moa.stage.delay') r('GateStage', module='moa.stage.gate') r('StageRender', module='moa.stage.base') r('TreeRender', module='moa.render.treerender') ...
2db6e8e294059847251feb9610c42180ae44e05b
fbone/appointment/views.py
fbone/appointment/views.py
from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appo...
from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('app...
Fix some error about session.
Fix some error about session.
Python
bsd-3-clause
wpic/flask-appointment-calendar,wpic/flask-appointment-calendar
+ from datetime import datetime + - from flask import (Blueprint, render_template, request, + from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAp...
Fix some error about session.
## Code Before: from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, u...
// ... existing code ... from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) // ... modified code ... def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) ...
a73cc6d6ad8460d492b29db60df2c0e8eaff932e
openerp_conventions.py
openerp_conventions.py
"""OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' class OpenERPConvention...
"""OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' class OpenERPConvention...
Improve BaseChecker class by using __metaclass__ keyword + add a filename setter
Improve BaseChecker class by using __metaclass__ keyword + add a filename setter
Python
mit
nbessi/openerp-conventions
"""OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' ...
Improve BaseChecker class by using __metaclass__ keyword + add a filename setter
## Code Before: """OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' class O...
// ... existing code ... for check in self.checks: check.set_filename(self.filename) check.visit(tree_root) // ... rest of the code ...
fb25fa04cf553b1084425a1f2af6a9315266ffaf
salt/renderers/yaml_jinja.py
salt/renderers/yaml_jinja.py
''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.Loader = yaml.CLoader yam...
''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.Loader = yaml.CLoader yam...
Add pillar data to default renderer
Add pillar data to default renderer
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.L...
Add pillar data to default renderer
## Code Before: ''' The default rendering engine, process yaml with the jinja2 templating engine This renderer will take a yaml file with the jinja2 template and render it to a high data format for salt states. ''' # Import Python Modules import os # Import thirt party modules import yaml try: yaml.Loader = yaml...
// ... existing code ... passthrough['grains'] = __grains__ passthrough['pillar'] = __pillar__ passthrough['env'] = env // ... rest of the code ...
28126555aea9a78467dfcadbb2b14f9c640cdc6d
dwitter/templatetags/to_gravatar_url.py
dwitter/templatetags/to_gravatar_url.py
import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower()).hexdigest())
import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())
Fix gravatar hashing error on py3
Fix gravatar hashing error on py3
Python
apache-2.0
lionleaf/dwitter,lionleaf/dwitter,lionleaf/dwitter
import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % - hashlib.md5((email or '').strip().lower()).hexdigest()) + hashlib.md5((email or '').strip().lower()....
Fix gravatar hashing error on py3
## Code Before: import hashlib from django import template register = template.Library() @register.filter def to_gravatar_url(email): return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower()).hexdigest()) ## Instruction: Fix gravatar hashing error on py3 ## Code A...
# ... existing code ... return ('https://gravatar.com/avatar/%s?d=retro' % hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest()) # ... rest of the code ...
66602e67c06266735b58fd2bee8b55b7cac401b1
archive/archive_report_ingest_status/src/test_archive_report_ingest_status.py
archive/archive_report_ingest_status/src/test_archive_report_ingest_status.py
import uuid import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { 'request_method': 'GET', 'id': guid ...
import uuid import pytest import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { 'request_method': 'GET', ...
Add a test that a non-GET method is rejected
Add a test that a non-GET method is rejected
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
import uuid + + import pytest import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { ...
Add a test that a non-GET method is rejected
## Code Before: import uuid import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { 'request_method': 'GET', ...
# ... existing code ... import uuid import pytest # ... modified code ... assert response == item def test_fails_if_called_with_post_event(): event = { 'request_method': 'POST' } with pytest.raises(AssertionError, match='Expected request_method=GET'): report_ingest_status.ma...
cbdc24aeef9ffbd8e7400ab43112409509b3337d
reviewday/util.py
reviewday/util.py
import os import shutil import html_helper from Cheetah.Template import Template def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') if os.path.exists(out_dir): print 'WARNING: output directory "%s" already exists' % ...
import os import html_helper from Cheetah.Template import Template from distutils.dir_util import copy_tree def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') copy_tree(report_files_dir, out_dir) def create_report(name_spa...
Remove warning for existing output directory.
Remove warning for existing output directory. In our configuration puppet will manage the output directory, so it is expected behavior for it to exist, removing warning. Also switching to distutils.dir_util copy_tree since that allows for copying of required supporting files into an existing output directory. Change-...
Python
mit
openstack-infra/reviewday,openstack-infra/reviewday,dprince/reviewday
import os - import shutil import html_helper from Cheetah.Template import Template + from distutils.dir_util import copy_tree def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') - if os.path.exists(out_dir): -...
Remove warning for existing output directory.
## Code Before: import os import shutil import html_helper from Cheetah.Template import Template def prep_out_dir(out_dir='out_report'): src_dir = os.path.dirname(__file__) report_files_dir = os.path.join(src_dir, 'report_files') if os.path.exists(out_dir): print 'WARNING: output directory "%s" al...
# ... existing code ... import os import html_helper # ... modified code ... from Cheetah.Template import Template from distutils.dir_util import copy_tree ... report_files_dir = os.path.join(src_dir, 'report_files') copy_tree(report_files_dir, out_dir) # ... rest of the code ...
5425c2419b7365969ea8b211432858d599214201
tests/test_archive.py
tests/test_archive.py
from json import load from django_archive import __version__ from .base import BaseArchiveTestCase from .sample.models import Sample class ArchiveTestCase(BaseArchiveTestCase): """ Test that the archive command includes correct data in the archive """ def setUp(self): Sample().save() ...
from json import load from django.core.files.base import ContentFile from django_archive import __version__ from .base import BaseArchiveTestCase from .sample.models import Sample class ArchiveTestCase(BaseArchiveTestCase): """ Test that the archive command includes correct data in the archive """ ...
Update test to ensure attached files are present in archives.
Update test to ensure attached files are present in archives.
Python
mit
nathan-osman/django-archive,nathan-osman/django-archive
from json import load + from django.core.files.base import ContentFile from django_archive import __version__ from .base import BaseArchiveTestCase from .sample.models import Sample class ArchiveTestCase(BaseArchiveTestCase): """ Test that the archive command includes correct data in t...
Update test to ensure attached files are present in archives.
## Code Before: from json import load from django_archive import __version__ from .base import BaseArchiveTestCase from .sample.models import Sample class ArchiveTestCase(BaseArchiveTestCase): """ Test that the archive command includes correct data in the archive """ def setUp(self): Sample...
... from django.core.files.base import ContentFile from django_archive import __version__ ... _ATTACHMENT_FILENAME = 'sample.txt' _ATTACHMENT_CONTENT = b'sample' def setUp(self): sample = Sample() sample.attachment.save( self._ATTACHMENT_FILENAME, Content...
94a944b01953ed75bfbefbd11ed62ca438cd9200
accounts/tests/test_models.py
accounts/tests/test_models.py
from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model...
from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(s...
Add test for unsupplied email for user model
Add test for unsupplied email for user model
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
from django.test import TestCase from django.contrib.auth import get_user_model + from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_...
Add test for unsupplied email for user model
## Code Before: from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise i...
... from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError ... def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() ...
abefbbc99e7e62bed31db549519807feee7254f9
tests/test_machine.py
tests/test_machine.py
import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM') assert len(lattice) == 173
import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM') assert len(lattice) == 173 for element in lattice.get_elements(): assert element.get_pv_name('readback')
Test to get different pv names for an element
Test to get different pv names for an element
Python
apache-2.0
razvanvasile/RML,willrogers/pml,willrogers/pml
import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM') assert len(lattice) == 173 + for element in lattice.get_elements(): + assert element.get_pv_name('readback')
Test to get different pv names for an element
## Code Before: import rml.machines def test_machine_load_elements(): lattice = rml.machines.get_elements(machine='SRI21', elemType='BPM') assert len(lattice) == 173 ## Instruction: Test to get different pv names for an element ## Code After: import rml.machines def test_machine_load_elements(): lattic...
// ... existing code ... assert len(lattice) == 173 for element in lattice.get_elements(): assert element.get_pv_name('readback') // ... rest of the code ...
5a4ff0b4da37a97e6ef86074dde63b47ba553ad8
test/typing.py
test/typing.py
from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def test2(arg): make_eq_test(re...
from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def test2(arg): make_eq_test(re...
Add a test that automatic type promotions are not allowed.
Add a test that automatic type promotions are not allowed.
Python
apache-2.0
squisher/stella,squisher/stella,squisher/stella,squisher/stella
from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def tes...
Add a test that automatic type promotions are not allowed.
## Code Before: from stella import stella from random import randint from test import * def return_bool(): return True def return_arg(x): return x def equality(a,b): return a==b def test1(): make_eq_test(return_bool, ()) @mark.parametrize('arg', single_args([True, False, 0, 1, 42.0, -42.5])) def test2(arg): ...
// ... existing code ... @mark.parametrize('args', [(False, 1), (42.0, True), (1, 1.0), (randint(0, 10000000), float(randint(-10000 , 1000000)))]) @mark.xfail() def test3fail(args): make_eq_test(equality, args) if __name__ == '__main__': // ... rest of the code ...
5bbed41d8150f6d0657f1a7670b449619f3ba0f7
promgen/util.py
promgen/util.py
import requests from promgen.version import __version__ def post(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.post(url, *args, **kwar...
import requests.sessions from promgen.version import __version__ def post(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.post(url, **kwargs) def get(url, **kwargs): with requests.sessions.Session(...
Copy the pattern from requests.api to use a slightly more stable API
Copy the pattern from requests.api to use a slightly more stable API
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
- import requests + import requests.sessions from promgen.version import __version__ - def post(url, *args, **kwargs): + def post(url, **kwargs): + with requests.sessions.Session() as session: - '''Wraps requests.post with our user-agent''' - if 'headers' not in kwargs: - kwargs['heade...
Copy the pattern from requests.api to use a slightly more stable API
## Code Before: import requests from promgen.version import __version__ def post(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = 'promgen/{}'.format(__version__) return requests.post(ur...
... import requests.sessions ... def post(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__version__) return session.post(url, **kwargs) ... def get(url, **kwargs): with requests.sessions.Session() as session:...
623c56c14aa1d1c47b081f607701323d00903dc9
gather/topic/api.py
gather/topic/api.py
from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_auth], }, include_methods=["have_read"], exclu...
from flask import g, jsonify from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_auth], }, include_met...
Add API to mark topic as reader
Add API to mark topic as reader
Python
mit
whtsky/Gather,whtsky/Gather
+ from flask import g, jsonify from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_aut...
Add API to mark topic as reader
## Code Before: from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager from gather.topic.models import Topic, Reply bp = api_manager.create_api_blueprint( Topic, methods=["GET", "POST"], preprocessors={ 'POST': [need_auth], }, include_methods=["have_r...
// ... existing code ... from flask import g, jsonify // ... modified code ... ) @bp.route("/topic/<int:topic_id>/mark_read") def _mark_read_for_topic(topic_id): need_auth() topic = Topic.query.get_or_404(topic_id) topic.mark_read(g.token_user) return jsonify({"code": 200}) // ... rest of ...
f87b8c5b94e3e163f19ea0414d1fb2c42f09c166
test/test_genmidi.py
test/test_genmidi.py
import unittest import tempfile from pyknon.MidiFile import MIDIFile from pyknon.genmidi import Midi, MidiError from pyknon.music import NoteSeq, Note class TestMidi(unittest.TestCase): def test_init(self): midi = Midi(1, tempo=120) self.assertEqual(midi.number_tracks, 1) self.assertIsInst...
import unittest import tempfile from pyknon.MidiFile import MIDIFile from pyknon.genmidi import Midi, MidiError from pyknon.music import NoteSeq, Note class TestMidi(unittest.TestCase): def test_init(self): midi = Midi(1, tempo=120) self.assertEqual(midi.number_tracks, 1) self.assertIsInst...
Test for sequence of chords
Test for sequence of chords
Python
mit
palmerev/pyknon,kroger/pyknon
import unittest import tempfile from pyknon.MidiFile import MIDIFile from pyknon.genmidi import Midi, MidiError from pyknon.music import NoteSeq, Note class TestMidi(unittest.TestCase): def test_init(self): midi = Midi(1, tempo=120) self.assertEqual(midi.number_tracks, 1) ...
Test for sequence of chords
## Code Before: import unittest import tempfile from pyknon.MidiFile import MIDIFile from pyknon.genmidi import Midi, MidiError from pyknon.music import NoteSeq, Note class TestMidi(unittest.TestCase): def test_init(self): midi = Midi(1, tempo=120) self.assertEqual(midi.number_tracks, 1) s...
// ... existing code ... def test_seq_chords(self): chords = [NoteSeq("C E G"), NoteSeq("G B D")] midi = Midi() midi.seq_chords(chords) // ... rest of the code ...
f4286480f0fa157eb1b88b144ee57ffef7d1fc03
barython/tests/hooks/test_bspwm.py
barython/tests/hooks/test_bspwm.py
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops':...
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops':...
Add test for bspwm widget
Add test for bspwm widget
Python
bsd-3-clause
Anthony25/barython
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ...
Add test for bspwm widget
## Code Before: from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-...
# ... existing code ... assert expected == bh.parse_event(status)["monitors"] # ... rest of the code ...
73d59df8b94f72e83b978c00518afa01967faac9
mle/test_package.py
mle/test_package.py
def test_distribution(): from mle import Normal, var, par import theano.tensor as T x = var('x') mu = par('mu') sigma = par('sigma') dist = Normal(x, mu, sigma) assert(len(dist.get_vars()) == 1) assert(len(dist.get_params()) == 2) assert(len(dist.get_dists()) == 0)
def test_formula_transform(): """ Check if variables can be added/multiplied/transformed. The result should be a formula that can be plugged into a model. """ from mle import var, par x = var('x') a = par('a') b = par('b') formula = a * x**2 + b def test_simple_fit(): """ ...
Add some tests that don't pass yet
Add some tests that don't pass yet
Python
mit
ibab/python-mle
- def test_distribution(): + + def test_formula_transform(): + """ + Check if variables can be added/multiplied/transformed. + The result should be a formula that can be plugged into a model. + """ + from mle import var, par + + x = var('x') + a = par('a') + b = par('b') + + formu...
Add some tests that don't pass yet
## Code Before: def test_distribution(): from mle import Normal, var, par import theano.tensor as T x = var('x') mu = par('mu') sigma = par('sigma') dist = Normal(x, mu, sigma) assert(len(dist.get_vars()) == 1) assert(len(dist.get_params()) == 2) assert(len(dist.get_dists()) == 0)...
# ... existing code ... def test_formula_transform(): """ Check if variables can be added/multiplied/transformed. The result should be a formula that can be plugged into a model. """ from mle import var, par x = var('x') a = par('a') b = par('b') formula = a * x**2 + b def tes...
7b1d520278b8fe33b68103d26f9aa7bb945f6791
cryptography/hazmat/backends/__init__.py
cryptography/hazmat/backends/__init__.py
from cryptography.hazmat.backends import openssl from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): from cryptography.hazmat.backends import commoncrypto _ALL_BACKENDS.append(commoncrypt...
from cryptography.hazmat.backends import openssl from cryptography.hazmat.backends.multibackend import MultiBackend from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): from cryptography.hazma...
Make the default backend be a multi-backend
Make the default backend be a multi-backend
Python
bsd-3-clause
bwhmather/cryptography,Ayrx/cryptography,bwhmather/cryptography,Lukasa/cryptography,Ayrx/cryptography,bwhmather/cryptography,kimvais/cryptography,skeuomorf/cryptography,dstufft/cryptography,kimvais/cryptography,Lukasa/cryptography,dstufft/cryptography,Ayrx/cryptography,skeuomorf/cryptography,Lukasa/cryptography,sholsap...
from cryptography.hazmat.backends import openssl + from cryptography.hazmat.backends.multibackend import MultiBackend from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): f...
Make the default backend be a multi-backend
## Code Before: from cryptography.hazmat.backends import openssl from cryptography.hazmat.bindings.commoncrypto.binding import ( Binding as CommonCryptoBinding ) _ALL_BACKENDS = [openssl.backend] if CommonCryptoBinding.is_available(): from cryptography.hazmat.backends import commoncrypto _ALL_BACKENDS.ap...
... from cryptography.hazmat.backends import openssl from cryptography.hazmat.backends.multibackend import MultiBackend from cryptography.hazmat.bindings.commoncrypto.binding import ( ... _default_backend = MultiBackend(_ALL_BACKENDS) def default_backend(): return _default_backend ...
6eb4c09cfc43e2f939660525101a1a8fac9c4838
threadedcomments/forms.py
threadedcomments/forms.py
from django import forms from django.contrib.comments.forms import CommentForm from django.conf import settings from django.utils.hashcompat import sha_constructor from threadedcomments.models import ThreadedComment class ThreadedCommentForm(CommentForm): parent = forms.IntegerField(required=False, widget=forms.H...
from django import forms from django.contrib.comments.forms import CommentForm from django.conf import settings from django.utils.hashcompat import sha_constructor from threadedcomments.models import ThreadedComment class ThreadedCommentForm(CommentForm): parent = forms.IntegerField(required=False, widget=forms.H...
Make title field appear before comment in the form
Make title field appear before comment in the form Fixes #7
Python
bsd-3-clause
yrcjaya/django-threadedcomments,coxmediagroup/django-threadedcomments,nikolas/django-threadedcomments,ccnmtl/django-threadedcomments,yrcjaya/django-threadedcomments,nikolas/django-threadedcomments,SmithsonianEnterprises/django-threadedcomments,PolicyStat/django-threadedcomments,ccnmtl/django-threadedcomments,Smithsonia...
from django import forms from django.contrib.comments.forms import CommentForm from django.conf import settings from django.utils.hashcompat import sha_constructor from threadedcomments.models import ThreadedComment class ThreadedCommentForm(CommentForm): parent = forms.IntegerField(required=Fal...
Make title field appear before comment in the form
## Code Before: from django import forms from django.contrib.comments.forms import CommentForm from django.conf import settings from django.utils.hashcompat import sha_constructor from threadedcomments.models import ThreadedComment class ThreadedCommentForm(CommentForm): parent = forms.IntegerField(required=False...
... parent = forms.IntegerField(required=False, widget=forms.HiddenInput) ... def __init__(self, target_object, parent=None, data=None, initial=None): self.base_fields.insert( self.base_fields.keyOrder.index('comment'), 'title', forms.CharField(required=False) ...
12acfff456e1a696d1117b20b8843c6789ee38bb
wake/views.py
wake/views.py
from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) ...
from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', even...
Add Atom feed for events that have 'syndicate' set in their source config.
Add Atom feed for events that have 'syndicate' set in their source config.
Python
bsd-3-clause
chromakode/wake
from been.couch import CouchStore - from flask import render_template, abort + from flask import render_template, abort, request, url_for + from urlparse import urljoin + from werkzeug.contrib.atom import AtomFeed + from datetime import datetime from wake import app store = CouchStore().load() @app.route(...
Add Atom feed for events that have 'syndicate' set in their source config.
## Code Before: from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by...
# ... existing code ... from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app # ... modified code ... @app.route('/recent.atom') def recent_feed(): ...
7fa490cb598aca2848ce886dfc45bb8606f07e58
backend/geonature/core/gn_profiles/models.py
backend/geonature/core/gn_profiles/models.py
from geonature.utils.env import DB from utils_flask_sqla.serializers import serializable @serializable class VmCorTaxonPhenology(DB.Model): __tablename__ = "vm_cor_taxon_phenology" __table_args__ = {"schema": "gn_profiles"} cd_ref = DB.Column(DB.Integer) period = DB.Column(DB.Integer) id_nomenclatu...
from flask import current_app from geoalchemy2 import Geometry from utils_flask_sqla.serializers import serializable from utils_flask_sqla_geo.serializers import geoserializable from geonature.utils.env import DB @serializable class VmCorTaxonPhenology(DB.Model): __tablename__ = "vm_cor_taxon_phenology" __ta...
Add VM valid profile model
Add VM valid profile model
Python
bsd-2-clause
PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature,PnEcrins/GeoNature
+ from flask import current_app + from geoalchemy2 import Geometry + + from utils_flask_sqla.serializers import serializable + from utils_flask_sqla_geo.serializers import geoserializable + from geonature.utils.env import DB - from utils_flask_sqla.serializers import serializable @serializable class VmCorTax...
Add VM valid profile model
## Code Before: from geonature.utils.env import DB from utils_flask_sqla.serializers import serializable @serializable class VmCorTaxonPhenology(DB.Model): __tablename__ = "vm_cor_taxon_phenology" __table_args__ = {"schema": "gn_profiles"} cd_ref = DB.Column(DB.Integer) period = DB.Column(DB.Integer) ...
# ... existing code ... from flask import current_app from geoalchemy2 import Geometry from utils_flask_sqla.serializers import serializable from utils_flask_sqla_geo.serializers import geoserializable from geonature.utils.env import DB # ... modified code ... count_valid_data = DB.Column(DB.Integer) @...
8052577164ba144263c7f45e4c823ba396f19d65
badgekit_webhooks/views.py
badgekit_webhooks/views.py
from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.http import require_POST import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST def badge_issued_hook(request): try: data = json.loads(request.body) except ValueError: ...
from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST @csrf_exempt def badge_issued_hook(request): try...
Make webhook exempt from CSRF protection
Make webhook exempt from CSRF protection Soon, we will add JWT verification, to replace it.
Python
mit
tgs/django-badgekit-webhooks
from django.http import HttpResponse, HttpResponseBadRequest + from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST + @csrf_exempt def badge_issued_...
Make webhook exempt from CSRF protection
## Code Before: from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.http import require_POST import json def hello(request): return HttpResponse("Hello, world. Badges!!!") @require_POST def badge_issued_hook(request): try: data = json.loads(request.body) exce...
# ... existing code ... from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST # ... modified code ... @require_POST @csrf_exempt def badge_issued_hook(request): # ... rest of the code ...
e9f2a3c29185466f1c92121e9f4e4b727fb20fd0
scripts/rename_tutorial_src_files.py
scripts/rename_tutorial_src_files.py
from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") dirs = sorted([Path(f) for f in directory.iterdir()]) d: PurePath sufix = "__out__" for d in dirs: if d.name.endswith(sufix): continue output_dir_name = d.name + "__out__" output_directory = directo...
from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") skip_names = {"bigger_applications"} skip_dirs = {directory / name for name in skip_names} dirs = sorted([Path(f) for f in directory.iterdir() if f not in skip_dirs]) d: PurePath sufix = "__out__" for d in dirs: if...
Update tutorial renamer to exclude files
:sparkles: Update tutorial renamer to exclude files
Python
mit
tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi
from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") + skip_names = {"bigger_applications"} + skip_dirs = {directory / name for name in skip_names} - dirs = sorted([Path(f) for f in directory.iterdir()]) + dirs = sorted([Path(f) for f in directory.iterdir() if f ...
Update tutorial renamer to exclude files
## Code Before: from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") dirs = sorted([Path(f) for f in directory.iterdir()]) d: PurePath sufix = "__out__" for d in dirs: if d.name.endswith(sufix): continue output_dir_name = d.name + "__out__" output_dir...
# ... existing code ... directory = Path("./docs/tutorial/src") skip_names = {"bigger_applications"} skip_dirs = {directory / name for name in skip_names} dirs = sorted([Path(f) for f in directory.iterdir() if f not in skip_dirs]) d: PurePath # ... modified code ... files = sorted([Path(f) for f in d.iterdi...
c4e0a132461dba798739b752a04fe3ff66af17ab
tests/high_level_curl_test.py
tests/high_level_curl_test.py
import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localhost:8380/') def tearDown(self): self.curl.close() def test_reuse(se...
import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localhost:8380/') def tearDown(self): self.curl.close() def test_reuse(self): ...
Fix test suite on python 3 - high level curl object returns result as bytes
Fix test suite on python 3 - high level curl object returns result as bytes
Python
lgpl-2.1
pycurl/pycurl,pycurl/pycurl,pycurl/pycurl
import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localhost:8380/') - + def tearDown(self): self.curl.close...
Fix test suite on python 3 - high level curl object returns result as bytes
## Code Before: import curl import unittest from . import appmanager setup_module, teardown_module = appmanager.setup(('app', 8380)) class RelativeUrlTest(unittest.TestCase): def setUp(self): self.curl = curl.Curl('http://localhost:8380/') def tearDown(self): self.curl.close() d...
# ... existing code ... self.curl = curl.Curl('http://localhost:8380/') def tearDown(self): # ... modified code ... self.curl.close() def test_reuse(self): ... result = self.curl.get('/success') self.assertEqual('success', result.decode()) ... resul...
66e67e53360a9f49ae73c8c8f2de49991525363b
txircd/modules/cmode_t.py
txircd/modules/cmode_t.py
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(self.ir...
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(targetC...
Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
Python
bsd-3-clause
Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] - if "t" in targetChannel.mode and not ...
Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
## Code Before: from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.h...
# ... existing code ... targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(targetChannel.name, self.ircd.servconfig["channel_minimum_level"]["TOPIC"]): user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, targetChannel.name, ":You do not have access to change the topic on this channe...
e01b0c9129c05e366605639553201f0dc2af2756
django_fsm_log/apps.py
django_fsm_log/apps.py
from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' verbose_name = "Djang...
from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' verbose_name = "Djang...
Revert "Solve warning coming from django 4.0"
Revert "Solve warning coming from django 4.0"
Python
mit
gizmag/django-fsm-log,ticosax/django-fsm-log
from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' ...
Revert "Solve warning coming from django 4.0"
## Code Before: from __future__ import unicode_literals from django.apps import AppConfig from django.conf import settings from django.utils.module_loading import import_string from django_fsm.signals import pre_transition, post_transition class DjangoFSMLogAppConfig(AppConfig): name = 'django_fsm_log' verbo...
... verbose_name = "Django FSM Log" ...
a84c02b4369bf698c82be22b6231fe412ad67c63
Cauldron/ext/click/__init__.py
Cauldron/ext/click/__init__.py
try: import click except ImportError: raise ImportError("Cauldron.ext.click requires the click package.") from ...api import use __all__ = ['backend', 'service'] def select_backend(ctx, param, value): """Callback to set the Cauldron backend.""" if not value or ctx.resilient_parsing: return ...
try: import click except ImportError: raise ImportError("Cauldron.ext.click requires the click package.") from ...api import use __all__ = ['backend', 'service'] def select_backend(ctx, param, value): """Callback to set the Cauldron backend.""" if not value or ctx.resilient_parsing: return ...
Fix a bug in Cauldron click extension
Fix a bug in Cauldron click extension
Python
bsd-3-clause
alexrudy/Cauldron
try: import click except ImportError: raise ImportError("Cauldron.ext.click requires the click package.") from ...api import use __all__ = ['backend', 'service'] def select_backend(ctx, param, value): """Callback to set the Cauldron backend.""" if not value or ctx.resilient...
Fix a bug in Cauldron click extension
## Code Before: try: import click except ImportError: raise ImportError("Cauldron.ext.click requires the click package.") from ...api import use __all__ = ['backend', 'service'] def select_backend(ctx, param, value): """Callback to set the Cauldron backend.""" if not value or ctx.resilient_parsing: ...
# ... existing code ... return option(func) return decorate # ... rest of the code ...
d837a194e29b867443a3758bb4c159afe193e798
enumfields/fields.py
enumfields/fields.py
from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: choices = en...
from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: choices = en...
Revert "Add South introspection rules"
Revert "Add South introspection rules" They weren't correct. This reverts commit b7235e2fc4b28271e0dce8d812faa4a46ed84aea.
Python
mit
suutari-ai/django-enumfields,jessamynsmith/django-enumfields,bxm156/django-enumfields,jackyyf/django-enumfields
from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: ...
Revert "Add South introspection rules"
## Code Before: from django.core.exceptions import ValidationError from django.db import models import six class EnumFieldMixin(six.with_metaclass(models.SubfieldBase)): def __init__(self, enum, choices=None, max_length=10, **options): self.enum = enum if not choices: try: ...
... pass ...
38b4af0b3c1c6105d68ff453d86107758ef9d751
preconditions.py
preconditions.py
class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate
import inspect class PreconditionError (TypeError): pass def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'.format...
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
Python
mit
nejucomo/preconditions
+ import inspect + + class PreconditionError (TypeError): pass def preconditions(*precs): + + precinfo = [] + for p in precs: + spec = inspect.getargspec(p) + if spec.varargs or spec.keywords: + raise PreconditionError( + 'Precondition {!r} must not...
Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wrapping function.
## Code Before: class PreconditionError (TypeError): pass def preconditions(*precs): def decorate(f): def g(*a, **kw): return f(*a, **kw) return g return decorate ## Instruction: Implement two of the "early" InvalidPreconditionTests which can be checked prior to seeing the wra...
... import inspect class PreconditionError (TypeError): ... def preconditions(*precs): precinfo = [] for p in precs: spec = inspect.getargspec(p) if spec.varargs or spec.keywords: raise PreconditionError( 'Precondition {!r} must not accept * nor ** args.'...
e94503e25bff0ba986c28ce3f16636b3bb9f2c3d
green_django/__init__.py
green_django/__init__.py
import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'): import pymysql ...
import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'): import pymysql ...
Check for greened package - consistency
Check for greened package - consistency
Python
mit
philipn/green-monkey
import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'):...
Check for greened package - consistency
## Code Before: import sys from utils import module_exists from gevent import monkey def make_django_green(): monkey.patch_all() if module_exists('psycogreen'): from psycogreen.gevent.psyco_gevent import make_psycopg_green make_psycopg_green() if module_exists('pymysql'): impor...
... if module_exists('gevent_zeromq'): from gevent_zeromq import zmq ...
1d3e956dcf667601feb871eab2a462fa09d0d101
tests/test_length.py
tests/test_length.py
from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)], ) def test_le...
from math import fabs, sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import floats, isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)],...
Test the axioms of normed vector spaces
tests/length: Test the axioms of normed vector spaces
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
- from math import sqrt + from math import fabs, sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector - from utils import isclose, vectors + from utils import floats, isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), ...
Test the axioms of normed vector spaces
## Code Before: from math import sqrt import pytest # type: ignore from hypothesis import given from ppb_vector import Vector from utils import isclose, vectors @pytest.mark.parametrize( "x, y, expected", [(6, 8, 10), (8, 6, 10), (0, 0, 0), (-6, -8, 10), (1, 2, 2.23606797749979)...
... from math import fabs, sqrt ... from ppb_vector import Vector from utils import floats, isclose, vectors ... assert isclose(v.length, sqrt(v * v)) @given(v=vectors()) def test_length_zero(v: Vector): """1st axiom of normed vector spaces: |v| = 0 iff v = 0""" assert (v.length == 0) ==...
301463a99dceceb21ecec933f3a83e55ca37c3b8
wagtail/wagtailimages/api/admin/serializers.py
wagtail/wagtailimages/api/admin/serializers.py
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specif...
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition with the specif...
Use source keyword argument (instead of overriding get_attribute)
Use source keyword argument (instead of overriding get_attribute) This allows the ImageRenditionField to be used on models that contain an image field.
Python
bsd-3-clause
nealtodd/wagtail,mikedingjan/wagtail,FlipperPA/wagtail,torchbox/wagtail,iansprice/wagtail,jnns/wagtail,wagtail/wagtail,zerolab/wagtail,thenewguy/wagtail,iansprice/wagtail,zerolab/wagtail,rsalmaso/wagtail,gasman/wagtail,timorieber/wagtail,kaedroho/wagtail,mikedingjan/wagtail,torchbox/wagtail,thenewguy/wagtail,zerolab/wa...
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a...
Use source keyword argument (instead of overriding get_attribute)
## Code Before: from __future__ import absolute_import, unicode_literals from collections import OrderedDict from rest_framework.fields import Field from ...models import SourceImageIOError from ..v2.serializers import ImageSerializer class ImageRenditionField(Field): """ A field that generates a rendition...
# ... existing code ... def to_representation(self, image): # ... modified code ... class AdminImageSerializer(ImageSerializer): thumbnail = ImageRenditionField('max-165x165', source='*', read_only=True) # ... rest of the code ...
fd819ff0ff1a7d73dd58f152d2c4be8aea18e2d3
rebulk/processors.py
rebulk/processors.py
def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk.match.Match] """ to_remove_matches = set() for match in filter...
def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk.match.Match] """ to_remove_matches = set() for match in filter...
Fix issue when a private match is found multiple times
Fix issue when a private match is found multiple times
Python
mit
Toilal/rebulk
def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk.match.Match] """ to_remove_matches = s...
Fix issue when a private match is found multiple times
## Code Before: def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk.match.Match] """ to_remove_matches = set() for...
// ... existing code ... """ for match in list(matches): if match.private: matches.remove(match) // ... rest of the code ...
e3c1819b6b5ddec1ff326c3693d48ec8a8b3a834
fantail/tests/__init__.py
fantail/tests/__init__.py
tests_require = [ 'pytest', 'pytest-capturelog', 'pytest-cov', ]
tests_require = [ 'coveralls', 'pytest', 'pytest-capturelog', 'pytest-cov', ]
Add coveralls to test requirements
Add coveralls to test requirements
Python
bsd-2-clause
sjkingo/fantail,sjkingo/fantail,sjkingo/fantail
tests_require = [ + 'coveralls', 'pytest', 'pytest-capturelog', 'pytest-cov', ]
Add coveralls to test requirements
## Code Before: tests_require = [ 'pytest', 'pytest-capturelog', 'pytest-cov', ] ## Instruction: Add coveralls to test requirements ## Code After: tests_require = [ 'coveralls', 'pytest', 'pytest-capturelog', 'pytest-cov', ]
... tests_require = [ 'coveralls', 'pytest', ...
6fd1305f2a4a2e08b51c421b1c2cfdd33b407119
src/puzzle/problems/problem.py
src/puzzle/problems/problem.py
from data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): return self.s...
from data import meta _THRESHOLD = 0.01 class Problem(object): def __init__(self, name, lines, threshold=_THRESHOLD): self.name = name self.lines = lines self._threshold = threshold self._solutions = None self._constraints = [ lambda k, v: v > self._threshold ] @property def kind...
Set a threshold on Problem and enforce it.
Set a threshold on Problem and enforce it.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
from data import meta + + _THRESHOLD = 0.01 class Problem(object): - def __init__(self, name, lines): + def __init__(self, name, lines, threshold=_THRESHOLD): self.name = name self.lines = lines + self._threshold = threshold self._solutions = None - self._constraints = [] + ...
Set a threshold on Problem and enforce it.
## Code Before: from data import meta class Problem(object): def __init__(self, name, lines): self.name = name self.lines = lines self._solutions = None self._constraints = [] @property def kind(self): return str(type(self)).strip("'<>").split('.').pop() @property def solution(self): ...
# ... existing code ... from data import meta _THRESHOLD = 0.01 # ... modified code ... class Problem(object): def __init__(self, name, lines, threshold=_THRESHOLD): self.name = name ... self.lines = lines self._threshold = threshold self._solutions = None self._constraints = [ ...
0d2816e4ea0bf5a04794456651e79f7db9b2571f
src/jupyter_notebook_gist/config.py
src/jupyter_notebook_gist/config.py
from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The ...
import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', ...
Use six for correct Python2/3 compatibility
Use six for correct Python2/3 compatibility
Python
mpl-2.0
mreid-moz/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mreid-moz/jupyter-notebook-gist
+ import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Un...
Use six for correct Python2/3 compatibility
## Code Before: from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', ...
... import six from traitlets.config import LoggingConfigurable ... client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, six.string_types): client_id = None ...
1557de38bcc9fa4099655c210d7e2daf7c19d715
task/models.py
task/models.py
from django.db import models from django.conf import settings class Task(models.Model): title = models.CharField(max_length=50, unique=True) created_at = models.DateField() status = models.CharField(max_length=30, choices=settings.TASK_CHOICES) def __unicode__(self): # pragma: no cover retur...
import datetime from django.db import models from django.conf import settings class Task(models.Model): title = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=30, choices=settings.TASK_CHOICES) class Meta: ...
Set order getting the list of tasks
Set order getting the list of tasks
Python
mit
rosadurante/to_do,rosadurante/to_do
+ import datetime + from django.db import models from django.conf import settings class Task(models.Model): title = models.CharField(max_length=50, unique=True) - created_at = models.DateField() + created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=...
Set order getting the list of tasks
## Code Before: from django.db import models from django.conf import settings class Task(models.Model): title = models.CharField(max_length=50, unique=True) created_at = models.DateField() status = models.CharField(max_length=30, choices=settings.TASK_CHOICES) def __unicode__(self): # pragma: no cov...
... import datetime from django.db import models ... title = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=30, choices=settings.TASK_CHOICES) class Meta: ordering = ('-created_at',) ...
8b545ee63ec695a77ba08fa5ff45b7d6dd3d94f8
cuteshop/downloaders/git.py
cuteshop/downloaders/git.py
import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if 'tag' in source_i...
import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def _checkout(name): with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', name), stdout=DEVNULL, stderr=subprocess.STDOUT, ) de...
Add auto branch checkout functionality
Add auto branch checkout functionality
Python
mit
uranusjr/cuteshop
import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER + + + def _checkout(name): + with change_working_directory(DOWNLOAD_CONTAINER): + subprocess.call( + ('git', 'checkout', name), + stdout=DEVNULL, stderr=subprocess....
Add auto branch checkout functionality
## Code Before: import subprocess from ..utils import DEVNULL, change_working_directory from .base import DOWNLOAD_CONTAINER def download(source_info): url = source_info['git'] subprocess.call( ('git', 'clone', url, DOWNLOAD_CONTAINER), stdout=DEVNULL, stderr=subprocess.STDOUT, ) if '...
# ... existing code ... from .base import DOWNLOAD_CONTAINER def _checkout(name): with change_working_directory(DOWNLOAD_CONTAINER): subprocess.call( ('git', 'checkout', name), stdout=DEVNULL, stderr=subprocess.STDOUT, ) # ... modified code ... if 'tag' in sour...
b13efa6234c2748515a9c3f5a8fbb3ad43093083
test/test_device.py
test/test_device.py
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-...
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): rb_pv = 'SR01A-...
Raise assertion error when creating a device with no pv
Raise assertion error when creating a device with no pv
Python
apache-2.0
willrogers/pml,willrogers/pml
from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_devic...
Raise assertion error when creating a device with no pv
## Code Before: from pml.exceptions import PvException import pml.device import pytest import mock @pytest.fixture def create_device(readback, setpoint): _rb = readback _sp = setpoint device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock()) return device def test_set_device_value(): ...
// ... existing code ... with pytest.raises(AssertionError): create_device(None, None) // ... rest of the code ...
e1138ebffbdfe31d4a4acdb4e164bdd767c6e8ea
saylua/wrappers.py
saylua/wrappers.py
from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorated_function(*args, **kwar...
from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorated_function(*args, **kwar...
Fix for no role in admin access wrapper
Fix for no role in admin access wrapper
Python
agpl-3.0
LikeMyBread/Saylua,saylua/SayluaV2,LikeMyBread/Saylua,saylua/SayluaV2,saylua/SayluaV2,LikeMyBread/Saylua,LikeMyBread/Saylua
from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorate...
Fix for no role in admin access wrapper
## Code Before: from flask import redirect as _redirect, url_for, render_template, g from functools import wraps def login_required(f, redirect='login'): """Redirects non-logged in users to a specified location. Usage: `@login_required`, `@login_required(redirect=<url>)` """ @wraps(f) def decorated_functi...
... if not g.user.get_role() or not g.user.get_role().can_access_admin: return render_template('403.html'), 403 ...
aa65464c86c562a690ba42901fa9dc24f17ba714
xbrowse_server/base/management/commands/add_project.py
xbrowse_server/base/management/commands/add_project.py
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project exists :(") ...
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") ...
Print error if dot in project ids
Print error if dot in project ids
Python
agpl-3.0
ssadedin/seqr,ssadedin/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,ssadedin/seqr,macarthur-lab/xbrowse,ssadedin/seqr,ssadedin/seqr
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project - + import sys class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] + if "." in project_id: + sys.exit("ERROR: A '.' in the project ID is no...
Print error if dot in project ids
## Code Before: from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): def handle(self, *args, **options): project_id = args[0] if Project.objects.filter(project_id=project_id).exists(): raise Exception("Project e...
... from xbrowse_server.base.models import Project import sys ... project_id = args[0] if "." in project_id: sys.exit("ERROR: A '.' in the project ID is not supported") if Project.objects.filter(project_id=project_id).exists(): ...
eb0714767cf5c0fd89ff4e50e22445a5e436f94c
iopath/tabular/tabular_io.py
iopath/tabular/tabular_io.py
from typing import Any, Iterable from iopath.common.file_io import PathHandler class TabularUriParser: def parse_uri(self, uri: str) -> None: pass class TabularPathHandler(PathHandler): def _opent( self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any ) -> Iterable[Any]:...
from typing import Any from iopath.common.file_io import PathHandler, TabularIO class TabularUriParser: def parse_uri(self, uri: str) -> None: pass class TabularPathHandler(PathHandler): def _opent( self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any ) -> TabularIO: ...
Update type signature of AIRStorePathHandler.opent()
Update type signature of AIRStorePathHandler.opent() Summary: The previous diff updated the type signature of the `PathHandler.opent()` method to return a custom context manager. Here, we update the return type of the overriden `AIRStorePathHandler.opent()` method to return an implementation of the `PathHandlerContext...
Python
mit
facebookresearch/iopath,facebookresearch/iopath
- from typing import Any, Iterable + from typing import Any - from iopath.common.file_io import PathHandler + from iopath.common.file_io import PathHandler, TabularIO class TabularUriParser: def parse_uri(self, uri: str) -> None: pass class TabularPathHandler(PathHandler): de...
Update type signature of AIRStorePathHandler.opent()
## Code Before: from typing import Any, Iterable from iopath.common.file_io import PathHandler class TabularUriParser: def parse_uri(self, uri: str) -> None: pass class TabularPathHandler(PathHandler): def _opent( self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any ) -...
... from typing import Any from iopath.common.file_io import PathHandler, TabularIO ... self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any ) -> TabularIO: assert mode == "r" ...
9d162a2919a1c9b56ded74d40963fa022fc7943b
src/config/settings/testing.py
src/config/settings/testing.py
"""Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'default': { 'ENGINE': 'dj...
"""Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'default': { 'ENGINE': 'dj...
Disable logging in test runs
Disable logging in test runs SPEED!
Python
agpl-3.0
FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de
"""Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'defau...
Disable logging in test runs
## Code Before: """Django configuration for testing and CI environments.""" from .common import * # Use in-memory file storage DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage' # Speed! PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) # Database DATABASES = { 'default': { ...
# ... existing code ... # Disable logging import logging logging.disable(logging.CRITICAL) env = get_secret("ENVIRONMENT") # ... rest of the code ...
7352a257a08ad4d41261dd0c1076cde966d2a5c2
sharer/multi.py
sharer/multi.py
from .base import AbstractSharer class MultiSharer(AbstractSharer): def __init__(self, **kw): super(MultiSharer, self).__init__() self.sharers = {} self.add_sharers(**kw) def add_sharers(self, **kw): for key, val in kw.iteritems(): self.sharers[key] = val def ...
from .base import AbstractSharer class MultiSharer(AbstractSharer): def __init__(self, **kw): super(MultiSharer, self).__init__() self.sharers = {} self.add_sharers(**kw) def add_sharers(self, **kw): for key, val in kw.iteritems(): self.sharers[key] = val def ...
Add _services keyword argument to MultiSharer's send.
Add _services keyword argument to MultiSharer's send.
Python
mit
FelixLoether/python-sharer
from .base import AbstractSharer class MultiSharer(AbstractSharer): def __init__(self, **kw): super(MultiSharer, self).__init__() self.sharers = {} self.add_sharers(**kw) def add_sharers(self, **kw): for key, val in kw.iteritems(): self.shar...
Add _services keyword argument to MultiSharer's send.
## Code Before: from .base import AbstractSharer class MultiSharer(AbstractSharer): def __init__(self, **kw): super(MultiSharer, self).__init__() self.sharers = {} self.add_sharers(**kw) def add_sharers(self, **kw): for key, val in kw.iteritems(): self.sharers[key]...
# ... existing code ... def send(self, *args, **kw): services = kw.pop('_services', {}) for name, sharer in self.sharers.iteritems(): if services.get(name, True): services[name] = sharer.send(*args, **kw) return services # ... rest of the code ...
ef69cad1175fa92543fce085cd46a9ec990fa55b
nbresuse/__init__.py
nbresuse/__init__.py
from notebook.utils import url_path_join from tornado import ioloop from nbresuse.api import ApiHandler from nbresuse.config import ResourceUseDisplay from nbresuse.metrics import PSUtilMetricsLoader from nbresuse.prometheus import PrometheusHandler def _jupyter_server_extension_paths(): """ Set up the serve...
from notebook.utils import url_path_join from tornado import ioloop from nbresuse.api import ApiHandler from nbresuse.config import ResourceUseDisplay from nbresuse.metrics import PSUtilMetricsLoader from nbresuse.prometheus import PrometheusHandler def _jupyter_server_extension_paths(): """ Set up the serve...
Add back the /metrics endpoint
Add back the /metrics endpoint
Python
bsd-2-clause
yuvipanda/nbresuse,yuvipanda/nbresuse
from notebook.utils import url_path_join from tornado import ioloop from nbresuse.api import ApiHandler from nbresuse.config import ResourceUseDisplay from nbresuse.metrics import PSUtilMetricsLoader from nbresuse.prometheus import PrometheusHandler def _jupyter_server_extension_paths(): ""...
Add back the /metrics endpoint
## Code Before: from notebook.utils import url_path_join from tornado import ioloop from nbresuse.api import ApiHandler from nbresuse.config import ResourceUseDisplay from nbresuse.metrics import PSUtilMetricsLoader from nbresuse.prometheus import PrometheusHandler def _jupyter_server_extension_paths(): """ ...
... nbapp.web_app.settings["nbresuse_display_config"] = resuseconfig base_url = nbapp.web_app.settings["base_url"] nbapp.web_app.add_handlers( ".*", [ (url_path_join(base_url, "/api/nbresuse/v1"), ApiHandler), (url_path_join(base_url, "/metrics"), ApiHandler), ...