Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
aff0eba2c0f7f5a0c9bebbfc9402f04c2c9d6d11
preference/miExecPref.py
preference/miExecPref.py
import os import json SCRIPT_PATH = os.path.dirname(__file__) def getPreference(): """ Load pref json data nad return as dict""" prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r') prefDict = json.load(prefFile) prefFile.close() return prefDict def getWindowSe...
import os import json import maya.cmds as cmds SCRIPT_PATH = os.path.dirname(__file__) MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True) def getPreference(): """ Load pref json data nad return as dict""" for root, dirs, files in os.walk(MAYA_SCRIPT_DIR): if 'miExecPref.json' in file...
Load user pref file if exists in the maya user script directory
Load user pref file if exists in the maya user script directory
Python
mit
minoue/miExecutor
import os import json - + import maya.cmds as cmds SCRIPT_PATH = os.path.dirname(__file__) + MAYA_SCRIPT_DIR = cmds.internalVar(userScriptDir=True) def getPreference(): """ Load pref json data nad return as dict""" + for root, dirs, files in os.walk(MAYA_SCRIPT_DIR): + ...
Load user pref file if exists in the maya user script directory
## Code Before: import os import json SCRIPT_PATH = os.path.dirname(__file__) def getPreference(): """ Load pref json data nad return as dict""" prefFile = open(os.path.join(SCRIPT_PATH, "miExecPref.json"), 'r') prefDict = json.load(prefFile) prefFile.close() return prefDict def getWindowSet...
7b5850d1b89d34ff9a60c3862d18691961c86656
poisson/tests/test_irf.py
poisson/tests/test_irf.py
from numpy.testing import assert_almost_equal, assert_array_less import numpy as np from poisson import BmiPoisson def test_grid_initialize(): model = BmiPoisson() model.initialize() assert_almost_equal(model.get_current_time(), 0.) assert_array_less(model.get_value('land_surface__elevation'), 1.) ...
from nose.tools import assert_equal from numpy.testing import assert_almost_equal, assert_array_less import numpy as np from poisson import BmiPoisson def test_initialize_defaults(): model = BmiPoisson() model.initialize() assert_almost_equal(model.get_current_time(), 0.) assert_array_less(model.get...
Test initialize with filename and file-like.
Test initialize with filename and file-like.
Python
mit
mperignon/bmi-delta,mperignon/bmi-STM,mperignon/bmi-STM,mperignon/bmi-delta
+ from nose.tools import assert_equal from numpy.testing import assert_almost_equal, assert_array_less import numpy as np from poisson import BmiPoisson - def test_grid_initialize(): + def test_initialize_defaults(): model = BmiPoisson() model.initialize() assert_almost_equal(model.g...
Test initialize with filename and file-like.
## Code Before: from numpy.testing import assert_almost_equal, assert_array_less import numpy as np from poisson import BmiPoisson def test_grid_initialize(): model = BmiPoisson() model.initialize() assert_almost_equal(model.get_current_time(), 0.) assert_array_less(model.get_value('land_surface__el...
7c68e3b00e7c66c0223617447e16a7159118d284
goldstone/addons/utils.py
goldstone/addons/utils.py
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
Change update_addon_node() to return the Addon node, whether created or found.
Change update_addon_node() to return the Addon node, whether created or found.
Python
apache-2.0
slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
Change update_addon_node() to return the Addon node, whether created or found.
## Code Before: """Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
0fb7e8d901addc801fb9b99d744666f573f672d3
billjobs/migrations/0003_auto_20160822_2341.py
billjobs/migrations/0003_auto_20160822_2341.py
from __future__ import unicode_literals from django.db import migrations def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_model('billjobs', 'Bill') for bill in Bill.objects.all(): bill.billing_...
from __future__ import unicode_literals from django.db import migrations, models def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_model('billjobs', 'Bill') for bill in Bill.objects.all(): bill....
Add billing_address and migrate data
Add billing_address and migrate data
Python
mit
ioO/billjobs
from __future__ import unicode_literals - from django.db import migrations + from django.db import migrations, models def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_model('billjobs', 'Bil...
Add billing_address and migrate data
## Code Before: from __future__ import unicode_literals from django.db import migrations def add_billing_address(apps, schema_editor): ''' Data migration add billing_address in Bill from user billing_address field ''' Bill = apps.get_model('billjobs', 'Bill') for bill in Bill.objects.all(): ...
bbb4496a99a5c65218b12c56de01c12ab83a1056
demo/recent_questions.py
demo/recent_questions.py
from __future__ import print_function # Same directory hack import sys sys.path.append('.') sys.path.append('..') try: get_input = raw_input except NameError: get_input = input user_api_key = get_input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None imp...
from __future__ import print_function from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Sit...
Use six function for input() in recent questions demo
Use six function for input() in recent questions demo
Python
bsd-3-clause
Khilo84/Py-StackExchange,lucjon/Py-StackExchange,damanjitsingh/StackExchange-python-
from __future__ import print_function + from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') - try: - get_input = raw_input - except NameError: - get_input = input - - user_api_key = get_input("Please enter an API key if you have one (Return fo...
Use six function for input() in recent questions demo
## Code Before: from __future__ import print_function # Same directory hack import sys sys.path.append('.') sys.path.append('..') try: get_input = raw_input except NameError: get_input = input user_api_key = get_input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api...
d358a759d86ce2a377e4fef84f20075bd0481d3b
ditto/flickr/views.py
ditto/flickr/views.py
from ..ditto.views import PaginatedListView from .models import Account, Photo, User class Home(PaginatedListView): template_name = 'flickr/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['account_list'] = Account.objects.all() r...
from ..ditto.views import PaginatedListView from .models import Account, Photo, User class Home(PaginatedListView): template_name = 'flickr/index.html' paginate_by = 48 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['account_list'] = Account.ob...
Change number of photos per page
Change number of photos per page
Python
mit
philgyford/django-ditto,philgyford/django-ditto,philgyford/django-ditto
from ..ditto.views import PaginatedListView from .models import Account, Photo, User class Home(PaginatedListView): template_name = 'flickr/index.html' + paginate_by = 48 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['acc...
Change number of photos per page
## Code Before: from ..ditto.views import PaginatedListView from .models import Account, Photo, User class Home(PaginatedListView): template_name = 'flickr/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['account_list'] = Account.objects...
7560bce01be5560395dd2373e979dbee086f3c21
py2app/converters/nibfile.py
py2app/converters/nibfile.py
import subprocess, os from py2app.decorators import converts @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() if xit != 0: ...
from __future__ import print_function import subprocess, os from py2app.decorators import converts gTool = None def _get_ibtool(): global gTool if gTool is None: if os.path.exists('/usr/bin/xcrun'): gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:-1] else: ...
Simplify nib compiler and support recent Xcode versions by using xcrun
Simplify nib compiler and support recent Xcode versions by using xcrun
Python
mit
metachris/py2app,metachris/py2app,metachris/py2app,metachris/py2app
+ from __future__ import print_function import subprocess, os from py2app.decorators import converts + + gTool = None + def _get_ibtool(): + global gTool + if gTool is None: + if os.path.exists('/usr/bin/xcrun'): + gTool = subprocess.check_output(['/usr/bin/xcrun', '-find', 'ibtool'])[:...
Simplify nib compiler and support recent Xcode versions by using xcrun
## Code Before: import subprocess, os from py2app.decorators import converts @converts(suffix=".xib") def convert_xib(source, destination, dry_run=0): destination = destination[:-4] + ".nib" if dry_run: return p = subprocess.Popen(['ibtool', '--compile', destination, source]) xit = p.wait() ...
b6d08abf7bc4aafaeec59944bdcdf8ae4a9352d5
recipe_scrapers/consts.py
recipe_scrapers/consts.py
import re TIME_REGEX = re.compile( r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z' ) HTML_SYMBOLS = '\xa0' # &nbsp;
import re TIME_REGEX = re.compile( r'\A(\s*(?P<hours>\d+)\s*(hours|hrs|hr|h))?(\s*(?P<minutes>\d+)\s*(minutes|mins|min|m))?\Z' ) HTML_SYMBOLS = '\xa0' # &nbsp;
Update time_regex captcher so to work with more sites
Update time_regex captcher so to work with more sites
Python
mit
hhursev/recipe-scraper
import re TIME_REGEX = re.compile( - r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z' + r'\A(\s*(?P<hours>\d+)\s*(hours|hrs|hr|h))?(\s*(?P<minutes>\d+)\s*(minutes|mins|min|m))?\Z' ) HTML_SYMBOLS = '\xa0' # &nbsp;
Update time_regex captcher so to work with more sites
## Code Before: import re TIME_REGEX = re.compile( r'\A(\s*(?P<hours>\d+)\s{1}(hours|hrs|hr|h))?((?P<minutes>\s*\d+)\s{1}(minutes|mins|min|m))?\Z' ) HTML_SYMBOLS = '\xa0' # &nbsp; ## Instruction: Update time_regex captcher so to work with more sites ## Code After: import re TIME_REGEX = re.compile( r'\A...
c0de2a081cfe9af7f6b9d39daae557d45f5d69ee
middleware/module_yaml.py
middleware/module_yaml.py
from __future__ import unicode_literals import os import yaml def main(app, data): filepath = os.path.join(app.data_dir, data.get('filename')) with open(filepath, 'r') as f: contents = yaml.load(f) return contents
from __future__ import unicode_literals import os import yaml import requests def local(app, data): filepath = os.path.join(app.data_dir, data.get('filename')) with open(filepath, 'r') as f: contents = yaml.load(f) return contents def remote(app, data): r = requests.get(data.get('url')) ...
Allow remote and local files.
Allow remote and local files.
Python
mit
myles/me-api,myles/me-api
from __future__ import unicode_literals import os import yaml + import requests - def main(app, data): + def local(app, data): filepath = os.path.join(app.data_dir, data.get('filename')) with open(filepath, 'r') as f: contents = yaml.load(f) return contents + + de...
Allow remote and local files.
## Code Before: from __future__ import unicode_literals import os import yaml def main(app, data): filepath = os.path.join(app.data_dir, data.get('filename')) with open(filepath, 'r') as f: contents = yaml.load(f) return contents ## Instruction: Allow remote and local files. ## Code After: fr...
2c8351ff8691eb9ad3009d316d932528d6f5c57d
runtests.py
runtests.py
import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { 'default': { 'E...
import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { 'default': { 'E...
Add more verbosity on test running
:lipstick: Add more verbosity on test running
Python
mit
kmike/django-widget-tweaks,daniboy/django-widget-tweaks
import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { '...
Add more verbosity on test running
## Code Before: import sys import os import django from django.conf import settings from django.core.management import call_command sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) opts = {'INSTALLED_APPS': ['widget_tweaks']} if django.VERSION[:2] < (1, 5): opts['DATABASES'] = { 'default': ...
4359a9947c1d86d9e4003c1e8fc358e9a66c6b1d
DisplayAdapter/display_adapter/scripts/init_db.py
DisplayAdapter/display_adapter/scripts/init_db.py
__author__ = 'richard'
import sys import sqlite3 from display_adapter import db_name help_message = """ This initialises an sqlite3 db for the purposes of the DisplayAdapter programs. Arguments: init_db.py database_name """ runs_table = """ CREATE TABLE runs ( id INTEGER NOT NULL, input_pattern VARCHAR, time_slot DATETIME, ...
Create internal db initialisation script
Create internal db initialisation script Paired by Michael and Richard
Python
mit
CO600GOL/Game_of_life,CO600GOL/Game_of_life,CO600GOL/Game_of_life
- __author__ = 'richard' + import sys + import sqlite3 + from display_adapter import db_name + help_message = """ + This initialises an sqlite3 db for the purposes of the DisplayAdapter programs. + + Arguments: init_db.py database_name + """ + + runs_table = """ + CREATE TABLE runs ( + id INTEGER NOT NULL, + ...
Create internal db initialisation script
## Code Before: __author__ = 'richard' ## Instruction: Create internal db initialisation script ## Code After: import sys import sqlite3 from display_adapter import db_name help_message = """ This initialises an sqlite3 db for the purposes of the DisplayAdapter programs. Arguments: init_db.py database_name """ runs...
4e9dfbaff5a91af75e3b18e6b4e06379747c6083
research_pyutils/__init__.py
research_pyutils/__init__.py
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: from .menpo_related import (resize_all_images, from_ln_to_bb_p...
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: from .menpo_related import (resize_all_images, from_ln_to_bb_p...
Add in the init the newly introduced function
Add in the init the newly introduced function
Python
apache-2.0
grigorisg9gr/pyutils,grigorisg9gr/pyutils
from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: from .menpo_related import (resize_all_images, f...
Add in the init the newly introduced function
## Code Before: from .path_related import (mkdir_p, rm_if_exists, remove_empty_paths, copy_contents_of_folder, count_files, copy_the_previous_if_missing, folders_last_modification) try: from .menpo_related import (resize_all_images,...
76c87d06efaac19350d870cd1c95229ed0a66c29
editdistance/__init__.py
editdistance/__init__.py
from .bycython import eval __all__ = ('eval',)
from .bycython import eval def distance(*args, **kwargs): """"An alias to eval""" return eval(*args, **kwargs) __all__ = ('eval', 'distance')
Add alias method named "distance"
Add alias method named "distance"
Python
mit
aflc/editdistance,aflc/editdistance,aflc/editdistance
from .bycython import eval - __all__ = ('eval',) + + def distance(*args, **kwargs): + """"An alias to eval""" + return eval(*args, **kwargs) + + + __all__ = ('eval', 'distance') +
Add alias method named "distance"
## Code Before: from .bycython import eval __all__ = ('eval',) ## Instruction: Add alias method named "distance" ## Code After: from .bycython import eval def distance(*args, **kwargs): """"An alias to eval""" return eval(*args, **kwargs) __all__ = ('eval', 'distance')
aff77b144c1a1895c9e8c0ca2d4e79451525901c
terminus/models/trunk.py
terminus/models/trunk.py
from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) self.add_lane(-2) def accept(self, generator): generator.start_trunk(self) for lane in self.lanes(): lane.accept(generator) g...
from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) self.add_lane(-2, reversed=True) def accept(self, generator): generator.start_trunk(self) for lane in self.lanes(): lane.accept(gener...
Make Trunks have opposite directions in the included lanes
Make Trunks have opposite directions in the included lanes
Python
apache-2.0
ekumenlabs/terminus,ekumenlabs/terminus
from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) - self.add_lane(-2) + self.add_lane(-2, reversed=True) def accept(self, generator): generator.start_trunk(self) f...
Make Trunks have opposite directions in the included lanes
## Code Before: from road import Road class Trunk(Road): def __init__(self, name=None): super(Trunk, self).__init__(name) self.add_lane(2) self.add_lane(-2) def accept(self, generator): generator.start_trunk(self) for lane in self.lanes(): lane.accept(gene...
e8940b632737f75897c0ea7c108563a63f1a5dde
transducer/test/test_functional.py
transducer/test/test_functional.py
import unittest from transducer.functional import compose class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = compose(f) # We can't test the equivalence of functions completely, so... self...
import unittest from transducer.functional import compose, true, identity, false class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = compose(f) # We can't test the equivalence of functions complet...
Improve test coverage of functional.py.
Improve test coverage of functional.py.
Python
mit
sixty-north/python-transducers
import unittest - from transducer.functional import compose + from transducer.functional import compose, true, identity, false class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = co...
Improve test coverage of functional.py.
## Code Before: import unittest from transducer.functional import compose class TestComposition(unittest.TestCase): def test_single(self): """ compose(f)(x) -> f(x) """ f = lambda x: x * 2 c = compose(f) # We can't test the equivalence of functions completely, so...
2408c5260106e050557b4898d5826932eb758142
normandy/selfrepair/views.py
normandy/selfrepair/views.py
from django.shortcuts import render from normandy.base.decorators import api_cache_control @api_cache_control() def repair(request, locale): return render(request, "selfrepair/repair.html")
from django.shortcuts import render from django.views.decorators.cache import cache_control ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7 @cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS) def repair(request, locale): return render(request, "selfrepair/repair.html")
Increase cache on deprecated self-repair to one week
Increase cache on deprecated self-repair to one week This view serves a message that the system is no longer active. We keep it around because it is still gets about 40 million hits per day, primarily from Firefox ESR 52, which never got the Normandy client. Notably, when we dropped support for Windows XP from Firefox...
Python
mpl-2.0
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
from django.shortcuts import render - - from normandy.base.decorators import api_cache_control + from django.views.decorators.cache import cache_control - @api_cache_control() + ONE_WEEK_IN_SECONDS = 60 * 60 * 24 * 7 + + + @cache_control(public=True, max_age=ONE_WEEK_IN_SECONDS) def repair(request, locale)...
Increase cache on deprecated self-repair to one week
## Code Before: from django.shortcuts import render from normandy.base.decorators import api_cache_control @api_cache_control() def repair(request, locale): return render(request, "selfrepair/repair.html") ## Instruction: Increase cache on deprecated self-repair to one week ## Code After: from django.shortcuts ...
dd260182bd8157fd6ac2a266b3ae5cf168400266
tests/custom_keywords.py
tests/custom_keywords.py
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_should_contain_num_m...
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) if not os.path.isdir(maildir): return for fname in os.listdir(maildir): os.remove(os.path.join...
Make Clear Inbox keyword more robust.
Make Clear Inbox keyword more robust.
Python
bsd-3-clause
andialbrecht/sentry-comments,andialbrecht/sentry-comments
import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) + if not os.path.isdir(maildir): + return for fname in os.listdir(maildir): ...
Make Clear Inbox keyword more robust.
## Code Before: import os from raven import Client def generate_event(msg, dsn): client = Client(dsn) client.captureMessage(msg) def clear_inbox(maildir): print('Clearing inbox at {}'.format(maildir)) for fname in os.listdir(maildir): os.remove(os.path.join(maildir, fname)) def inbox_shou...
114f40dd282d1837db42ffb6625760d1483d3192
jfu/templatetags/jfutags.py
jfu/templatetags/jfutags.py
from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', upload_handler_name =...
from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', upload_handler_name =...
Allow args and kwargs to upload_handler_name
Allow args and kwargs to upload_handler_name Now can use args and kwargs for reverse url. Example in template: {% jfu 'core/core_fileuploader.html' 'core_upload' object_id=1 content_type_str='app.model' %}
Python
bsd-3-clause
Alem/django-jfu,dzhuang/django-jfu,Alem/django-jfu,dzhuang/django-jfu,Alem/django-jfu,dzhuang/django-jfu,dzhuang/django-jfu,Alem/django-jfu
from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', - ...
Allow args and kwargs to upload_handler_name
## Code Before: from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.template import Library, Context, loader register = Library() @register.simple_tag( takes_context = True ) def jfu( context, template_name = 'jfu/upload_form.html', uploa...
9f3289f45c727835c8f52b0c2489b06da2f03c25
pyglab/__init__.py
pyglab/__init__.py
__title__ = 'pyglab' __version__ = '0.0dev' __author__ = 'Michael Schlottke' __license__ = 'MIT License' __copyright__ = '(c) 2014 Michael Schlottke' from .pyglab import Pyglab from .apirequest import ApiRequest, RequestType
__title__ = 'pyglab' __version__ = '0.0dev' __author__ = 'Michael Schlottke' __license__ = 'MIT License' __copyright__ = '(c) 2014 Michael Schlottke' from .pyglab import Pyglab from .exceptions import RequestError from .apirequest import ApiRequest, RequestType
Make RequestError available in package root.
Make RequestError available in package root.
Python
mit
sloede/pyglab,sloede/pyglab
__title__ = 'pyglab' __version__ = '0.0dev' __author__ = 'Michael Schlottke' __license__ = 'MIT License' __copyright__ = '(c) 2014 Michael Schlottke' from .pyglab import Pyglab + from .exceptions import RequestError from .apirequest import ApiRequest, RequestType
Make RequestError available in package root.
## Code Before: __title__ = 'pyglab' __version__ = '0.0dev' __author__ = 'Michael Schlottke' __license__ = 'MIT License' __copyright__ = '(c) 2014 Michael Schlottke' from .pyglab import Pyglab from .apirequest import ApiRequest, RequestType ## Instruction: Make RequestError available in package root. ## Code After: _...
cd2bc29837d31d8999d9f72f7ddaecddb56e26a5
tests/unit/test_views.py
tests/unit/test_views.py
from flask import json from nose.tools import eq_ from server import app client = app.test_client() def test_hello_world(): # When: I access root path resp = client.get('/') # Then: Expected response is returned eq_(resp.status_code, 200) eq_(resp.headers['Content-Type'], 'application/json') ...
from flask import json from nose.tools import eq_ from server import app client = app.test_client() def test_hello_world(): # When: I access root path resp = client.get('/') # Then: Expected response is returned eq_(resp.status_code, 200) eq_(resp.headers['Content-Type'], 'application/json') ...
Use startswith instead of exact string match
Use startswith instead of exact string match
Python
mit
agarone-mm/scholastic-demo,totem/totem-demo,risingspiral/appnexus-demo
from flask import json from nose.tools import eq_ from server import app client = app.test_client() def test_hello_world(): # When: I access root path resp = client.get('/') # Then: Expected response is returned eq_(resp.status_code, 200) eq_(resp.headers['Content-Typ...
Use startswith instead of exact string match
## Code Before: from flask import json from nose.tools import eq_ from server import app client = app.test_client() def test_hello_world(): # When: I access root path resp = client.get('/') # Then: Expected response is returned eq_(resp.status_code, 200) eq_(resp.headers['Content-Type'], 'applic...
b30d4301d58766471f435536cf804f7a63448ac5
qotr/tests/test_server.py
qotr/tests/test_server.py
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() def te...
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() # def t...
Disable testing for index.html, needs ember build
Disable testing for index.html, needs ember build Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com>
Python
agpl-3.0
rmoorman/qotr,rmoorman/qotr,sbuss/qotr,rmoorman/qotr,crodjer/qotr,sbuss/qotr,crodjer/qotr,sbuss/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,rmoorman/qotr,crodjer/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,sbuss/qotr,crodjer/qotr
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return m...
Disable testing for index.html, needs ember build
## Code Before: from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_applicatio...
cda81a4585d2b2be868e784566f3c804feb1e9bf
analyze.py
analyze.py
import sys import re def main(argv): # Message to perform sentiment analysis on message = argv[0] if len(argv) > 0 else "" if message == "": print("Usage: python analyze.py [message]") sys.exit(1) # Load the positive and negative words words = {} with open("words/positive.txt"...
import sys import re def main(argv): # Load the positive and negative words words = {} with open("words/positive.txt") as file: for line in file: words[line.rstrip()] = 1 with open("words/negative.txt") as file: for line in file: words[line.rstrip()] = -1 #...
Read from standard input and perform on each line
Read from standard input and perform on each line The analyze script can now be run with, for example - echo "Message" | python analyze.py - cat | python analyze.py (enter messages and end with Ctrl-D) - python analyze.py < filename - MapReduce (at some point)
Python
mit
timvandermeij/sentiment-analysis,timvandermeij/sentiment-analysis
import sys import re def main(argv): - # Message to perform sentiment analysis on - message = argv[0] if len(argv) > 0 else "" - - if message == "": - print("Usage: python analyze.py [message]") - sys.exit(1) - # Load the positive and negative words words = {} wi...
Read from standard input and perform on each line
## Code Before: import sys import re def main(argv): # Message to perform sentiment analysis on message = argv[0] if len(argv) > 0 else "" if message == "": print("Usage: python analyze.py [message]") sys.exit(1) # Load the positive and negative words words = {} with open("wor...
ac3c0e93adf35015d7f6cfc8c6cf2e6ec45cdeae
server/canonicalization/relationship_mapper.py
server/canonicalization/relationship_mapper.py
"""Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common def canonicalize_relationship(text): words = common.clean_text(text).split() freq = ...
"""Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function import repoze.lru from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common @repoze.lru.lru_cache(4096) def canonicalize_relationship(text): words...
Add LRU for relationship mapper.
[master] Add LRU for relationship mapper.
Python
mit
hotpxl/canonicalization-server,hotpxl/canonicalization-server
"""Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function + import repoze.lru from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common + @repoze.lru.lru_cache(4096) def canonicalize_relat...
Add LRU for relationship mapper.
## Code Before: """Contains functions to canonicalize relationships.""" from __future__ import absolute_import from __future__ import print_function from nltk.corpus import wordnet from .utils import wordnet_helper from .utils import common def canonicalize_relationship(text): words = common.clean_text(text).spl...
452924faafcfb4dcb1eb960ea30ab000f1f93962
migrations/versions/0245_archived_flag_jobs.py
migrations/versions/0245_archived_flag_jobs.py
from alembic import op import sqlalchemy as sa revision = '0245_archived_flag_jobs' down_revision = '0244_another_letter_org' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=sa.false())) ...
from alembic import op import sqlalchemy as sa revision = '0245_archived_flag_jobs' down_revision = '0244_another_letter_org' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True)) op.execute('update jobs set...
Update jobs archived flag before setting the default value
Update jobs archived flag before setting the default value Running an update before setting the column default value reduces the time the table is locked (since most rows don't have a NULL value anymore), but the migration takes slightly longer to run overall.
Python
mit
alphagov/notifications-api,alphagov/notifications-api
from alembic import op import sqlalchemy as sa revision = '0245_archived_flag_jobs' down_revision = '0244_another_letter_org' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### + op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=True)) + op....
Update jobs archived flag before setting the default value
## Code Before: from alembic import op import sqlalchemy as sa revision = '0245_archived_flag_jobs' down_revision = '0244_another_letter_org' def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('jobs', sa.Column('archived', sa.Boolean(), nullable=False, server_default=...
e3a530d741529a7bbfeb274c232e2c6b8a5faddc
kokki/cookbooks/postgresql9/recipes/default.py
kokki/cookbooks/postgresql9/recipes/default.py
import os from kokki import Execute, Package apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list' Execute("apt-update-postgresql9", command = "apt-get update", action = "nothing") apt = None if env.system.platform == "ubuntu": Package("python-software-properties") Execute("add-apt-re...
import os from kokki import Execute, Package if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]): apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list' Execute("apt-update-postgresql9", command = "apt-get update", action = "nothing") apt = N...
Use standard repo for postgresql9 in ubuntu 11.10
Use standard repo for postgresql9 in ubuntu 11.10
Python
bsd-3-clause
samuel/kokki
import os from kokki import Execute, Package + if not (env.system.platform == "ubuntu" and env.system.lsb['release'] in ["11.10"]): - apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list' + apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list' - Execute("apt-update-postgres...
Use standard repo for postgresql9 in ubuntu 11.10
## Code Before: import os from kokki import Execute, Package apt_list_path = '/etc/apt/sources.list.d/pitti-postgresql-lucid.list' Execute("apt-update-postgresql9", command = "apt-get update", action = "nothing") apt = None if env.system.platform == "ubuntu": Package("python-software-properties") Exe...
8e47696a805cce70989a79cc6e8324aaec870f6d
electionleaflets/apps/people/devs_dc_helpers.py
electionleaflets/apps/people/devs_dc_helpers.py
import requests from django.conf import settings class DevsDCAPIHelper: def __init__(self): self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN self.base_url = "https://developers.democracyclub.org.uk/api/v1" def make_request(self, endpoint, **params): default_params = { "auth_...
import requests from django.conf import settings class DevsDCAPIHelper: def __init__(self): self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN self.base_url = "https://developers.democracyclub.org.uk/api/v1" self.ballot_cache = {} def make_request(self, endpoint, **params): defaul...
Add a cached ballot fetcher to the DevsDC helper
Add a cached ballot fetcher to the DevsDC helper If we happen to run out of RAM in Lambda (we won't), Lambda will just kill the function and invoke a new one next time.
Python
mit
DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets
import requests from django.conf import settings class DevsDCAPIHelper: def __init__(self): self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN self.base_url = "https://developers.democracyclub.org.uk/api/v1" + self.ballot_cache = {} def make_request(self, endpoint, *...
Add a cached ballot fetcher to the DevsDC helper
## Code Before: import requests from django.conf import settings class DevsDCAPIHelper: def __init__(self): self.AUTH_TOKEN = settings.DEVS_DC_AUTH_TOKEN self.base_url = "https://developers.democracyclub.org.uk/api/v1" def make_request(self, endpoint, **params): default_params = { ...
00c808efd2ab38bcf9d808dcb784c9360a19937f
api/radar_api/views/organisation_consultants.py
api/radar_api/views/organisation_consultants.py
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView class OrganisationConsultantListView(ListCreateModelView): serializer_class = OrganisationCon...
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView from radar.permissions import AdminPermission class OrganisationConsultantListView(ListCreateMode...
Add permissions to organisation consultants endpoint
Add permissions to organisation consultants endpoint
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView + from radar.permissions import AdminPermission class OrganisationConsultantListView(...
Add permissions to organisation consultants endpoint
## Code Before: from radar_api.serializers.organisation_consultants import OrganisationConsultantSerializer from radar.models import OrganisationConsultant from radar.views.core import RetrieveUpdateDestroyModelView, ListCreateModelView class OrganisationConsultantListView(ListCreateModelView): serializer_class =...
c977e1c235ccb040f28bc03c63d2667924d5edd3
pythonforandroid/recipes/xeddsa/__init__.py
pythonforandroid/recipes/xeddsa/__init__.py
from pythonforandroid.recipe import CythonRecipe from pythonforandroid.toolchain import current_directory, shprint from os.path import join import sh class XedDSARecipe(CythonRecipe): name = 'xeddsa' version = '0.4.4' url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz' dep...
from pythonforandroid.recipe import CythonRecipe from pythonforandroid.toolchain import current_directory, shprint from os.path import join import sh class XedDSARecipe(CythonRecipe): name = 'xeddsa' version = '0.4.4' url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}.tar.gz' dep...
Fix xeddsa crypto_sign shared lib copy
Fix xeddsa crypto_sign shared lib copy Could be `_crypto_sign.cpython-37m-x86_64-linux-gnu.so` or simply `_crypto_sign.so` depending on the platform/distribution
Python
mit
germn/python-for-android,rnixx/python-for-android,rnixx/python-for-android,germn/python-for-android,rnixx/python-for-android,kivy/python-for-android,PKRoma/python-for-android,germn/python-for-android,germn/python-for-android,kronenpj/python-for-android,kivy/python-for-android,kronenpj/python-for-android,kivy/python-for...
from pythonforandroid.recipe import CythonRecipe from pythonforandroid.toolchain import current_directory, shprint from os.path import join import sh class XedDSARecipe(CythonRecipe): name = 'xeddsa' version = '0.4.4' url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{vers...
Fix xeddsa crypto_sign shared lib copy
## Code Before: from pythonforandroid.recipe import CythonRecipe from pythonforandroid.toolchain import current_directory, shprint from os.path import join import sh class XedDSARecipe(CythonRecipe): name = 'xeddsa' version = '0.4.4' url = 'https://pypi.python.org/packages/source/X/XEdDSA/XEdDSA-{version}...
6deab74e41cabcb9a3fb4075f270a9cdd591a435
pgallery/tests/test_utils.py
pgallery/tests/test_utils.py
from __future__ import unicode_literals import unittest from ..models import sanitize_exif_value class SanitizeExifValueTestCase(unittest.TestCase): def test_strip_null_bytes(self): """ Check that null bytes are stripped from the string. """ key = "not relevant" value = "...
from __future__ import unicode_literals import unittest from ..models import sanitize_exif_value class SanitizeExifValueTestCase(unittest.TestCase): def test_strip_null_bytes(self): """ Check that null bytes are stripped from the string. """ key = "not relevant" value = "...
Test type coercion in sanitize_exif_value
Test type coercion in sanitize_exif_value
Python
mit
zsiciarz/django-pgallery,zsiciarz/django-pgallery
from __future__ import unicode_literals import unittest from ..models import sanitize_exif_value class SanitizeExifValueTestCase(unittest.TestCase): def test_strip_null_bytes(self): """ Check that null bytes are stripped from the string. """ key = "not r...
Test type coercion in sanitize_exif_value
## Code Before: from __future__ import unicode_literals import unittest from ..models import sanitize_exif_value class SanitizeExifValueTestCase(unittest.TestCase): def test_strip_null_bytes(self): """ Check that null bytes are stripped from the string. """ key = "not relevant" ...
42709afec9f2e2ed419365f61324ce0c8ff96423
budget/forms.py
budget/forms.py
from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): class Meta: model = Budget fields = ('name', 'start_date') def save(self): if not self.instance.slug: self.in...
import datetime from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget) class Meta: ...
Split the start_date for better data entry (and Javascript date pickers).
Split the start_date for better data entry (and Javascript date pickers).
Python
bsd-3-clause
jokimies/django-pj-budget,jokimies/django-pj-budget,toastdriven/django-budget,toastdriven/django-budget,jokimies/django-pj-budget
+ import datetime from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): + start_date = forms.DateTimeField(initial=datetime.datetime.now, required=False, widget=forms.SplitDateTimeWidget) + ...
Split the start_date for better data entry (and Javascript date pickers).
## Code Before: from django import forms from django.template.defaultfilters import slugify from budget.models import Budget, BudgetEstimate class BudgetForm(forms.ModelForm): class Meta: model = Budget fields = ('name', 'start_date') def save(self): if not self.instance.slug: ...
db6b9761d51d45b2708ba6bca997196fc73fbe94
sheldon/__init__.py
sheldon/__init__.py
# Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * # Utils folder contains scripts for more # comfortable work with sending and parsing # messages. For example, script for downloading # files by url. from sheldon.utils impo...
# Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * # Adapter module contains classes and tools # for plugins sending messages from sheldon.adapter import * # Utils folder contains scripts for more # comfortable work with s...
Add adapter module to init file
Add adapter module to init file
Python
mit
lises/sheldon
# Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * + + # Adapter module contains classes and tools + # for plugins sending messages + from sheldon.adapter import * # Utils folder contains scripts for more ...
Add adapter module to init file
## Code Before: # Bot module contains bot's main class - Sheldon from sheldon.bot import * # Hooks module contains hooks for plugins from sheldon.hooks import * # Utils folder contains scripts for more # comfortable work with sending and parsing # messages. For example, script for downloading # files by url. from sh...
987fd7555eadfa15d10db7991f4a7e8a4a7dbbbf
custom/topo-2sw-2host.py
custom/topo-2sw-2host.py
from mininet.topo import Topo, Node class MyTopo( Topo ): "Simple topology example." def __init__( self, enable_all = True ): "Create custom topo." # Add default members to class. super( MyTopo, self ).__init__() # Set Node IDs for hosts and switches leftHost = 1 ...
from mininet.topo import Topo from mininet.node import Node class MyTopo( Topo ): "Simple topology example." def __init__( self, enable_all = True ): "Create custom topo." # Add default members to class. super( MyTopo, self ).__init__() # Set Node IDs for hosts and switches ...
Fix custom topology example; outdated import
Fix custom topology example; outdated import Reported-by: Julius Bachnick
Python
bsd-3-clause
mininet/mininet,mininet/mininet,mininet/mininet
- from mininet.topo import Topo, Node + from mininet.topo import Topo + from mininet.node import Node class MyTopo( Topo ): "Simple topology example." def __init__( self, enable_all = True ): "Create custom topo." # Add default members to class. super( MyTopo, sel...
Fix custom topology example; outdated import
## Code Before: from mininet.topo import Topo, Node class MyTopo( Topo ): "Simple topology example." def __init__( self, enable_all = True ): "Create custom topo." # Add default members to class. super( MyTopo, self ).__init__() # Set Node IDs for hosts and switches ...
4b819129557d5f0546d9edf206710fd2ec962881
utsokt/restapi/models.py
utsokt/restapi/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_at = models.TimeFie...
from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_at = models.TimeFie...
Order stories by descending creation time
Order stories by descending creation time
Python
bsd-3-clause
madr/utsokt,madr/utsokt
from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_a...
Order stories by descending creation time
## Code Before: from django.db import models from django.utils.translation import ugettext_lazy as _ class Story(models.Model): url = models.URLField(_('URL')) title = models.CharField(_('Title'), max_length=64) excerpt = models.CharField(_('Excerpt'), max_length=64, null=True, blank=True) created_at ...
dd50858ee22c27076919614d1994e3ce9c8e2399
soundem/handlers.py
soundem/handlers.py
from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, 'error': 'Bad Request', 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e): return json_error_handler(e) @app.errorhandler(401...
from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, 'error': e.name, 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e): return json_error_handler(e) @app.errorhandler(401) def u...
Fix json error handler name
Fix json error handler name
Python
mit
building4theweb/soundem-api
from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, - 'error': 'Bad Request', + 'error': e.name, 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e):...
Fix json error handler name
## Code Before: from flask import jsonify from soundem import app def json_error_handler(e): return jsonify({ 'status_code': e.code, 'error': 'Bad Request', 'detail': e.description }), e.code @app.errorhandler(400) def bad_request_handler(e): return json_error_handler(e) @app....
dfc7e8a46558d3cf0e7f63da347e2b34253e302c
soundmeter/utils.py
soundmeter/utils.py
from ctypes import * from contextlib import contextmanager import os import stat def get_file_path(f): if f: name = getattr(f, 'name') if name: path = os.path.abspath(name) return path def create_executable(path, content): with open(path, 'w') as f: f.write(co...
from ctypes import * # NOQA from contextlib import contextmanager import os import stat def get_file_path(f): if f: name = getattr(f, 'name') if name: path = os.path.abspath(name) return path def create_executable(path, content): with open(path, 'w') as f: f.w...
Enforce flake8 and NOQA cases
Enforce flake8 and NOQA cases
Python
bsd-2-clause
shichao-an/soundmeter
- from ctypes import * + from ctypes import * # NOQA from contextlib import contextmanager import os import stat def get_file_path(f): if f: name = getattr(f, 'name') if name: path = os.path.abspath(name) return path def create_executable(path,...
Enforce flake8 and NOQA cases
## Code Before: from ctypes import * from contextlib import contextmanager import os import stat def get_file_path(f): if f: name = getattr(f, 'name') if name: path = os.path.abspath(name) return path def create_executable(path, content): with open(path, 'w') as f: ...
569dbdc820d9ead02a8941d69b1c8143fe4d4cfa
pytest_pipeline/plugin.py
pytest_pipeline/plugin.py
## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfailed = item def ...
## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfailed = item def ...
Remove unused 'skip_run' option flag
Remove unused 'skip_run' option flag
Python
bsd-3-clause
bow/pytest-pipeline
## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfail...
Remove unused 'skip_run' option flag
## Code Before: ## credits to Holger Krekel himself for these xfail marking functions ## http://stackoverflow.com/a/12579625/243058 def pytest_runtest_makereport(item, call): if "xfail_pipeline" in item.keywords: if call.excinfo is not None: parent = item.parent parent._previousfail...
4f2a3f26b8b0ec1f62e036f0bd9d15d71a628e0c
mamba/formatters.py
mamba/formatters.py
from clint.textui import indent, puts, colored from mamba import spec class DocumentationFormatter(object): def __init__(self): self.has_failed_tests = False self.total_specs = 0 self.total_seconds = .0 def format(self, item): puts(colored.white(item.name)) self._for...
from clint.textui import indent, puts, colored from mamba import spec class DocumentationFormatter(object): def __init__(self): self.has_failed_tests = False self.total_specs = 0 self.total_seconds = .0 def format(self, item): puts() puts(colored.white(item.name)) ...
Put a blank line among main suites
Put a blank line among main suites
Python
mit
alejandrodob/mamba,eferro/mamba,jaimegildesagredo/mamba,dex4er/mamba,angelsanz/mamba,nestorsalceda/mamba,markng/mamba
from clint.textui import indent, puts, colored from mamba import spec class DocumentationFormatter(object): def __init__(self): self.has_failed_tests = False self.total_specs = 0 self.total_seconds = .0 def format(self, item): + puts() put...
Put a blank line among main suites
## Code Before: from clint.textui import indent, puts, colored from mamba import spec class DocumentationFormatter(object): def __init__(self): self.has_failed_tests = False self.total_specs = 0 self.total_seconds = .0 def format(self, item): puts(colored.white(item.name)) ...
f9f9111ddafb7dfd0554d541befd3cc660169689
apps/redirects/urls.py
apps/redirects/urls.py
from django.conf.urls.defaults import * from util import redirect urlpatterns = patterns('', redirect(r'^b2g', 'firefoxos'), redirect(r'^b2g/faq', 'firefoxos'), redirect(r'^b2g/about', 'firefoxos'), )
from django.conf.urls.defaults import * from util import redirect urlpatterns = patterns('', redirect(r'^b2g', 'firefoxos.firefoxos'), redirect(r'^b2g/faq', 'firefoxos.firefoxos'), redirect(r'^b2g/about', 'firefoxos.firefoxos'), )
Fix view name for b2g redirects
Fix view name for b2g redirects bug 792482
Python
mpl-2.0
dudepare/bedrock,rishiloyola/bedrock,mahinthjoe/bedrock,ckprice/bedrock,davehunt/bedrock,davidwboswell/documentation_autoresponse,jpetto/bedrock,dudepare/bedrock,glogiotatidis/bedrock,kyoshino/bedrock,mahinthjoe/bedrock,MichaelKohler/bedrock,ckprice/bedrock,analytics-pros/mozilla-bedrock,analytics-pros/mozilla-bedrock,...
from django.conf.urls.defaults import * from util import redirect urlpatterns = patterns('', - redirect(r'^b2g', 'firefoxos'), + redirect(r'^b2g', 'firefoxos.firefoxos'), - redirect(r'^b2g/faq', 'firefoxos'), + redirect(r'^b2g/faq', 'firefoxos.firefoxos'), - redirect(r'^b2g/about', 'fire...
Fix view name for b2g redirects
## Code Before: from django.conf.urls.defaults import * from util import redirect urlpatterns = patterns('', redirect(r'^b2g', 'firefoxos'), redirect(r'^b2g/faq', 'firefoxos'), redirect(r'^b2g/about', 'firefoxos'), ) ## Instruction: Fix view name for b2g redirects ## Code After: from django.conf...
960eb0ce813988d8f90e76fbfd0485656cef541f
mff_rams_plugin/__init__.py
mff_rams_plugin/__init__.py
from uber.common import * from ._version import __version__ from .config import * from .models import * from .model_checks import * from .automated_emails import * static_overrides(join(config['module_root'], 'static')) template_overrides(join(config['module_root'], 'templates')) mount_site_sections(config['module_roo...
from uber.common import * from ._version import __version__ from .config import * from .models import * from .model_checks import * from .automated_emails import * static_overrides(join(config['module_root'], 'static')) template_overrides(join(config['module_root'], 'templates')) mount_site_sections(config['module_roo...
Rename new admin dropdown menu
Rename new admin dropdown menu
Python
agpl-3.0
MidwestFurryFandom/mff-rams-plugin,MidwestFurryFandom/mff-rams-plugin
from uber.common import * from ._version import __version__ from .config import * from .models import * from .model_checks import * from .automated_emails import * static_overrides(join(config['module_root'], 'static')) template_overrides(join(config['module_root'], 'templates')) mount_site_section...
Rename new admin dropdown menu
## Code Before: from uber.common import * from ._version import __version__ from .config import * from .models import * from .model_checks import * from .automated_emails import * static_overrides(join(config['module_root'], 'static')) template_overrides(join(config['module_root'], 'templates')) mount_site_sections(co...
6196c1fe13df88c1d9f1fe706120c175ab890a1d
gen_tone.py
gen_tone.py
import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samples_per_element * len(...
import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samples_per_element * len(...
Use 16 bit samples instead of float
Use 16 bit samples instead of float
Python
mit
nickodell/morse-code
import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samp...
Use 16 bit samples instead of float
## Code Before: import math import numpy from demodulate.cfg import * def gen_tone(pattern, WPM): cycles_per_sample = MORSE_FREQ/SAMPLE_FREQ radians_per_sample = cycles_per_sample * 2 * math.pi elements_per_second = WPM * 50.0 / 60.0 samples_per_element = int(SAMPLE_FREQ/elements_per_second) length = samples_pe...
da28458dffc3529f16cb222fce1676ddb0d87e05
oembed/resources.py
oembed/resources.py
from django.utils.simplejson import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} content_object = None def __getattr__(self, name): ...
from django.utils import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} content_object = None def __getattr__(self, name): return...
Use the simplejson bundled with django
Use the simplejson bundled with django
Python
mit
0101/djangoembed,worldcompany/djangoembed,akvo/djangoembed,akvo/djangoembed,worldcompany/djangoembed,d4nielcosta/djangoembed,0101/djangoembed,d4nielcosta/djangoembed
- from django.utils.simplejson import simplejson + from django.utils import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} con...
Use the simplejson bundled with django
## Code Before: from django.utils.simplejson import simplejson from oembed.exceptions import OEmbedException class OEmbedResource(object): """ OEmbed resource, as well as a factory for creating resource instances from response json """ _data = {} content_object = None def __getattr__(...
1cb201c57c592ebd014910fe225fa594cd87c745
opendebates/middleware.py
opendebates/middleware.py
from opendebates.utils import get_site_mode class SiteModeMiddleware(object): """ Gets or creates a SiteMode for the request, based on the hostname. """ def process_view(self, request, view_func, view_args, view_kwargs): request.site_mode = get_site_mode(request)
from opendebates.utils import get_site_mode class SiteModeMiddleware(object): """ Gets or creates a SiteMode for the request, based on the hostname. """ def process_request(self, request): request.site_mode = get_site_mode(request)
Make sure that the site mode is populated on the request
Make sure that the site mode is populated on the request even if the request winds up getting dispatched to a flatpage.
Python
apache-2.0
caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates
from opendebates.utils import get_site_mode class SiteModeMiddleware(object): """ Gets or creates a SiteMode for the request, based on the hostname. """ - def process_view(self, request, view_func, view_args, view_kwargs): + def process_request(self, request): request.si...
Make sure that the site mode is populated on the request
## Code Before: from opendebates.utils import get_site_mode class SiteModeMiddleware(object): """ Gets or creates a SiteMode for the request, based on the hostname. """ def process_view(self, request, view_func, view_args, view_kwargs): request.site_mode = get_site_mode(request) ## Instructi...
9651c0278d93bf5c4620e198baac975f0c84e9a0
src/unittest/stattestmain.py
src/unittest/stattestmain.py
def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.initText("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Reset to p...
def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.addStatVisitor("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() # Rese...
Fix the stats unit test.
tests: Fix the stats unit test. This has been broken since February. The interface for opening initializing where the stats output should go was changed, but the test wasn't updated. Change-Id: I54bd8be15bf870352d5fcfad95ded28d87c7cc5a Reviewed-on: https://gem5-review.googlesource.com/6001 Reviewed-by: Andreas Sandbe...
Python
bsd-3-clause
TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,TUD-OS/gem5-dtu,gem5/gem5,gem5/gem5,TUD-OS/gem5-dtu
def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() - m5.stats.initText("cout") + m5.stats.addStatVisitor("cout") # We're done registering statistics. Enable th...
Fix the stats unit test.
## Code Before: def main(): from _m5.stattest import stattest_init, stattest_run import m5.stats stattest_init() # Initialize the global statistics m5.stats.initSimStats() m5.stats.initText("cout") # We're done registering statistics. Enable the stats package now. m5.stats.enable() ...
61accbe3fa6ebdeed3bbf48573d5ac5412d0f1db
app/status/views.py
app/status/views.py
import os from flask import jsonify, current_app, request from sqlalchemy.exc import SQLAlchemyError from . import status from . import utils from dmutils.status import get_flags @status.route('/_status') def status_no_db(): if 'ignore-dependencies' in request.args: return jsonify( status="o...
from flask import jsonify, current_app, request from sqlalchemy.exc import SQLAlchemyError from . import status from . import utils from ..models import Framework from dmutils.status import get_flags @status.route('/_status') def status_no_db(): if 'ignore-dependencies' in request.args: return jsonify( ...
Add framework status to API /_status
Add framework status to API /_status To figure out current framework statuses for the given environment you either need access to the API token or you'd have to look through a number of frontend pages to infer the status from. Framework status is a part of almost every request to the API, so it should always be avail...
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
- import os from flask import jsonify, current_app, request from sqlalchemy.exc import SQLAlchemyError from . import status from . import utils + from ..models import Framework from dmutils.status import get_flags @status.route('/_status') def status_no_db(): if 'ignore-dependencies' in ...
Add framework status to API /_status
## Code Before: import os from flask import jsonify, current_app, request from sqlalchemy.exc import SQLAlchemyError from . import status from . import utils from dmutils.status import get_flags @status.route('/_status') def status_no_db(): if 'ignore-dependencies' in request.args: return jsonify( ...
8d1a4869286735a55773ce0c074349bb0cafd3aa
ca_on_ottawa/people.py
ca_on_ottawa/people.py
from utils import CSVScraper class OttawaPersonScraper(CSVScraper): csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv'
from utils import CSVScraper class OttawaPersonScraper(CSVScraper): csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv' corrections = { 'district name': { "Orl\u0082...
Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work
ca_on_ottawa: Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
from utils import CSVScraper class OttawaPersonScraper(CSVScraper): csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv' - + corrections = { + 'district name': { + ...
Use corrections, as none of utf-8, iso-8859-1 or windows-1252 work
## Code Before: from utils import CSVScraper class OttawaPersonScraper(CSVScraper): csv_url = 'http://data.ottawa.ca/en/dataset/fd26ae83-fe1a-40d8-8951-72df40021c82/resource/33a437d3-a06d-4c56-a7fe-4fd622364ce6/download/elected-officials-282014-201829-v.2.csv' ## Instruction: Use corrections, as none of utf-8, i...
e326cef4ae66d4d2dd500e933ff4f7c6fc619b28
fix-perm.py
fix-perm.py
from __future__ import print_function import os import stat import sys if __name__ == '__main__': for line in sys.stdin: path = line.rstrip('\n') if path == '': continue if not os.path.isfile(path): continue st = os.stat(path) mode = st.st_mode ...
from __future__ import print_function import os import stat import sys if __name__ == '__main__': for line in sys.stdin: path = line.rstrip('\n') if path == '': continue if not os.path.isfile(path): continue st = os.stat(path) mode = int('644', 8...
Change permissions to either 644 or 755.
Change permissions to either 644 or 755.
Python
isc
eliteraspberries/minipkg,eliteraspberries/minipkg
from __future__ import print_function import os import stat import sys if __name__ == '__main__': for line in sys.stdin: path = line.rstrip('\n') if path == '': continue if not os.path.isfile(path): continue st = os.st...
Change permissions to either 644 or 755.
## Code Before: from __future__ import print_function import os import stat import sys if __name__ == '__main__': for line in sys.stdin: path = line.rstrip('\n') if path == '': continue if not os.path.isfile(path): continue st = os.stat(path) mod...
0078bb14b85df519744371df89e243822a86ed4c
generate.py
generate.py
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] = y buff...
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer...
Add a little more detail to the generator
Add a little more detail to the generator
Python
mit
spgill/bitnigma
import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': + print('WIRING') popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popse...
Add a little more detail to the generator
## Code Before: import random import sys population = bytes([i for i in range(256)]) if sys.argv[1] == 'reflector': popset = set(population) buffer = [None for i in range(256)] for i in range(128): x, y = random.sample(popset, 2) popset.remove(x) popset.remove(y) buffer[x] ...
211f1fdfe1d969df7c9762ba8e914d3ea829e9b4
manual/conf.py
manual/conf.py
import sphinx_rtd_theme # noQA F401 import os import sys sys.path.append(os.path.abspath("./_ext")) project = 'QPDF' copyright = '2005-2021, Jay Berkenbilt' author = 'Jay Berkenbilt' # make_dist and the CI build lexically find the release version from this file. release = '10.5.0' version = release extensions = [ ...
import sphinx_rtd_theme # noQA F401 import os import sys sys.path.append(os.path.abspath("./_ext")) project = 'QPDF' copyright = '2005-2021, Jay Berkenbilt' author = 'Jay Berkenbilt' # make_dist and the CI build lexically find the release version from this file. release = '10.5.0' version = release extensions = [ ...
Allow real <= and >= in LateX
Allow real <= and >= in LateX
Python
apache-2.0
jberkenbilt/qpdf,jberkenbilt/qpdf,jberkenbilt/qpdf,qpdf/qpdf,jberkenbilt/qpdf,qpdf/qpdf,jberkenbilt/qpdf,qpdf/qpdf,qpdf/qpdf,qpdf/qpdf
import sphinx_rtd_theme # noQA F401 import os import sys sys.path.append(os.path.abspath("./_ext")) project = 'QPDF' copyright = '2005-2021, Jay Berkenbilt' author = 'Jay Berkenbilt' # make_dist and the CI build lexically find the release version from this file. release = '10.5.0' version = r...
Allow real <= and >= in LateX
## Code Before: import sphinx_rtd_theme # noQA F401 import os import sys sys.path.append(os.path.abspath("./_ext")) project = 'QPDF' copyright = '2005-2021, Jay Berkenbilt' author = 'Jay Berkenbilt' # make_dist and the CI build lexically find the release version from this file. release = '10.5.0' version = release e...
ad55d04d6688f75f0e441603668e0337a0333d76
tests/test_validate.py
tests/test_validate.py
import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid2) invalid3 = "user"...
import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid2) invalid3 = "user"...
Add length validator unit tests
Add length validator unit tests
Python
mit
maximkulkin/marshmallow,0xDCA/marshmallow,Tim-Erwin/marshmallow,xLegoz/marshmallow,marshmallow-code/marshmallow,VladimirPal/marshmallow,0xDCA/marshmallow,daniloakamine/marshmallow,dwieeb/marshmallow,mwstobo/marshmallow,quxiaolong1504/marshmallow,etataurov/marshmallow,Bachmann1234/marshmallow,bartaelterman/marshmallow
import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid2)...
Add length validator unit tests
## Code Before: import pytest from marshmallow import validate, ValidationError def test_invalid_email(): invalid1 = "user@example" with pytest.raises(ValidationError): validate.email(invalid1) invalid2 = "example.com" with pytest.raises(ValidationError): validate.email(invalid2) i...
98eaf33328814342cdf6a2e8379c87cd00c911ce
campaign/views.py
campaign/views.py
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm from campaign.models import PROSPECTUS_FIELD_HELP def create_edit_prospectus(request): if request.method == ...
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm from campaign.models import PROSPECTUS_FIELD_HELP, Campaign def create_edit_prospectus(request): if request....
Update default queryset for formsets
Update default queryset for formsets
Python
mit
tdphillips/campaigns,tdphillips/campaigns
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm - from campaign.models import PROSPECTUS_FIELD_HELP + from campaign.models import PROSPECTUS_FIELD_HELP,...
Update default queryset for formsets
## Code Before: from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm from campaign.models import PROSPECTUS_FIELD_HELP def create_edit_prospectus(request): if re...
547130e5f3717fd5bfd083be89afd361fdcdefc1
van/contactology/tests/test_contactology.py
van/contactology/tests/test_contactology.py
import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock from van.contactology import Contactology class TestProxy(TestCase): @defer.inlineCallbacks def test_list_return(self): patcher = patch('van.contact...
import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock from van.contactology import Contactology, APIError class TestProxy(TestCase): @defer.inlineCallbacks def test_list_return(self): patcher = patch('v...
Test for exception raising on API error.
Test for exception raising on API error.
Python
bsd-3-clause
jinty/van.contactology
import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock - from van.contactology import Contactology + from van.contactology import Contactology, APIError class TestProxy(TestCase): @defer.inlineCa...
Test for exception raising on API error.
## Code Before: import unittest from simplejson import dumps from twisted.trial.unittest import TestCase from twisted.internet import defer from mock import patch, Mock from van.contactology import Contactology class TestProxy(TestCase): @defer.inlineCallbacks def test_list_return(self): patcher = pa...
87de1fce846d7f50017fba885725a0907d43275e
swf/querysets/__init__.py
swf/querysets/__init__.py
from swf.querysets.activity import ActivityTypeQuerySet from swf.querysets.domain import DomainQuerySet from swf.querysets.workflow import (WorkflowTypeQuerySet, WorkflowExecutionQuerySet)
from swf.querysets.activity import ActivityTypeQuerySet from swf.querysets.domain import DomainQuerySet from swf.querysets.history import HistoryQuerySet from swf.querysets.workflow import (WorkflowTypeQuerySet, WorkflowExecutionQuerySet)
Add history qs to swf querysets modules
Add history qs to swf querysets modules
Python
mit
botify-labs/python-simple-workflow,botify-labs/python-simple-workflow
from swf.querysets.activity import ActivityTypeQuerySet from swf.querysets.domain import DomainQuerySet + from swf.querysets.history import HistoryQuerySet from swf.querysets.workflow import (WorkflowTypeQuerySet, WorkflowExecutionQuerySet)
Add history qs to swf querysets modules
## Code Before: from swf.querysets.activity import ActivityTypeQuerySet from swf.querysets.domain import DomainQuerySet from swf.querysets.workflow import (WorkflowTypeQuerySet, WorkflowExecutionQuerySet) ## Instruction: Add history qs to swf querysets modules ## Code After: from ...
3a0b844f33274f7d9c389dd89b21a953cb9c1510
promgen/sender/webhook.py
promgen/sender/webhook.py
''' Simple webhook bridge Accepts alert json from Alert Manager and then POSTs individual alerts to configured webhook destinations ''' import logging import requests from promgen.sender import SenderBase logger = logging.getLogger(__name__) class SenderWebhook(SenderBase): def _send(self, url, alert, data): ...
''' Simple webhook bridge Accepts alert json from Alert Manager and then POSTs individual alerts to configured webhook destinations ''' import logging import requests from promgen.sender import SenderBase logger = logging.getLogger(__name__) class SenderWebhook(SenderBase): def _send(self, url, alert, data): ...
Fix case where annotations may not exist
Fix case where annotations may not exist
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
''' Simple webhook bridge Accepts alert json from Alert Manager and then POSTs individual alerts to configured webhook destinations ''' import logging + import requests + from promgen.sender import SenderBase logger = logging.getLogger(__name__) class SenderWebhook(SenderBase): d...
Fix case where annotations may not exist
## Code Before: ''' Simple webhook bridge Accepts alert json from Alert Manager and then POSTs individual alerts to configured webhook destinations ''' import logging import requests from promgen.sender import SenderBase logger = logging.getLogger(__name__) class SenderWebhook(SenderBase): def _send(self, url, ...
e9e632008db1eb2bbdbd989584b82255a10f8944
CodeFights/arrayReplace.py
CodeFights/arrayReplace.py
def arrayReplace(inputArray, elemToReplace, substitutionElem): pass def main(): pass if __name__ == '__main__': main()
def arrayReplace(inputArray, elemToReplace, substitutionElem): return [x if x != elemToReplace else substitutionElem for x in inputArray] def main(): tests = [ [[1, 2, 1], 1, 3, [3, 2, 3]], [[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]], [[1, 1, 1], 1, 10, [10, 10, 10]] ] for t in...
Solve Code Fights array replace problem
Solve Code Fights array replace problem
Python
mit
HKuz/Test_Code
def arrayReplace(inputArray, elemToReplace, substitutionElem): - pass + return [x if x != elemToReplace else substitutionElem for x in inputArray] def main(): - pass + tests = [ + [[1, 2, 1], 1, 3, [3, 2, 3]], + [[1, 2, 3, 4, 5], 3, 0, [1, 2, 0, 4, 5]], + [[1, 1, ...
Solve Code Fights array replace problem
## Code Before: def arrayReplace(inputArray, elemToReplace, substitutionElem): pass def main(): pass if __name__ == '__main__': main() ## Instruction: Solve Code Fights array replace problem ## Code After: def arrayReplace(inputArray, elemToReplace, substitutionElem): return [x if x != elemToRe...
016d955319b6971fec42ac6ada1052f88d867cee
freepacktbook/__init__.py
freepacktbook/__init__.py
import os from bs4 import BeautifulSoup import requests class FreePacktBook(object): base_url = 'https://www.packtpub.com' url = base_url + '/packt/offers/free-learning/' def __init__(self, email=None, password=None): self.session = requests.Session() self.email = email self.pas...
import os from bs4 import BeautifulSoup import requests class FreePacktBook(object): base_url = 'https://www.packtpub.com' url = base_url + '/packt/offers/free-learning/' def __init__(self, email=None, password=None): self.session = requests.Session() self.email = email self.pas...
Add ability to get book details
Add ability to get book details
Python
mit
bogdal/freepacktbook
import os from bs4 import BeautifulSoup import requests class FreePacktBook(object): base_url = 'https://www.packtpub.com' url = base_url + '/packt/offers/free-learning/' def __init__(self, email=None, password=None): self.session = requests.Session() self.em...
Add ability to get book details
## Code Before: import os from bs4 import BeautifulSoup import requests class FreePacktBook(object): base_url = 'https://www.packtpub.com' url = base_url + '/packt/offers/free-learning/' def __init__(self, email=None, password=None): self.session = requests.Session() self.email = email ...
76b39021fb0171da6036ceaf7894e3ff18d259ae
src/syft/grid/client/request_api/worker_api.py
src/syft/grid/client/request_api/worker_api.py
from typing import Any from typing import Dict # third party from pandas import DataFrame # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messages import...
from typing import Callable # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra_messages import GetWorkersMessage from ...messages.infra_messages import Updat...
Update Worker API - ADD type hints - Remove unused imports
Update Worker API - ADD type hints - Remove unused imports
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
- from typing import Any + from typing import Callable - from typing import Dict - - # third party - from pandas import DataFrame # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWo...
Update Worker API - ADD type hints - Remove unused imports
## Code Before: from typing import Any from typing import Dict # third party from pandas import DataFrame # syft relative from ...messages.infra_messages import CreateWorkerMessage from ...messages.infra_messages import DeleteWorkerMessage from ...messages.infra_messages import GetWorkerMessage from ...messages.infra...
6153952ca9794ccb1dd5d76696aa2d4881a665c1
tests/core/migrations/0004_bookwithchapters.py
tests/core/migrations/0004_bookwithchapters.py
from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class PostgresOnlyCreateModel(migrations.CreateModel): def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor.startswith("postgre...
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models if VERSION >= (1, 8): from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None) else: chapters_field = mo...
Add version check for importing django.contrib.postgres.fields.ArrayField
Add version check for importing django.contrib.postgres.fields.ArrayField
Python
bsd-2-clause
daniell/django-import-export,jnns/django-import-export,django-import-export/django-import-export,bmihelac/django-import-export,copperleaftech/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,daniell/django-import-export,daniell/django-import-export,PetrDlouhy/django-import-export,PetrD...
from __future__ import unicode_literals - import django.contrib.postgres.fields + from django import VERSION from django.db import migrations, models + if VERSION >= (1, 8): + from django.contrib.postgres.fields import ArrayField + chapters_field = ArrayField(base_field=models.CharField(max_length=100), ...
Add version check for importing django.contrib.postgres.fields.ArrayField
## Code Before: from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class PostgresOnlyCreateModel(migrations.CreateModel): def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor.sta...
d317b27a5dac13900beb8f2674b0725313970a80
nodeconductor/core/handlers.py
nodeconductor/core/handlers.py
from __future__ import unicode_literals import logging from nodeconductor.core.log import EventLoggerAdapter logger = logging.getLogger(__name__) event_logger = EventLoggerAdapter(logger) def log_ssh_key_save(sender, instance, created=False, **kwargs): if created: event_logger.info( 'SSH k...
from __future__ import unicode_literals import logging from nodeconductor.core.log import EventLoggerAdapter logger = logging.getLogger(__name__) event_logger = EventLoggerAdapter(logger) def log_ssh_key_save(sender, instance, created=False, **kwargs): if created: event_logger.info( 'SSH k...
Rename event types for consistency
Rename event types for consistency - NC-332
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
from __future__ import unicode_literals import logging from nodeconductor.core.log import EventLoggerAdapter logger = logging.getLogger(__name__) event_logger = EventLoggerAdapter(logger) def log_ssh_key_save(sender, instance, created=False, **kwargs): if created: event_log...
Rename event types for consistency
## Code Before: from __future__ import unicode_literals import logging from nodeconductor.core.log import EventLoggerAdapter logger = logging.getLogger(__name__) event_logger = EventLoggerAdapter(logger) def log_ssh_key_save(sender, instance, created=False, **kwargs): if created: event_logger.info( ...
fba983fa54691fcde0de93d6519b3906dff3cb32
sara_flexbe_states/src/sara_flexbe_states/get_distance2D.py
sara_flexbe_states/src/sara_flexbe_states/get_distance2D.py
from flexbe_core import EventState, Logger import rospy import re import ros import math class getDistance(EventState): """ Calcule la distance entre deux points donnes. ### InputKey ># point1 ># point2 ### OutputKey #> distance <= done """ def __init__(self): """Con...
from flexbe_core import EventState, Logger import rospy import re import ros import math class getDistance(EventState): """ Calcule la distance entre deux points donnes. ### InputKey ># point1 ># point2 ### OutputKey #> distance <= done """ def __init__(self): """Con...
Correct call to super constructor
Correct call to super constructor
Python
bsd-3-clause
WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors
from flexbe_core import EventState, Logger import rospy import re import ros import math class getDistance(EventState): """ Calcule la distance entre deux points donnes. ### InputKey ># point1 ># point2 ### OutputKey #> distance <= done ""...
Correct call to super constructor
## Code Before: from flexbe_core import EventState, Logger import rospy import re import ros import math class getDistance(EventState): """ Calcule la distance entre deux points donnes. ### InputKey ># point1 ># point2 ### OutputKey #> distance <= done """ def __init__(self)...
06914af3d8df899947a53c2fe3b3ce1de208d04d
robot-framework-needle.py
robot-framework-needle.py
from needle.cases import NeedleTestCase from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec class TestLogo(NeedleTestCase): def test_logo(self): self.driver.get('http://www.bbc.co.uk/news/') ...
from needle.cases import NeedleTestCase from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec class TestLogo(NeedleTestCase): def test_logo(self): self.driver.get('http://www.bbc.co.uk/news/') ...
Fix locators used in needle example on BBC site
Fix locators used in needle example on BBC site
Python
apache-2.0
laurentbristiel/robotframework-needle
from needle.cases import NeedleTestCase from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec class TestLogo(NeedleTestCase): def test_logo(self): self.driver.get('http://www...
Fix locators used in needle example on BBC site
## Code Before: from needle.cases import NeedleTestCase from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec class TestLogo(NeedleTestCase): def test_logo(self): self.driver.get('http://www.bbc...
ede4689ce3f9e03db5f250617e793083333af3a5
notification/backends/email.py
notification/backends/email.py
from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from notification import backends from notification.message import message_to_text # favour djan...
from django.conf import settings from django.db.models.loading import get_app from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigur...
Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
pluggable-backends: Use get_app over to include django-mailer support over a standard import and ImportError exception handling. git-svn-id: 12265af7f62f437cb19748843ef653b20b846039@130 590c3fc9-4838-0410-bb95-17a0c9b37ca9
Python
mit
brosner/django-notification,arctelix/django-notification-automated
from django.conf import settings + from django.db.models.loading import get_app from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site + from django.core.exceptions import Im...
Use get_app over to include django-mailer support over a standard import and ImportError exception handling.
## Code Before: from django.conf import settings from django.core.urlresolvers import reverse from django.template.loader import render_to_string from django.utils.translation import ugettext from django.contrib.sites.models import Site from notification import backends from notification.message import message_to_tex...
24c1309a9f221ec8be6a3b15dc843769f4157cf1
allauth/socialaccount/providers/twitch/views.py
allauth/socialaccount/providers/twitch/views.py
import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchProvider.id access_token_url = 'https://api.twitch.tv/kraken/oauth2/...
import requests from allauth.socialaccount.providers.oauth2.client import OAuth2Error from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchPr...
Add error checking in API response
twitch: Add error checking in API response
Python
mit
rsalmaso/django-allauth,lukeburden/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pztrick/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pztrick/django-allauth,pennersr/django-allauth,lukeburden/django-allauth,lukeburden/django-allauth,pztrick/django-allauth,bitt...
import requests + from allauth.socialaccount.providers.oauth2.client import OAuth2Error from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): ...
Add error checking in API response
## Code Before: import requests from allauth.socialaccount.providers.oauth2.views import ( OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView, ) from .provider import TwitchProvider class TwitchOAuth2Adapter(OAuth2Adapter): provider_id = TwitchProvider.id access_token_url = 'https://api.twitch.t...
8386d7372f9ff8bfad651efe43504746aff19b73
app/models/rooms/rooms.py
app/models/rooms/rooms.py
from models.people.people import Staff, Fellow from models.rooms.rooms import Office, LivingSpace import random class Dojo(object): def __init__(self): self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self.all_people = []...
import os import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class Room(object): """Models the kind of rooms available at Andela, It forms the base class Room from which OfficeSpace and LivingRoom inherit""" def __init__(self, room_name, room_type, room_...
Implement the Room base class
Implement the Room base class
Python
mit
Alweezy/alvin-mutisya-dojo-project
- from models.people.people import Staff, Fellow - from models.rooms.rooms import Office, LivingSpace - import random + import os + import sys + from os import path + sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) - class Dojo(object): + class Room(object): + """Models the kind of rooms a...
Implement the Room base class
## Code Before: from models.people.people import Staff, Fellow from models.rooms.rooms import Office, LivingSpace import random class Dojo(object): def __init__(self): self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self...
df2d24757d8e12035437d152d17dc9016f1cd9df
app/__init__.py
app/__init__.py
from flask import Flask app = Flask(__name__) # pylint: disable=invalid-name app.config.from_object('config') # commented as for file structure, should recover later. # from app import models @app.route('/') @app.route('/hellworld') def helloworld(): """ Hello World for app. """ return 'Hello world from {...
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # pylint: disable=invalid-name app.config.from_object('config') # commented as for file structure, should recover later. # from app import models db = SQLAlchemy(app) @app.route('/') @app.route('/hellworld') def helloworld(...
Create model in config file.
Create model in config file.
Python
mit
CAPU-ENG/CAPUHome-API,huxuan/CAPUHome-API
from flask import Flask + from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) # pylint: disable=invalid-name app.config.from_object('config') # commented as for file structure, should recover later. # from app import models + + db = SQLAlchemy(app) @app.route('/') @app.route...
Create model in config file.
## Code Before: from flask import Flask app = Flask(__name__) # pylint: disable=invalid-name app.config.from_object('config') # commented as for file structure, should recover later. # from app import models @app.route('/') @app.route('/hellworld') def helloworld(): """ Hello World for app. """ return 'He...
8c2996b94cdc3210b24ebeaeb957c625629f68a5
hunting/level/encoder.py
hunting/level/encoder.py
import json import hunting.sim.entities as entities class GameObjectEncoder(json.JSONEncoder): def default(self, o): d = o.__dict__ d.pop('owner', None) if isinstance(o, entities.GameObject): d.pop('log', None) d.pop('ai', None) return d elif is...
import json import hunting.sim.entities as entities class GameObjectEncoder(json.JSONEncoder): def default(self, o): d = o.__dict__ d.pop('owner', None) if isinstance(o, entities.GameObject): d.pop('log', None) d.pop('ai', None) return d elif is...
Add log to encoding output (still fails due to objects)
Add log to encoding output (still fails due to objects)
Python
mit
MoyTW/RL_Arena_Experiment
import json import hunting.sim.entities as entities class GameObjectEncoder(json.JSONEncoder): def default(self, o): d = o.__dict__ d.pop('owner', None) if isinstance(o, entities.GameObject): d.pop('log', None) d.pop('ai', None) ...
Add log to encoding output (still fails due to objects)
## Code Before: import json import hunting.sim.entities as entities class GameObjectEncoder(json.JSONEncoder): def default(self, o): d = o.__dict__ d.pop('owner', None) if isinstance(o, entities.GameObject): d.pop('log', None) d.pop('ai', None) return d...
b723cbceb896f7ca8690eaa13c38ffb20fecd0be
avocado/search_indexes.py
avocado/search_indexes.py
import warnings from haystack import indexes from avocado.conf import settings from avocado.models import DataConcept, DataField # Warn if either of the settings are set to false if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \ not getattr(settings, 'FIELD_SEARCH_ENABLED', True): warnings.warn...
from haystack import indexes from avocado.models import DataConcept, DataField class DataIndex(indexes.SearchIndex): text = indexes.CharField(document=True, use_template=True) text_auto = indexes.EdgeNgramField(use_template=True) def index_queryset(self, using=None): return self.get_model().objec...
Change DataIndex to restrict on published and archived flags only
Change DataIndex to restrict on published and archived flags only In addition, the warnings of the deprecated settings have been removed. Fix #290 Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
- import warnings from haystack import indexes - from avocado.conf import settings from avocado.models import DataConcept, DataField - - # Warn if either of the settings are set to false - if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \ - not getattr(settings, 'FIELD_SEARCH_ENABLED', True): -...
Change DataIndex to restrict on published and archived flags only
## Code Before: import warnings from haystack import indexes from avocado.conf import settings from avocado.models import DataConcept, DataField # Warn if either of the settings are set to false if not getattr(settings, 'CONCEPT_SEARCH_ENABLED', True) or \ not getattr(settings, 'FIELD_SEARCH_ENABLED', True): ...
86a2e55954ff4b8f5e005296e2ae336b6be627a0
py/rackattack/clientfactory.py
py/rackattack/clientfactory.py
import os from rackattack.tcp import client _VAR_NAME = "RACKATTACK_PROVIDER" def factory(): if _VAR_NAME not in os.environ: raise Exception( "The environment variable '%s' must be defined properly" % _VAR_NAME) request, subscribe, http = os.environ[_VAR_NAME].split("@@") return clie...
import os from rackattack.tcp import client _VAR_NAME = "RACKATTACK_PROVIDER" def factory(connectionString=None): if connectionString is None: if _VAR_NAME not in os.environ: raise Exception( "The environment variable '%s' must be defined properly" % _VAR_NAME) connec...
Allow passing the rackattack connection string as an argument to the client factory
Allow passing the rackattack connection string as an argument to the client factory
Python
apache-2.0
eliran-stratoscale/rackattack-api,Stratoscale/rackattack-api
import os from rackattack.tcp import client _VAR_NAME = "RACKATTACK_PROVIDER" - def factory(): + def factory(connectionString=None): + if connectionString is None: - if _VAR_NAME not in os.environ: + if _VAR_NAME not in os.environ: - raise Exception( + raise Excepti...
Allow passing the rackattack connection string as an argument to the client factory
## Code Before: import os from rackattack.tcp import client _VAR_NAME = "RACKATTACK_PROVIDER" def factory(): if _VAR_NAME not in os.environ: raise Exception( "The environment variable '%s' must be defined properly" % _VAR_NAME) request, subscribe, http = os.environ[_VAR_NAME].split("@@")...
43f67067c470386b6b24080642cc845ec1655f58
utils/networking.py
utils/networking.py
import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ ip = _ip_address_for_interface(ifname.encode('ascii')) original_socket = socket.socket def rebound_socket(*args, **kwargs): sock = origi...
import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ ip = _ip_address_for_interface(ifname) original_socket = socket.socket def rebound_socket(*args, **kwargs): sock = original_socket(*args...
Make _ip_address_for_interface easier to use
Make _ip_address_for_interface easier to use
Python
apache-2.0
OPWEN/opwen-webapp,ascoderu/opwen-webapp,ascoderu/opwen-webapp,OPWEN/opwen-webapp,OPWEN/opwen-webapp,ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver,ascoderu/opwen-webapp
import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ - ip = _ip_address_for_interface(ifname.encode('ascii')) + ip = _ip_address_for_interface(ifname) original_socket = soc...
Make _ip_address_for_interface easier to use
## Code Before: import fcntl import socket import struct from contextlib import contextmanager @contextmanager def use_interface(ifname): """ :type ifname: str """ ip = _ip_address_for_interface(ifname.encode('ascii')) original_socket = socket.socket def rebound_socket(*args, **kwargs): ...
c80a68b81e936435434931f0b5bf748bcbea54dc
statistics/webui.py
statistics/webui.py
from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): sort_by = request.args....
from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): sort_by = request.args....
Add proto of average page. Without sorting.
Add proto of average page. Without sorting.
Python
mit
uvNikita/appstats,uvNikita/appstats,uvNikita/appstats
from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): ...
Add proto of average page. Without sorting.
## Code Before: from flask import render_template, g, redirect, request from db import connect_db, get_all_sum from statistics import app @app.before_request def before_request(): g.db = connect_db() g.fields = ["CPU", "TOTAL", "SQL", "SOLR", "REDIS", "MEMCACHED"] @app.route("/") def main_page(): sort_by...
236a3e81164e8f7c37c50eaf59bfadd32e76735a
defines.py
defines.py
INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK
INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK from pdb import set_trace as st
Make a shortcut for debugging with pdb
Make a shortcut for debugging with pdb
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK + from pdb impor...
Make a shortcut for debugging with pdb
## Code Before: INFINITY = 1e+31 DIRECTIONS = ((-1,-1),(-1,0),(-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)) EMPTY = 0 BLACK = 1 WHITE = 2 def opposite_colour(col): if col == BLACK: return WHITE if col == WHITE: return BLACK ## Instruction: Make a shortcut ...
67b243915ef95ff1b9337bc67053d18df372e79d
unitypack/enums.py
unitypack/enums.py
from enum import IntEnum class RuntimePlatform(IntEnum): OSXEditor = 0 OSXPlayer = 1 WindowsPlayer = 2 OSXWebPlayer = 3 OSXDashboardPlayer = 4 WindowsWebPlayer = 5 WindowsEditor = 7 IPhonePlayer = 8 PS3 = 9 XBOX360 = 10 Android = 11 NaCl = 12 LinuxPlayer = 13 FlashPlayer = 15 WebGLPlayer = 17 MetroPla...
from enum import IntEnum class RuntimePlatform(IntEnum): OSXEditor = 0 OSXPlayer = 1 WindowsPlayer = 2 OSXWebPlayer = 3 OSXDashboardPlayer = 4 WindowsWebPlayer = 5 WindowsEditor = 7 IPhonePlayer = 8 PS3 = 9 XBOX360 = 10 Android = 11 NaCl = 12 LinuxPlayer = 13 FlashPlayer = 15 WebGLPlayer = 17 MetroPla...
Add PSMPlayer and SamsungTVPlayer platforms
Add PSMPlayer and SamsungTVPlayer platforms
Python
mit
andburn/python-unitypack
from enum import IntEnum class RuntimePlatform(IntEnum): OSXEditor = 0 OSXPlayer = 1 WindowsPlayer = 2 OSXWebPlayer = 3 OSXDashboardPlayer = 4 WindowsWebPlayer = 5 WindowsEditor = 7 IPhonePlayer = 8 PS3 = 9 XBOX360 = 10 Android = 11 NaCl = 12 LinuxPlayer = 13 FlashPla...
Add PSMPlayer and SamsungTVPlayer platforms
## Code Before: from enum import IntEnum class RuntimePlatform(IntEnum): OSXEditor = 0 OSXPlayer = 1 WindowsPlayer = 2 OSXWebPlayer = 3 OSXDashboardPlayer = 4 WindowsWebPlayer = 5 WindowsEditor = 7 IPhonePlayer = 8 PS3 = 9 XBOX360 = 10 Android = 11 NaCl = 12 LinuxPlayer = 13 FlashPlayer = 15 WebGLPlaye...
c4de9152f34d2831d43dfa3769a7a6452bba5814
blockbuster/bb_security.py
blockbuster/bb_security.py
__author__ = 'matt' from blockbuster import bb_dbconnector_factory def credentials_are_valid(username, password): db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create() print(username) result = db.api_username_exists(username) print (result) return result
__author__ = 'matt' from blockbuster import bb_dbconnector_factory def credentials_are_valid(username, password): db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create() print(username) result = db.api_credentials_are_valid(username, password) print (result) return result
Update method to check both username and password
Update method to check both username and password
Python
mit
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
__author__ = 'matt' from blockbuster import bb_dbconnector_factory def credentials_are_valid(username, password): db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create() print(username) - result = db.api_username_exists(username) + result = db.api_credentials_are_valid(user...
Update method to check both username and password
## Code Before: __author__ = 'matt' from blockbuster import bb_dbconnector_factory def credentials_are_valid(username, password): db = bb_dbconnector_factory.DBConnectorInterfaceFactory().create() print(username) result = db.api_username_exists(username) print (result) return result ## Instructi...
753f5bdc3f023cf31c0f189dd835978aad2b5d49
djs_playground/urls.py
djs_playground/urls.py
from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/', include('djan...
from django.conf import settings from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ re_path(r'^$', index, name='index'), re_path(r'^admin/', admin.site.urls), re_path(r'^summernote/', in...
Change url in favor of the re_path
Change url in favor of the re_path
Python
mit
summernote/django-summernote,summernote/django-summernote,summernote/django-summernote
from django.conf import settings - from django.conf.urls import url, include + from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ - url(r'^$', index, name='index'), + re_path(r'^...
Change url in favor of the re_path
## Code Before: from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/...
5a641736faf6bb3ce335480848464a1f22fab040
fabfile.py
fabfile.py
from contextlib import nested from fabric.api import * def prepare_project(): u""" Enters the directory and sources environment configuration. I know ``nested`` is deprecated, but what a nice shortcut it is here ;) """ return nested( cd(PROJECT_PATH), prefix("source ../.virtuale...
from contextlib import nested from fabric.api import * def prepare_project(): u""" Enters the directory and sources environment configuration. I know ``nested`` is deprecated, but what a nice shortcut it is here ;) """ return nested( cd(PROJECT_PATH), prefix("source ../.virtuale...
Make Fabric honor .ssh/config settings
Make Fabric honor .ssh/config settings
Python
mit
zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net
from contextlib import nested from fabric.api import * def prepare_project(): u""" Enters the directory and sources environment configuration. I know ``nested`` is deprecated, but what a nice shortcut it is here ;) """ return nested( cd(PROJECT_PATH), ...
Make Fabric honor .ssh/config settings
## Code Before: from contextlib import nested from fabric.api import * def prepare_project(): u""" Enters the directory and sources environment configuration. I know ``nested`` is deprecated, but what a nice shortcut it is here ;) """ return nested( cd(PROJECT_PATH), prefix("sou...
dc1cf6fabcf871e3661125f7ac5d1cf9567798d6
cms/management/commands/load_dev_fixtures.py
cms/management/commands/load_dev_fixtures.py
import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ help = "Download and...
import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ help = "Download and...
Use self.stdout.write() instead of print().
Use self.stdout.write() instead of print(). This is the recommended way in the Django documentation: https://docs.djangoproject.com/en/1.7/howto/custom-management-commands/
Python
apache-2.0
manhhomienbienthuy/pythondotorg,python/pythondotorg,SujaySKumar/pythondotorg,lebronhkh/pythondotorg,SujaySKumar/pythondotorg,lepture/pythondotorg,python/pythondotorg,proevo/pythondotorg,Mariatta/pythondotorg,malemburg/pythondotorg,willingc/pythondotorg,fe11x/pythondotorg,berkerpeksag/pythondotorg,demvher/pythondotorg,p...
import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ ...
Use self.stdout.write() instead of print().
## Code Before: import requests from django.core.management import call_command from django.core.management.base import NoArgsCommand from django.conf import settings from django.utils.six.moves import input class Command(NoArgsCommand): """ Download and load dev fixtures from www.python.org """ help...
125dfa47e5656c3f9b1e8846be03010ed02c6f91
tests/rules_tests/isValid_tests/InvalidSyntaxTest.py
tests/rules_tests/isValid_tests/InvalidSyntaxTest.py
from unittest import main, TestCase from grammpy import Rule class InvalidSyntaxTest(TestCase): pass if __name__ == '__main__': main()
from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleSyntaxException from .grammar import * class InvalidSyntaxTest(TestCase): def test_rulesMissingEncloseList(self): class tmp(Rule): rules = ([0], [1]) with self.assertRaises(RuleSyntaxExcept...
Add base set of rule's invalid syntax tests
Add base set of rule's invalid syntax tests
Python
mit
PatrikValkovic/grammpy
from unittest import main, TestCase from grammpy import Rule + from grammpy.exceptions import RuleSyntaxException + from .grammar import * class InvalidSyntaxTest(TestCase): - pass + def test_rulesMissingEncloseList(self): + class tmp(Rule): + rules = ([0], [1]) + with...
Add base set of rule's invalid syntax tests
## Code Before: from unittest import main, TestCase from grammpy import Rule class InvalidSyntaxTest(TestCase): pass if __name__ == '__main__': main() ## Instruction: Add base set of rule's invalid syntax tests ## Code After: from unittest import main, TestCase from grammpy import Rule from grammpy.except...
12cb8ca101faa09e4cc07f9e257b3d3130892297
tests/sentry/web/frontend/tests.py
tests/sentry/web/frontend/tests.py
from __future__ import absolute_import import pytest from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TestCase @pytest.mark.xfail class ReplayTest(TestCase): @fixture def path(self): return reverse('sentry-replay', kwargs={ 'organizatio...
from __future__ import absolute_import from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TestCase class ReplayTest(TestCase): @fixture def path(self): return reverse('sentry-replay', kwargs={ 'organization_slug': self.organization.slug, ...
Remove xfail from replay test
Remove xfail from replay test
Python
bsd-3-clause
mitsuhiko/sentry,fotinakis/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,alexm92/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,nicholasserra/sentry,JackDanger/sentry,fotinakis/sentry,gencer/sentry,fotinakis/sentry,beeftornado/sentry,ifduyue/sentry,JamesMura/sentry,imankulov/sentry,l...
from __future__ import absolute_import - - import pytest from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TestCase - @pytest.mark.xfail class ReplayTest(TestCase): @fixture def path(self): return reverse('sentry-replay', k...
Remove xfail from replay test
## Code Before: from __future__ import absolute_import import pytest from django.core.urlresolvers import reverse from exam import fixture from sentry.testutils import TestCase @pytest.mark.xfail class ReplayTest(TestCase): @fixture def path(self): return reverse('sentry-replay', kwargs={ ...
23675e41656cac48f390d97f065b36de39e27d58
duckbot.py
duckbot.py
import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url(duckbot...
import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) rand = random.SystemRandom() @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = di...
Add a real roll command
Add a real roll command
Python
mit
andrewlin16/duckbot,andrewlin16/duckbot
import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) + rand = random.SystemRandom() @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.u...
Add a real roll command
## Code Before: import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.o...
30ed3800fdeec4aec399e6e0ec0760e46eb891ec
djangoautoconf/model_utils/model_reversion.py
djangoautoconf/model_utils/model_reversion.py
from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version from reversion.revisions import default_revision_manager global_save_signal_receiver = [] class PreSaveHandler(object): def __init__(s...
from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version def create_initial_version(obj): try: from reversion.revisions import default_revision_manager default_revision_manager...
Fix broken initial version creation.
Fix broken initial version creation.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version + + + def create_initial_version(obj): + try: - from reversion.revisions import default_revision_manager + from reversi...
Fix broken initial version creation.
## Code Before: from django.contrib.contenttypes.models import ContentType from django.db.models.signals import pre_save from django.dispatch import receiver from reversion.models import Version from reversion.revisions import default_revision_manager global_save_signal_receiver = [] class PreSaveHandler(object): ...
5237cb7f1339eb13b4c01f1c3611448a8f865726
terms/templatetags/terms.py
terms/templatetags/terms.py
from django.template import Library from ..html import TermsHTMLReconstructor register = Library() @register.filter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser.out
from django.template import Library from django.template.defaultfilters import stringfilter from ..html import TermsHTMLReconstructor register = Library() @register.filter @stringfilter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser.out
Make sure the filter arg is a string.
Make sure the filter arg is a string.
Python
bsd-3-clause
BertrandBordage/django-terms,philippeowagner/django-terms,BertrandBordage/django-terms,philippeowagner/django-terms
from django.template import Library + from django.template.defaultfilters import stringfilter from ..html import TermsHTMLReconstructor register = Library() @register.filter + @stringfilter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser...
Make sure the filter arg is a string.
## Code Before: from django.template import Library from ..html import TermsHTMLReconstructor register = Library() @register.filter def replace_terms(html): parser = TermsHTMLReconstructor() parser.feed(html) return parser.out ## Instruction: Make sure the filter arg is a string. ## Code After: from d...
1b218de76e8b09c70abcd88a2c6dd2c043bfc7f0
drcli/__main__.py
drcli/__main__.py
import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) def main(args=sys.argv[1:]): load_plugins(os.path.joi...
import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) def main(args=None): if args is None: args = sys....
Allow sub-commands to use same main function
Allow sub-commands to use same main function
Python
mit
schwa-lab/dr-apps-python
import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) - def main(args=sys.argv[1:...
Allow sub-commands to use same main function
## Code Before: import os.path import sys import imp import argparse from api import App, add_subparsers def load_plugins(dir): for f in os.listdir(dir): module_name, ext = os.path.splitext(f) if ext == '.py': imp.load_source('arbitrary', os.path.join(dir, f)) def main(args=sys.argv[1:]): load_plu...
85d684369e72aa2968f9ffbd0632f84558e1b44e
tests/test_vector2_dot.py
tests/test_vector2_dot.py
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x MAGNITUDE=1e10 @given(x=vectors(max_magn...
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x @given(x=vectors()) def test_dot_length(x...
Test that x² == |x|²
tests/dot: Test that x² == |x|²
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x + + @given(x=vector...
Test that x² == |x|²
## Code Before: from ppb_vector import Vector2 from math import isclose, sqrt import pytest # type: ignore from hypothesis import assume, given, note from utils import floats, vectors @given(x=vectors(), y=vectors()) def test_dot_commutes(x: Vector2, y: Vector2): assert x * y == y * x MAGNITUDE=1e10 @given(x=...
6d08c13fbf42eb4251d3477a904ab6d8513620df
dataset.py
dataset.py
from scrapy.item import Item, Field class DatasetItem(Item): name = Field() frequency = Field()
from scrapy.item import Item, Field class DatasetItem(Item): url = Field() name = Field() frequency = Field()
Add url field to Dataset web item
Add url field to Dataset web item
Python
mit
MaxLikelihood/CODE
from scrapy.item import Item, Field class DatasetItem(Item): + url = Field() name = Field() frequency = Field() - +
Add url field to Dataset web item
## Code Before: from scrapy.item import Item, Field class DatasetItem(Item): name = Field() frequency = Field() ## Instruction: Add url field to Dataset web item ## Code After: from scrapy.item import Item, Field class DatasetItem(Item): url = Field() name = Field() frequency = Field()
b5006a2820051e00c9fe4f5efe43e90129c12b4d
troposphere/cloudtrail.py
troposphere/cloudtrail.py
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "IncludeManagementE...
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "ExcludeManagementE...
Update Cloudtrail per 2021-09-10 changes
Update Cloudtrail per 2021-09-10 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False),...
Update Cloudtrail per 2021-09-10 changes
## Code Before: from . import AWSObject, AWSProperty, Tags from .validators import boolean class DataResource(AWSProperty): props = { "Type": (str, True), "Values": ([str], False), } class EventSelector(AWSProperty): props = { "DataResources": ([DataResource], False), "In...
053d6a2ca13b1f36a02fa3223092a10af35f6579
erpnext/patches/v10_0/item_barcode_childtable_migrate.py
erpnext/patches/v10_0/item_barcode_childtable_migrate.py
from __future__ import unicode_literals import frappe def execute(): items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") frappe.reload_doc("stock", "doctype", "item_barcode") for item in items_barcode: barcode = item.barcode.st...
from __future__ import unicode_literals import frappe def execute(): frappe.reload_doc("stock", "doctype", "item_barcode") items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") for item in items_barcode: barcode = item.barcode....
Move reload doc before get query
Move reload doc before get query
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
from __future__ import unicode_literals import frappe def execute(): + frappe.reload_doc("stock", "doctype", "item_barcode") + items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) + frappe.reload_doc("stock", "doctype", "item") + - frappe.reload_doc("stock"...
Move reload doc before get query
## Code Before: from __future__ import unicode_literals import frappe def execute(): items_barcode = frappe.get_all('Item', ['name', 'barcode'], { 'barcode': ('!=', '') }) frappe.reload_doc("stock", "doctype", "item") frappe.reload_doc("stock", "doctype", "item_barcode") for item in items_barcode: barcode =...
a2efdbc7c790df31f511d9a347774a961132d565
txircd/modules/cmode_l.py
txircd/modules/cmode_l.py
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): intParam = int(param) if str(intParam) != param: return [False, param] return [(intParam >= 0), param] def checkPermission(self, user,...
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): try: intParam = int(param) except ValueError: return [False, param] if str(intParam) != param: return [False, param] ...
Fix checking of limit parameter
Fix checking of limit parameter
Python
bsd-3-clause
DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): + try: - intParam = int(param) + intParam = int(param) + except ValueError: + return [False, param] if str(intP...
Fix checking of limit parameter
## Code Before: from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): intParam = int(param) if str(intParam) != param: return [False, param] return [(intParam >= 0), param] def checkPermis...
4de5050deda6c73fd9812a5e53938fea11e0b2cc
tests/unit/minion_test.py
tests/unit/minion_test.py
''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch from salt import minion from salt.exceptions import SaltSystemExit ensure_...
''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import python libs import os # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch # Import salt libs from salt import minion f...
Add test for sock path length
Add test for sock path length
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' + + # Import python libs + import os # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch + # Import salt libs...
Add test for sock path length
## Code Before: ''' :codeauthor: :email:`Mike Place <mp@saltstack.com>` ''' # Import Salt Testing libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch from salt import minion from salt.exceptions import SaltSyst...
e379aa75690d5bacc1d0bdec325ed4c16cf1a183
lims/permissions/views.py
lims/permissions/views.py
from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer
from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer search_fields = ('name',)
Add search functionality to permissions endpoint
Add search functionality to permissions endpoint
Python
mit
GETLIMS/LIMS-Backend,GETLIMS/LIMS-Backend
from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer + search_fields = ('...
Add search functionality to permissions endpoint
## Code Before: from django.contrib.auth.models import Permission from rest_framework import viewsets from .serializers import PermissionSerializer class PermissionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Permission.objects.all() serializer_class = PermissionSerializer ## Instruction: Add search ...
00922099d6abb03a0dbcca19781eb586d367eab0
skimage/measure/__init__.py
skimage/measure/__init__.py
from .find_contours import find_contours from ._regionprops import regionprops from .find_contours import find_contours from ._structural_similarity import ssim
from .find_contours import find_contours from ._regionprops import regionprops from ._structural_similarity import ssim
Remove double import of find contours.
BUG: Remove double import of find contours.
Python
bsd-3-clause
robintw/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,SamHames/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,chintak/scikit-image,rjeli/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,pratapvardha...
from .find_contours import find_contours from ._regionprops import regionprops - from .find_contours import find_contours from ._structural_similarity import ssim
Remove double import of find contours.
## Code Before: from .find_contours import find_contours from ._regionprops import regionprops from .find_contours import find_contours from ._structural_similarity import ssim ## Instruction: Remove double import of find contours. ## Code After: from .find_contours import find_contours from ._regionprops import regio...
985cefd81472069240b074423a831fe6031d6887
website_sale_available/controllers/website_sale_available.py
website_sale_available/controllers/website_sale_available.py
from openerp import http from openerp.http import request from openerp.addons.website_sale.controllers.main import website_sale class controller(website_sale): @http.route(['/shop/confirm_order'], type='http', auth="public", website=True) def confirm_order(self, **post): res = super(controller, self...
from openerp import http from openerp.http import request from openerp.addons.website_sale.controllers.main import website_sale class controller(website_sale): @http.route(['/shop/confirm_order'], type='http', auth="public", website=True) def confirm_order(self, **post): res = super(controller, self...
FIX sale_available integration with delivery
FIX sale_available integration with delivery
Python
mit
it-projects-llc/website-addons,it-projects-llc/website-addons,it-projects-llc/website-addons
from openerp import http from openerp.http import request from openerp.addons.website_sale.controllers.main import website_sale class controller(website_sale): @http.route(['/shop/confirm_order'], type='http', auth="public", website=True) def confirm_order(self, **post): res = ...
FIX sale_available integration with delivery
## Code Before: from openerp import http from openerp.http import request from openerp.addons.website_sale.controllers.main import website_sale class controller(website_sale): @http.route(['/shop/confirm_order'], type='http', auth="public", website=True) def confirm_order(self, **post): res = super(...
3f26d3c53f4bff36ec05da7a51a026b7d3ba5517
tests/modules/test_atbash.py
tests/modules/test_atbash.py
"""Tests for the Caeser module""" import pycipher from lantern.modules import atbash def _test_atbash(plaintext, *fitness_functions, top_n=1): ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True) decryption = atbash.decrypt(ciphertext) assert decryption == plaintext.upper() def test_de...
"""Tests for the Caeser module""" from lantern.modules import atbash def test_decrypt(): """Test decryption""" assert atbash.decrypt("uozt{Yzybolm}") == "flag{Babylon}" def test_encrypt(): """Test encryption""" assert ''.join(atbash.encrypt("flag{Babylon}")) == "uozt{Yzybolm}"
Remove unnecessary testing code from atbash
Remove unnecessary testing code from atbash
Python
mit
CameronLonsdale/lantern
"""Tests for the Caeser module""" - import pycipher - from lantern.modules import atbash - - - def _test_atbash(plaintext, *fitness_functions, top_n=1): - ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True) - decryption = atbash.decrypt(ciphertext) - - assert decryption == plainte...
Remove unnecessary testing code from atbash
## Code Before: """Tests for the Caeser module""" import pycipher from lantern.modules import atbash def _test_atbash(plaintext, *fitness_functions, top_n=1): ciphertext = pycipher.Atbash().encipher(plaintext, keep_punct=True) decryption = atbash.decrypt(ciphertext) assert decryption == plaintext.upper...
2c7065f82a242e6f05eaefda4ec902ddf9d90037
tests/test_stanc_warnings.py
tests/test_stanc_warnings.py
"""Test that stanc warnings are visible.""" import contextlib import io import stan def test_stanc_no_warning() -> None: """No warnings.""" program_code = "parameters {real y;} model {y ~ normal(0,1);}" buffer = io.StringIO() with contextlib.redirect_stderr(buffer): stan.build(program_code=pr...
"""Test that stanc warnings are visible.""" import contextlib import io import stan def test_stanc_no_warning() -> None: """No warnings.""" program_code = "parameters {real y;} model {y ~ normal(0,1);}" buffer = io.StringIO() with contextlib.redirect_stderr(buffer): stan.build(program_code=pr...
Update test for Stan 2.29
test: Update test for Stan 2.29
Python
isc
stan-dev/pystan,stan-dev/pystan
"""Test that stanc warnings are visible.""" import contextlib import io import stan def test_stanc_no_warning() -> None: """No warnings.""" program_code = "parameters {real y;} model {y ~ normal(0,1);}" buffer = io.StringIO() with contextlib.redirect_stderr(buffer): ...
Update test for Stan 2.29
## Code Before: """Test that stanc warnings are visible.""" import contextlib import io import stan def test_stanc_no_warning() -> None: """No warnings.""" program_code = "parameters {real y;} model {y ~ normal(0,1);}" buffer = io.StringIO() with contextlib.redirect_stderr(buffer): stan.build...
f668956fd37fa2fa0a0c82a8241671bf3cc306cb
tests/unit/moto_test_data.py
tests/unit/moto_test_data.py
import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} s3.put_object(Key=f"{prefix}/readme.txt", **default_kwargs) ...
import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} s3.put_object(Key="{}/readme.txt".format(prefix), **default_kw...
Fix string using py3 only feature.
Fix string using py3 only feature.
Python
mit
DigitalGlobe/gbdxtools,DigitalGlobe/gbdxtools
import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} - s3.put_object(Key=f"{prefix}/readme.txt", **...
Fix string using py3 only feature.
## Code Before: import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake data for testing.", "Bucket": bucket_name} s3.put_object(Key=f"{prefix}/readme.txt", **de...
03b685055037283279394d940602520c5ff7a817
email_log/models.py
email_log/models.py
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Email(models.Model): """Model to store outgoing email information""" from_email = mod...
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Email(models.Model): """Model to store outgoing email information""" from_email = mod...
Fix indentation problem and line length (PEP8)
Fix indentation problem and line length (PEP8)
Python
mit
treyhunner/django-email-log,treyhunner/django-email-log
from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Email(models.Model): """Model to store outgoing email information"""...
Fix indentation problem and line length (PEP8)
## Code Before: from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Email(models.Model): """Model to store outgoing email information""" ...
b25164e69d255beae1a76a9e1f7168a436a81f38
tests/test_utils.py
tests/test_utils.py
import helper from rock import utils class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s.write('ok') s.__exit__(None, None, None) self.a...
import helper from rock import utils from rock.exceptions import ConfigError class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s.write('ok') s._...
Test isexecutable check in utils.Shell
Test isexecutable check in utils.Shell
Python
mit
silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock,silas/rock
import helper from rock import utils + from rock.exceptions import ConfigError class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s...
Test isexecutable check in utils.Shell
## Code Before: import helper from rock import utils class UtilsTestCase(helper.unittest.TestCase): def test_shell(self): utils.Shell.run = lambda self: self s = utils.Shell() self.assertTrue(isinstance(s.__enter__(), utils.Shell)) s.write('ok') s.__exit__(None, None, None...
fc14e41432fece7d724aef73dd8ad7fef5e85c9a
flow/__init__.py
flow/__init__.py
from model import BaseModel from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature from extractor import Node,Graph,Aggregator,NotEnoughData from bytestream import ByteStream,ByteStreamFeature from data import \ IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\ ,StringDelimite...
from model import BaseModel from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature from extractor import Node,Graph,Aggregator,NotEnoughData from bytestream import ByteStream,ByteStreamFeature from data import \ IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\ ,StringDelimite...
Add IdentityEncoder to top-level exports
Add IdentityEncoder to top-level exports
Python
mit
JohnVinyard/featureflow,JohnVinyard/featureflow
from model import BaseModel from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature from extractor import Node,Graph,Aggregator,NotEnoughData from bytestream import ByteStream,ByteStreamFeature from data import \ IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuil...
Add IdentityEncoder to top-level exports
## Code Before: from model import BaseModel from feature import Feature,JSONFeature,TextFeature,CompressedFeature,PickleFeature from extractor import Node,Graph,Aggregator,NotEnoughData from bytestream import ByteStream,ByteStreamFeature from data import \ IdProvider,UuidProvider,UserSpecifiedIdProvider,KeyBuilder\...
ff4477c870b9c618b7432047071792c3a8055eb7
coffeeraspi/messages.py
coffeeraspi/messages.py
class DrinkOrder(): def __init__(self, mug_size, add_ins, name=None): self.mug_size = mug_size self.add_ins = add_ins self.name = name @classmethod def deserialize(cls, data): return DrinkOrder(data['mug_size'], data['add_ins'], data.get('name...
class DrinkOrder(): def __init__(self, mug_size, add_ins, name=None): self.mug_size = mug_size self.add_ins = add_ins self.name = name @classmethod def deserialize(cls, data): return DrinkOrder(data['mug_size'], data['add_ins'], data.get('name...
Add nicer drink order logging
Add nicer drink order logging
Python
apache-2.0
umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp,umbc-hackafe/htcpcp
class DrinkOrder(): def __init__(self, mug_size, add_ins, name=None): self.mug_size = mug_size self.add_ins = add_ins self.name = name @classmethod def deserialize(cls, data): return DrinkOrder(data['mug_size'], data['add_ins'], ...
Add nicer drink order logging
## Code Before: class DrinkOrder(): def __init__(self, mug_size, add_ins, name=None): self.mug_size = mug_size self.add_ins = add_ins self.name = name @classmethod def deserialize(cls, data): return DrinkOrder(data['mug_size'], data['add_ins'], ...
58be36ca646c4bb7fd4263a592cf3a240fbca64f
post_tag.py
post_tag.py
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes from bottle import post, request, redirect, mako_view as view @post("/post-tag") @view("post-tag") def r_post_tag(): client = init() m = request.forms.post post = client.get_post(m) tags = request.forms.tags create = request.forms.get...
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes from bottle import post, request, redirect, mako_view as view @post("/post-tag") @view("post-tag") def r_post_tag(): client = init() m = request.forms.post post = client.get_post(m) tags = request.forms.tags create = [a.decode("utf-8"...
Fix tag creation with non-ascii chars. (Dammit bottle!)
Fix tag creation with non-ascii chars. (Dammit bottle!)
Python
mit
drougge/wwwwellpapp,drougge/wwwwellpapp,drougge/wwwwellpapp
from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes from bottle import post, request, redirect, mako_view as view @post("/post-tag") @view("post-tag") def r_post_tag(): client = init() m = request.forms.post post = client.get_post(m) tags = request.forms.tags - cr...
Fix tag creation with non-ascii chars. (Dammit bottle!)
## Code Before: from common import init, globaldata, tag_clean, tag_prefix, tag_post, tagtypes from bottle import post, request, redirect, mako_view as view @post("/post-tag") @view("post-tag") def r_post_tag(): client = init() m = request.forms.post post = client.get_post(m) tags = request.forms.tags create = r...
bb32f2327d2e3aa386fffd2fd320a7af7b03ce95
corehq/apps/domain/project_access/middleware.py
corehq/apps/domain/project_access/middleware.py
from __future__ import absolute_import from __future__ import unicode_literals from datetime import datetime, timedelta from django.utils.deprecation import MiddlewareMixin from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY from corehq.util.quickcache import quickc...
from __future__ import absolute_import from __future__ import unicode_literals from datetime import datetime, timedelta from django.utils.deprecation import MiddlewareMixin from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY from corehq.util.quickcache import quickc...
Include superusers in web user domaing access record
Include superusers in web user domaing access record
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import from __future__ import unicode_literals from datetime import datetime, timedelta from django.utils.deprecation import MiddlewareMixin from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY from corehq.util.quickcache...
Include superusers in web user domaing access record
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from datetime import datetime, timedelta from django.utils.deprecation import MiddlewareMixin from corehq.apps.domain.project_access.models import SuperuserProjectEntryRecord, ENTRY_RECORD_FREQUENCY from corehq.util.quickcac...
d9f20935f6a0d5bf4e2c1dd1a3c5b41167f8518b
email_log/migrations/0001_initial.py
email_log/migrations/0001_initial.py
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=Tr...
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, ...
Fix migration file for Python 3.2 (and PEP8)
Fix migration file for Python 3.2 (and PEP8)
Python
mit
treyhunner/django-email-log,treyhunner/django-email-log
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ - (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_cr...
Fix migration file for Python 3.2 (and PEP8)
## Code Before: from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True...