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
e12432b0c97d1ddebf16df821fe6c77bb8b6a66b
wagtail/wagtailsites/wagtail_hooks.py
wagtail/wagtailsites/wagtail_hooks.py
from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls def register_admin_urls(): return [ url(r'^sit...
from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls @hooks.register('register_admin_urls') def register_admin_...
Move Sites to the settings menu (and use decorator syntax for hooks)
Move Sites to the settings menu (and use decorator syntax for hooks)
Python
bsd-3-clause
mixxorz/wagtail,wagtail/wagtail,KimGlazebrook/wagtail-experiment,gasman/wagtail,mayapurmedia/wagtail,kaedroho/wagtail,jnns/wagtail,serzans/wagtail,hanpama/wagtail,iho/wagtail,marctc/wagtail,kurtw/wagtail,nilnvoid/wagtail,nrsimha/wagtail,gasman/wagtail,jorge-marques/wagtail,Toshakins/wagtail,rsalmaso/wagtail,takeflight/...
from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls + @hooks.register('register_admin_urls...
Move Sites to the settings menu (and use decorator syntax for hooks)
## Code Before: from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls def register_admin_urls(): return [ ...
6689858b2364a668b362a5f00d4c86e57141dc37
numba/cuda/models.py
numba/cuda/models.py
from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def __init__(self, dmm, f...
from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def __init__(self, dmm, f...
Reorder FloatModel checks in ascending order
CUDA: Reorder FloatModel checks in ascending order
Python
bsd-2-clause
cpcloud/numba,numba/numba,numba/numba,seibert/numba,cpcloud/numba,cpcloud/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,numba/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,IntelLabs/numba,IntelLabs/numba,seibert/numba,IntelLabs/numba,numba/numba
from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def...
Reorder FloatModel checks in ascending order
## Code Before: from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def __ini...
4a650922ee97b9cb54b203cab9709d511487d9ff
silver/tests/factories.py
silver/tests/factories.py
"""Factories for the silver app.""" # import factory # from .. import models
import factory from silver.models import Provider class ProviderFactory(factory.django.DjangoModelFactory): class Meta: model = Provider
Add factory for the Provider model
Add factory for the Provider model
Python
apache-2.0
PressLabs/silver,PressLabs/silver,PressLabs/silver
- """Factories for the silver app.""" - # import factory + import factory - # from .. import models + from silver.models import Provider + + class ProviderFactory(factory.django.DjangoModelFactory): + class Meta: + model = Provider +
Add factory for the Provider model
## Code Before: """Factories for the silver app.""" # import factory # from .. import models ## Instruction: Add factory for the Provider model ## Code After: import factory from silver.models import Provider class ProviderFactory(factory.django.DjangoModelFactory): class Meta: model = Provider
d0a907872749f1bb54d6e8e160ea170059289623
source/custom/combo.py
source/custom/combo.py
import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator, name=wx.ComboBoxNameStr): OwnerDrawnComb...
import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator, name=wx.ComboBoxNameStr): Owne...
Set ComboBox class default ID to wx.ID_ANY
Set ComboBox class default ID to wx.ID_ANY
Python
mit
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): - def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition, + def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSiz...
Set ComboBox class default ID to wx.ID_ANY
## Code Before: import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, validator=wx.DefaultValidator, name=wx.ComboBoxNameStr): ...
2560ca287e81cbefb6037e5688bfa4ef74d85149
clock.py
clock.py
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.run( "notif...
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.check_call( ...
Change call method for Python2.7
Change call method for Python2.7
Python
mit
oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/dmm-eikaiwa-fft
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") - subp...
Change call method for Python2.7
## Code Before: from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.run...
6bb9a4ed50ad879c56cdeae0dedb49bba6780780
matchers/volunteer.py
matchers/volunteer.py
import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick'] all_candidates = dev_candidates + ['Craig', 'Evan'] def respond(self, message, user=None): ...
import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergeant'] all_candidates = dev_candidates + ['cz', 'ehazlett'] def respond(self, mes...
Use IRC Nicks instead of real names.
Use IRC Nicks instead of real names.
Python
bsd-2-clause
honza/nigel
import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" - dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick'] + dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergea...
Use IRC Nicks instead of real names.
## Code Before: import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick'] all_candidates = dev_candidates + ['Craig', 'Evan'] def respond(self, messa...
7016b7bb026e0fe557ca06efa81dace9999e526d
hubbot/Modules/Healthcheck.py
hubbot/Modules/Healthcheck.py
from twisted.internet import reactor, protocol from hubbot.moduleinterface import ModuleInterface class Echo(protocol.Protocol): """This is just about the simplest possible protocol""" def dataReceived(self, data): """As soon as any data is received, write it back.""" self.transport.write(da...
from twisted.protocols import basic from twisted.internet import protocol, reactor from hubbot.moduleinterface import ModuleInterface class HealthcheckProtocol(basic.LineReceiver): def lineReceived(self, line): response_body = "All is well. Ish." self.sendLine("HTTP/1.0 200 OK".encode("UTF-8")) ...
Write a slightly less dumb protocol?
Write a slightly less dumb protocol?
Python
mit
HubbeKing/Hubbot_Twisted
+ from twisted.protocols import basic - from twisted.internet import reactor, protocol + from twisted.internet import protocol, reactor from hubbot.moduleinterface import ModuleInterface + class HealthcheckProtocol(basic.LineReceiver): - class Echo(protocol.Protocol): - """This is just about the simplest...
Write a slightly less dumb protocol?
## Code Before: from twisted.internet import reactor, protocol from hubbot.moduleinterface import ModuleInterface class Echo(protocol.Protocol): """This is just about the simplest possible protocol""" def dataReceived(self, data): """As soon as any data is received, write it back.""" self.tr...
0eaff91695eefcf289e31d8ca93d19ab5bbd392d
katana/expr.py
katana/expr.py
import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex def on_match(self, string): return [self.name, string] def callback(self, _, string): return self.on_match(string) class Scanner(object): def __init__(self, exprs): ...
import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex def __iter__(self): yield self.regex yield lambda _, token: self.on_match(token) def on_match(self, string): return [self.name, string] class Scanner(object): ...
Refactor Expr object to be more self contained
Refactor Expr object to be more self contained
Python
mit
eugene-eeo/katana
import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex + def __iter__(self): + yield self.regex + yield lambda _, token: self.on_match(token) + def on_match(self, string): return [self.name, string] -...
Refactor Expr object to be more self contained
## Code Before: import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex def on_match(self, string): return [self.name, string] def callback(self, _, string): return self.on_match(string) class Scanner(object): def __init__(...
ce2e5b0dc3ddafe931a902cb7aa24c3adbc246b7
fireplace/cards/wog/neutral_legendary.py
fireplace/cards/wog/neutral_legendary.py
from ..utils import * ## # Minions
from ..utils import * ## # Minions class OG_122: "Mukla, Tyrant of the Vale" play = Give(CONTROLLER, "EX1_014t") * 2 class OG_318: "Hogger, Doom of Elwynn" events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t")) class OG_338: "Nat, the Darkfisher" events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
Implement corrupted Mukla, Hogger and Nat
Implement corrupted Mukla, Hogger and Nat
Python
agpl-3.0
beheh/fireplace,NightKev/fireplace,jleclanche/fireplace
from ..utils import * ## # Minions + class OG_122: + "Mukla, Tyrant of the Vale" + play = Give(CONTROLLER, "EX1_014t") * 2 + + + class OG_318: + "Hogger, Doom of Elwynn" + events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t")) + + + class OG_338: + "Nat, the Darkfisher" + events = BeginTurn(OPP...
Implement corrupted Mukla, Hogger and Nat
## Code Before: from ..utils import * ## # Minions ## Instruction: Implement corrupted Mukla, Hogger and Nat ## Code After: from ..utils import * ## # Minions class OG_122: "Mukla, Tyrant of the Vale" play = Give(CONTROLLER, "EX1_014t") * 2 class OG_318: "Hogger, Doom of Elwynn" events = SELF_DAMAGE.on(Summ...
5ed9e43ec451aca9bdca4391bd35934e5fe4aea3
huts/management/commands/dumphutsjson.py
huts/management/commands/dumphutsjson.py
from django.core.management.base import BaseCommand from huts.utils import export class Command(BaseCommand): args = '' help = 'Dumps the huts, agencies, and regions in the json api format.' def handle(self, *args, **options): print(export.db_as_json().encode('utf-8'))
from optparse import make_option from django.core.management.base import BaseCommand from huts.utils import export class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--file', help='Write to file instead of stdout' ), ) help = 'Dumps...
Update command to take file argument
Update command to take file argument
Python
mit
dylanfprice/hutmap,dylanfprice/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap
+ from optparse import make_option + from django.core.management.base import BaseCommand from huts.utils import export + class Command(BaseCommand): - args = '' + option_list = BaseCommand.option_list + ( + make_option( + '--file', + help='Write to file instead of stdo...
Update command to take file argument
## Code Before: from django.core.management.base import BaseCommand from huts.utils import export class Command(BaseCommand): args = '' help = 'Dumps the huts, agencies, and regions in the json api format.' def handle(self, *args, **options): print(export.db_as_json().encode('utf-8')) ## Instruct...
2d3e52567d7d361428ce93d02cc42ecaddacab6c
tests/test_commands.py
tests/test_commands.py
from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=True) @patch('os.getcwd',...
from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=True) @patch('os.getcwd',...
Test cases for push with export flag
Test cases for push with export flag
Python
apache-2.0
couchapp/couchapp,h4ki/couchapp,couchapp/couchapp,couchapp/couchapp,h4ki/couchapp,h4ki/couchapp,couchapp/couchapp,h4ki/couchapp
from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=Tru...
Test cases for push with export flag
## Code Before: from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=True) @pa...
9dc253b79d885ca205b557f88fca6fa35bd8fe21
tests/test_selector.py
tests/test_selector.py
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def tes...
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def tes...
Make Selector.scope test more rigorous
Make Selector.scope test more rigorous
Python
mit
eugene-eeo/scell
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list...
Make Selector.scope test more rigorous
## Code Before: from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select())...
7520e1285af36292def45f892808841e78cc4a2b
bloop/index.py
bloop/index.py
missing = object() class GlobalSecondaryIndex(object): def __init__(self, hash_key=None, range_key=None, write_units=1, read_units=1, name=missing): self._model_name = None self._backing_name = name self.write_units = write_units self.read_units = read_units ...
class Index(object): def __init__(self, write_units=1, read_units=1, name=None, range_key=None): self._model_name = None self._dynamo_name = name self.write_units = write_units self.read_units = read_units self.range_key = range_key @property def model_name(self): ...
Refactor GSI, LSI to use base Index class
Refactor GSI, LSI to use base Index class
Python
mit
numberoverzero/bloop,numberoverzero/bloop
+ class Index(object): + def __init__(self, write_units=1, read_units=1, name=None, range_key=None): - missing = object() - - - class GlobalSecondaryIndex(object): - def __init__(self, hash_key=None, range_key=None, - write_units=1, read_units=1, name=missing): self._model_name = No...
Refactor GSI, LSI to use base Index class
## Code Before: missing = object() class GlobalSecondaryIndex(object): def __init__(self, hash_key=None, range_key=None, write_units=1, read_units=1, name=missing): self._model_name = None self._backing_name = name self.write_units = write_units self.read_units = ...
db4ccce9e418a1227532bde8834ca682bc873609
system/t04_mirror/show.py
system/t04_mirror/show.py
from lib import BaseTest class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ show mirror: missing mirror """...
from lib import BaseTest import re class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ show mirror: missing mirr...
Remove updated at while comparing.
Remove updated at while comparing.
Python
mit
gearmover/aptly,bsundsrud/aptly,adfinis-forks/aptly,vincentbernat/aptly,gdbdzgd/aptly,ceocoder/aptly,adfinis-forks/aptly,seaninspace/aptly,neolynx/aptly,scalp42/aptly,gdbdzgd/aptly,sobczyk/aptly,neolynx/aptly,scalp42/aptly,aptly-dev/aptly,seaninspace/aptly,aptly-dev/aptly,bsundsrud/aptly,gdbdzgd/aptly,bankonme/aptly,ad...
from lib import BaseTest + import re class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ ...
Remove updated at while comparing.
## Code Before: from lib import BaseTest class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ show mirror: missin...
1e8c094c0f806b624a41447446676c1f2ac3590d
tools/debug_adapter.py
tools/debug_adapter.py
import sys if 'darwin' in sys.platform: sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') sys.path.append('.') import adapter adapter.main.run_tcp_server()
import sys import subprocess import string out = subprocess.check_output(['lldb', '-P']) sys.path.append(string.strip(out)) sys.path.append('.') import adapter adapter.main.run_tcp_server()
Fix adapter debugging on Linux.
Fix adapter debugging on Linux.
Python
mit
vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb
import sys - if 'darwin' in sys.platform: - sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') + import subprocess + import string + + out = subprocess.check_output(['lldb', '-P']) + sys.path.append(string.strip(out)) sys.path.append('.') import adapter ...
Fix adapter debugging on Linux.
## Code Before: import sys if 'darwin' in sys.platform: sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') sys.path.append('.') import adapter adapter.main.run_tcp_server() ## Instruction: Fix adapter debugging on Linux. ## Code After: import sys import subprocess...
73e8864e745ca75c2ea327b53244c9f2f4183e1a
lambda_function.py
lambda_function.py
from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, write_contacts_xlsx ) def s3_contacts(contacts, bucket, key): s3 = boto3.client('s3') o = StringIO() if key.endswith('.csv'): t = 'text/csv' write_co...
from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, write_contacts_xlsx, ) from dmrx_most_heard_n0gsg import ( get_users as get_most_heard, write_n0gsg_csv, ) def s3_contacts(contacts, bucket, key): s3 = boto3.clien...
Add N0GSG DMRX MostHeard to AWS Lambda function
Add N0GSG DMRX MostHeard to AWS Lambda function
Python
apache-2.0
ajorg/DMR_contacts
from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, - write_contacts_xlsx + write_contacts_xlsx, + ) + from dmrx_most_heard_n0gsg import ( + get_users as get_most_heard, + write_n0gsg_csv, ) de...
Add N0GSG DMRX MostHeard to AWS Lambda function
## Code Before: from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, write_contacts_xlsx ) def s3_contacts(contacts, bucket, key): s3 = boto3.client('s3') o = StringIO() if key.endswith('.csv'): t = 'text/csv' ...
6dfb0c1ea4fb3d12d14a07d0e831eb32f3b2f340
yaml_argparse.py
yaml_argparse.py
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument...
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() r...
Implement creating arguments for multiple strings
Implement creating arguments for multiple strings
Python
mit
krasch/yaml_argparse,krasch/quickargs
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) - # to start with, support only a single parameter - key = list(yaml_data.keys())[0] - value = yaml_data[key] parser = argparse.ArgumentParser...
Implement creating arguments for multiple strings
## Code Before: import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() par...
eae4b06bd798eab3a46bdd5b7452411bb7fb02e1
dashcam.py
dashcam.py
import pygame import picamera import os os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
import pygame import picamera import os import sys import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') size = width, height = 320, 240 pygame.init() pygame.mouse.set_visible(False) scre...
Update dascham with pygame GO button load
Update dascham with pygame GO button load
Python
mit
the-raspberry-pi-guy/bike_dashcam,the-raspberry-pi-guy/bike_dashcam
import pygame import picamera import os + import sys + import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') + size = width, height = 320, 240 + pygame.init() pygam...
Update dascham with pygame GO button load
## Code Before: import pygame import picamera import os os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode((0,0), pyg...
b35d4292e50e8a8dc56635bddeac5a1fc42a5d19
tveebot_tracker/source.py
tveebot_tracker/source.py
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
Rename Source's get_episodes_for() method to fetch()
Rename Source's get_episodes_for() method to fetch()
Python
mit
tveebot/tracker
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracke...
Rename Source's get_episodes_for() method to fetch()
## Code Before: from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obt...
30c21806dcc347326d6ac51be2adac9ff637f241
day20/part1.py
day20/part1.py
ranges = [] for line in open('input.txt', 'r'): ranges.append(tuple(map(int, line.split('-')))) ranges.sort() lowest = 0 for l, r in ranges: if l <= lowest <= r: lowest = r + 1 print(lowest) input()
ranges = [] for line in open('input.txt', 'r'): ranges.append(tuple(map(int, line.split('-')))) ranges.sort() lowest = 0 for l, r in ranges: if l > lowest: break if lowest <= r: lowest = r + 1 print(lowest) input()
Break the loop at the first gap
Break the loop at the first gap
Python
unlicense
ultramega/adventofcode2016
ranges = [] for line in open('input.txt', 'r'): ranges.append(tuple(map(int, line.split('-')))) ranges.sort() lowest = 0 for l, r in ranges: + if l > lowest: + break - if l <= lowest <= r: + if lowest <= r: lowest = r + 1 print(lowest) input()
Break the loop at the first gap
## Code Before: ranges = [] for line in open('input.txt', 'r'): ranges.append(tuple(map(int, line.split('-')))) ranges.sort() lowest = 0 for l, r in ranges: if l <= lowest <= r: lowest = r + 1 print(lowest) input() ## Instruction: Break the loop at the first gap ## Code After: ranges = [] for line in...
4a75df6e253401cbed7b31e1882211946f02093a
src/ggrc/__init__.py
src/ggrc/__init__.py
from .bootstrap import db, logger
from ggrc.bootstrap import db __all__ = [ db ]
Remove logger from ggrc init
Remove logger from ggrc init The logger from ggrc init is never used and should be removed.
Python
apache-2.0
selahssea/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-co...
- from .bootstrap import db, logger + from ggrc.bootstrap import db + __all__ = [ + db + ] +
Remove logger from ggrc init
## Code Before: from .bootstrap import db, logger ## Instruction: Remove logger from ggrc init ## Code After: from ggrc.bootstrap import db __all__ = [ db ]
3885fcbb31393f936bc58842dc06bdc9ffe55151
fabfile.py
fabfile.py
from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task def update_dependencies(): with prefix('workon jarvis2'): run('pip install --use-mirr...
from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix from fabric.contrib.project import rsync_project env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task def push_code(): rsync_project(local_dir='.'...
Add task for pushing code with rsync
Add task for pushing code with rsync
Python
mit
Foxboron/Frank,mpolden/jarvis2,martinp/jarvis2,Foxboron/Frank,mpolden/jarvis2,mpolden/jarvis2,martinp/jarvis2,Foxboron/Frank,martinp/jarvis2
from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix + from fabric.contrib.project import rsync_project env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task + def push_code(...
Add task for pushing code with rsync
## Code Before: from fabric.api import env, run, sudo, task from fabric.context_managers import cd, prefix env.use_ssh_config = True home = '~/jarvis2' @task def pull_code(): with cd(home): run('git pull --rebase') @task def update_dependencies(): with prefix('workon jarvis2'): run('pip in...
decb1699fe036c55d33c7d3b77a834cf8c3ee785
RPLCD/__init__.py
RPLCD/__init__.py
from .common import Alignment, CursorMode, ShiftMode, BacklightMode from .contextmanagers import cursor, cleared
import warnings from .common import Alignment, CursorMode, ShiftMode, BacklightMode from .contextmanagers import cursor, cleared from .gpio import CharLCD as GpioCharLCD class CharLCD(GpioCharLCD): def __init__(self, *args, **kwargs): warnings.warn("Using RPLCD.CharLCD directly is deprecated. " + ...
Add backwards compatible CharLCD wrapper
Add backwards compatible CharLCD wrapper
Python
mit
GoranLundberg/RPLCD,thijstriemstra/RPLCD,dbrgn/RPLCD,paulenuta/RPLCD
+ import warnings + from .common import Alignment, CursorMode, ShiftMode, BacklightMode from .contextmanagers import cursor, cleared + from .gpio import CharLCD as GpioCharLCD + class CharLCD(GpioCharLCD): + def __init__(self, *args, **kwargs): + warnings.warn("Using RPLCD.CharLCD directly is deprec...
Add backwards compatible CharLCD wrapper
## Code Before: from .common import Alignment, CursorMode, ShiftMode, BacklightMode from .contextmanagers import cursor, cleared ## Instruction: Add backwards compatible CharLCD wrapper ## Code After: import warnings from .common import Alignment, CursorMode, ShiftMode, BacklightMode from .contextmanagers import curs...
d3675b777dc95f296f26bdd9b8b05311ceac6ba5
cyder/core/system/migrations/0006_rename_table_from_system_key_value_to_system_kv.py
cyder/core/system/migrations/0006_rename_table_from_system_key_value_to_system_kv.py
from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): db.rename_table('system_key_value', 'system_kv') def backwards(self, orm): db.rename_table('system_kv', 'system_key_value')
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db.rename_table('system_key_value', 'system_kv') def backwards(self, orm): db.rename_table('system_kv', 'system_key_value') ...
Add ORM freeze thing to SystemKeyValue migration
Add ORM freeze thing to SystemKeyValue migration
Python
bsd-3-clause
akeym/cyder,murrown/cyder,zeeman/cyder,akeym/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,akeym/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder
+ import datetime from south.db import db from south.v2 import SchemaMigration + from django.db import models class Migration(SchemaMigration): def forwards(self, orm): db.rename_table('system_key_value', 'system_kv') def backwards(self, orm): db.rename_table('system_kv...
Add ORM freeze thing to SystemKeyValue migration
## Code Before: from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): db.rename_table('system_key_value', 'system_kv') def backwards(self, orm): db.rename_table('system_kv', 'system_key_value') ## Instruction: Add ORM freeze ...
442f0df33b91fced038e2c497e6c03e0f82f55b2
qtpy/QtTest.py
qtpy/QtTest.py
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: ...
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) elif PYSIDE: ...
Add support for QTest with PySide
Add support for QTest with PySide
Python
mit
spyder-ide/qtpy,davvid/qtpy,goanpeca/qtpy,davvid/qtpy,goanpeca/qtpy
from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(...
Add support for QTest with PySide
## Code Before: from qtpy import PYQT5, PYQT4, PYSIDE, PythonQtError if PYQT5: from PyQt5.QtTest import QTest elif PYQT4: from PyQt4.QtTest import QTest as OldQTest class QTest(OldQTest): @staticmethod def qWaitForWindowActive(QWidget): OldQTest.qWaitForWindowShown(QWidget) e...
3a0cf1f6114d6c80909f90fe122b026908200b0a
IPython/nbconvert/exporters/markdown.py
IPython/nbconvert/exporters/markdown.py
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #---------------...
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #---------------...
Revert "Removed Javascript from Markdown by adding display priority to def config."
Revert "Removed Javascript from Markdown by adding display priority to def config." This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. ...
Revert "Removed Javascript from Markdown by adding display priority to def config."
## Code Before: """Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. ...
b922273cb4786e72dbf018b33100814e2a462ebe
examples/list_stats.py
examples/list_stats.py
import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.server != "": if not w...
import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.server != "": if not ...
Add encoding line for Python 3
Fix: Add encoding line for Python 3
Python
mit
linusg/wsinfo
+ import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.ser...
Add encoding line for Python 3
## Code Before: import sys import os import operator sys.path.insert(1, os.path.abspath('..')) from wsinfo import Info cnt = 0 max_cnt = 100 servers = {} with open("urls.txt", "r") as f: for url in f.readlines(): url = url[:-1] try: w = Info(url) if w.server != "": ...
8c34cc43d23e0d97c531e1aa5d2339693db554e0
projects/projectdl.py
projects/projectdl.py
from bs4 import BeautifulSoup import requests r = requests.get("https://projects.archlinux.org/") soup = BeautifulSoup(r.text) repos = soup.select(".sublevel-repo a") repo_names = [] for repo in repos: repo_name = repo.string if repo_name[-4:] == ".git": repo_name = repo_name[:-4] repo_names.appe...
from bs4 import BeautifulSoup import requests import simplediff from pprint import pprint r = requests.get("https://projects.archlinux.org/") soup = BeautifulSoup(r.text) repos = soup.select(".sublevel-repo a") with open("projects.txt", mode = "r", encoding = "utf-8") as projects_file: cur_repos = projects_file....
Update project downloader to do diffs before overwriting
Update project downloader to do diffs before overwriting
Python
unlicense
djmattyg007/archlinux,djmattyg007/archlinux
from bs4 import BeautifulSoup import requests + import simplediff + from pprint import pprint r = requests.get("https://projects.archlinux.org/") soup = BeautifulSoup(r.text) repos = soup.select(".sublevel-repo a") - repo_names = [] + with open("projects.txt", mode = "r", encoding = "utf-8") as proje...
Update project downloader to do diffs before overwriting
## Code Before: from bs4 import BeautifulSoup import requests r = requests.get("https://projects.archlinux.org/") soup = BeautifulSoup(r.text) repos = soup.select(".sublevel-repo a") repo_names = [] for repo in repos: repo_name = repo.string if repo_name[-4:] == ".git": repo_name = repo_name[:-4] ...
14e98bc2038f50f38244550a1fa7ec3f836ed5f3
http/online_checker.py
http/online_checker.py
import http.client def __is_online(domain, sub_path, response_status, response_reason): conn = http.client.HTTPSConnection(domain, timeout=1) conn.request("HEAD", sub_path) response = conn.getresponse() conn.close() return (response.status == response_status) and (response.reason == response_reas...
import http.client def __is_online(domain, sub_path, response_status, response_reason): conn = http.client.HTTPSConnection(domain, timeout=1) conn.request("HEAD", sub_path) response = conn.getresponse() conn.close() return (response.status == response_status) and (response.reason == response_re...
Add docstring to online checker
Add docstring to online checker
Python
mit
thatsIch/sublime-rainmeter
+ + import http.client def __is_online(domain, sub_path, response_status, response_reason): conn = http.client.HTTPSConnection(domain, timeout=1) conn.request("HEAD", sub_path) response = conn.getresponse() conn.close() return (response.status == response_status) and (respon...
Add docstring to online checker
## Code Before: import http.client def __is_online(domain, sub_path, response_status, response_reason): conn = http.client.HTTPSConnection(domain, timeout=1) conn.request("HEAD", sub_path) response = conn.getresponse() conn.close() return (response.status == response_status) and (response.reason ...
bda756847e31e97eb8363f48bed67035a3f46d67
settings/travis.py
settings/travis.py
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST...
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '', 'HOST...
Use Solr for testing with Travis CI
Use Solr for testing with Travis CI
Python
mit
denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase,denverfoundation/storybase
from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD...
Use Solr for testing with Travis CI
## Code Before: from defaults import * DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'ENGINE': 'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'atlas_test', 'USER': 'postgres', 'PASSWORD': '...
080e4336675ea29b28b63698e5a0e77e91d54a2b
exercises/acronym/acronym_test.py
exercises/acronym/acronym_test.py
import unittest from acronym import abbreviate # test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG') def test_lowercase_words(self): self.assertE...
import unittest from acronym import abbreviate # test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG') def test_lowercase_words(self): self.assertE...
Remove test with mixed-case word
acronym: Remove test with mixed-case word see: https://github.com/exercism/x-common/pull/788
Python
mit
jmluy/xpython,smalley/python,exercism/xpython,exercism/python,smalley/python,jmluy/xpython,pheanex/xpython,pheanex/xpython,exercism/xpython,behrtam/xpython,exercism/python,N-Parsons/exercism-python,N-Parsons/exercism-python,mweb/python,mweb/python,behrtam/xpython
import unittest from acronym import abbreviate - # test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0 + # test cases adapted from `x-common//canonical-data.json` @ version: 1.1.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbrevia...
Remove test with mixed-case word
## Code Before: import unittest from acronym import abbreviate # test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0 class AcronymTest(unittest.TestCase): def test_basic(self): self.assertEqual(abbreviate('Portable Network Graphics'), 'PNG') def test_lowercase_words(self): ...
124489e979ed9d913b97ff688ce65d678579e638
morse_modem.py
morse_modem.py
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_test import * if __name__ == "__main__": #gen_test_data() data = gen_test_data() #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(data) element_r...
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_tone import * import random if __name__ == "__main__": WPM = random.uniform(2,20) pattern = [1,0,1,1,1,0,0,0,0,0,0,0] # morse code 'A' #gen_test_data() data = gen_tone(pattern) #p...
Add tone generation arguments to gen_tone
Add tone generation arguments to gen_tone
Python
mit
nickodell/morse-code
import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * - from gen_test import * + from gen_tone import * + import random - if __name__ == "__main__": + if __name__ == "__main__": + WPM = random.uniform(2,20) + pattern = [1,0,1,1,1,0...
Add tone generation arguments to gen_tone
## Code Before: import cProfile from demodulate.cfg import * from demodulate.detect_tone import * from demodulate.element_resolve import * from gen_test import * if __name__ == "__main__": #gen_test_data() data = gen_test_data() #print len(data)/SAMPLE_FREQ #cProfile.run('detect_tone(data)') #print detect_tone(...
f39f7d64ba8ca8051b24407811239f960cc6f561
lib/collect/backend.py
lib/collect/backend.py
import lib.collect.config as config if config.BACKEND == 'dynamodb': import lib.collect.backends.dymamodb as api else: import lib.collect.backends.localfs as api
import lib.collect.config as config try: if config.BACKEND == 'dynamodb': import lib.collect.backends.dymamodb as api else: import lib.collect.backends.localfs as api except AttributeError: import lib.collect.backends.localfs as api
Fix bug in module selection.
Fix bug in module selection.
Python
mit
ic/mark0
import lib.collect.config as config + try: - if config.BACKEND == 'dynamodb': + if config.BACKEND == 'dynamodb': - import lib.collect.backends.dymamodb as api + import lib.collect.backends.dymamodb as api - else: + else: + import lib.collect.backends.localfs as api + except AttributeErr...
Fix bug in module selection.
## Code Before: import lib.collect.config as config if config.BACKEND == 'dynamodb': import lib.collect.backends.dymamodb as api else: import lib.collect.backends.localfs as api ## Instruction: Fix bug in module selection. ## Code After: import lib.collect.config as config try: if config.BACKEND == 'dyna...
f6bff4e5360ba2c0379c129a111d333ee718c1d3
datafeeds/usfirst_event_teams_parser.py
datafeeds/usfirst_event_teams_parser.py
import re from BeautifulSoup import BeautifulSoup from datafeeds.parser_base import ParserBase class UsfirstEventTeamsParser(ParserBase): @classmethod def parse(self, html): """ Find what Teams are attending an Event, and return their team_numbers. """ teamRe = re.compile(r'...
import re from BeautifulSoup import BeautifulSoup from datafeeds.parser_base import ParserBase class UsfirstEventTeamsParser(ParserBase): @classmethod def parse(self, html): """ Find what Teams are attending an Event, and return their team_numbers. """ teamRe = re.compile(r'...
Fix event teams parser for new format
Fix event teams parser for new format
Python
mit
the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-allian...
import re from BeautifulSoup import BeautifulSoup from datafeeds.parser_base import ParserBase class UsfirstEventTeamsParser(ParserBase): @classmethod def parse(self, html): """ Find what Teams are attending an Event, and return their team_numbers. """ + ...
Fix event teams parser for new format
## Code Before: import re from BeautifulSoup import BeautifulSoup from datafeeds.parser_base import ParserBase class UsfirstEventTeamsParser(ParserBase): @classmethod def parse(self, html): """ Find what Teams are attending an Event, and return their team_numbers. """ teamRe...
b80726a5a36480b4146fc4df89ad96a738aa2091
waitress/settings/__init__.py
waitress/settings/__init__.py
import os if os.getenv('OPENSHIFT_REPO_DIR'): from .staging import * elif os.getenv('TRAVIS_CI'): from .testing import * else: from .development import *
import os if os.getenv('OPENSHIFT_REPO_DIR'): from .staging import * elif os.getenv('TRAVIS_CI'): from .testing import * elif os.getenv('HEROKU'): from .production import * else: from .development import *
Use production settings in Heroku
[fix] Use production settings in Heroku
Python
mit
waitress-andela/waitress,andela-osule/waitress,andela-osule/waitress,andela-osule/waitress,waitress-andela/waitress,waitress-andela/waitress
import os if os.getenv('OPENSHIFT_REPO_DIR'): from .staging import * elif os.getenv('TRAVIS_CI'): from .testing import * + elif os.getenv('HEROKU'): + from .production import * else: from .development import *
Use production settings in Heroku
## Code Before: import os if os.getenv('OPENSHIFT_REPO_DIR'): from .staging import * elif os.getenv('TRAVIS_CI'): from .testing import * else: from .development import * ## Instruction: Use production settings in Heroku ## Code After: import os if os.getenv('OPENSHIFT_REPO_DIR'): from .staging import ...
814684225140231de25dc7ee616c6bfa73b312ee
addons/hr/__terp__.py
addons/hr/__terp__.py
{ "name" : "Human Resources", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "description": """ Module for human resource management. You can manage: * Employees and hierarchies * Work hours sheets * Attendances and sign i...
{ "name" : "Human Resources", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "description": """ Module for human resource management. You can manage: * Employees and hierarchies * Work hours sheets * Attendances and sign i...
Add hr_security.xml file entry in update_xml section
Add hr_security.xml file entry in update_xml section bzr revid: mga@tinyerp.com-d69c221f3647e67487af7bd1c349e27cdbbbe857
Python
agpl-3.0
VielSoft/odoo,naousse/odoo,tarzan0820/odoo,BT-ojossen/odoo,leoliujie/odoo,Danisan/odoo-1,ehirt/odoo,odooindia/odoo,ThinkOpen-Solutions/odoo,bakhtout/odoo-educ,ingadhoc/odoo,naousse/odoo,datenbetrieb/odoo,charbeljc/OCB,sysadminmatmoz/OCB,cysnake4713/odoo,arthru/OpenUpgrade,bwrsandman/OpenUpgrade,ovnicraft/odoo,sysadminm...
{ "name" : "Human Resources", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "description": """ Module for human resource management. You can manage: * Employees and hierarchies * Work hours sheets * ...
Add hr_security.xml file entry in update_xml section
## Code Before: { "name" : "Human Resources", "version" : "1.0", "author" : "Tiny", "category" : "Generic Modules/Human Resources", "website" : "http://tinyerp.com/module_hr.html", "description": """ Module for human resource management. You can manage: * Employees and hierarchies * Work hours sheets * Attend...
164a80ce3bcffad0e233426830c712cddd2f750b
thefederation/apps.py
thefederation/apps.py
import datetime import sys import django_rq from django.apps import AppConfig class TheFederationConfig(AppConfig): name = "thefederation" verbose_name = "The Federation" def ready(self): # Only register tasks if RQ Scheduler process if "rqscheduler" not in sys.argv: return ...
import datetime import sys import django_rq from django.apps import AppConfig class TheFederationConfig(AppConfig): name = "thefederation" verbose_name = "The Federation" def ready(self): # Only register tasks if RQ Scheduler process if "rqscheduler" not in sys.argv: return ...
Increase timeout of clean_duplicate_nodes job
Increase timeout of clean_duplicate_nodes job
Python
agpl-3.0
jaywink/diaspora-hub,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/diaspora-hub,jaywink/the-federation.info,jaywink/the-federation.info
import datetime import sys import django_rq from django.apps import AppConfig class TheFederationConfig(AppConfig): name = "thefederation" verbose_name = "The Federation" def ready(self): # Only register tasks if RQ Scheduler process if "rqscheduler" not in sy...
Increase timeout of clean_duplicate_nodes job
## Code Before: import datetime import sys import django_rq from django.apps import AppConfig class TheFederationConfig(AppConfig): name = "thefederation" verbose_name = "The Federation" def ready(self): # Only register tasks if RQ Scheduler process if "rqscheduler" not in sys.argv: ...
0cdfabf24c01920617535205dfcdba7a187b4d32
doc/_ext/saltdocs.py
doc/_ext/saltdocs.py
def setup(app): """Additions and customizations to Sphinx that are useful for documenting the Salt project. """ app.add_crossref_type(directivename="conf_master", rolename="conf_master", indextemplate="pair: %s; conf/master") app.add_crossref_type(directivename="conf_minion", rolename="...
def setup(app): """Additions and customizations to Sphinx that are useful for documenting the Salt project. """ app.add_crossref_type(directivename="conf_master", rolename="conf_master", indextemplate="pair: %s; conf/master") app.add_crossref_type(directivename="conf_minion", rolename="...
Allow the `conf-log` role to link to the logging documentation.
Allow the `conf-log` role to link to the logging documentation.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
def setup(app): """Additions and customizations to Sphinx that are useful for documenting the Salt project. """ app.add_crossref_type(directivename="conf_master", rolename="conf_master", indextemplate="pair: %s; conf/master") app.add_crossref_type(directivename="conf_min...
Allow the `conf-log` role to link to the logging documentation.
## Code Before: def setup(app): """Additions and customizations to Sphinx that are useful for documenting the Salt project. """ app.add_crossref_type(directivename="conf_master", rolename="conf_master", indextemplate="pair: %s; conf/master") app.add_crossref_type(directivename="conf_min...
db2d0b2f7277f21ce2f500dc0cc4837258fdd200
traceview/__init__.py
traceview/__init__.py
__title__ = 'traceview' __version__ = '0.1.0' __author__ = 'Daniel Riti' __license__ = 'MIT' from .request import Request import resources class TraceView(object): """ Provides access to TraceView API resources. :param api_key: The TraceView API access key. """ def __init__(self, api_key): ...
__title__ = 'traceview' __version__ = '0.1.0' __author__ = 'Daniel Riti' __license__ = 'MIT' from .request import Request import resources class TraceView(object): """ Provides access to TraceView API resources. :param api_key: The TraceView API access key. """ def __init__(self, api_key): ...
Add layers object attribute to TraceView.
Add layers object attribute to TraceView.
Python
mit
danriti/python-traceview
__title__ = 'traceview' __version__ = '0.1.0' __author__ = 'Daniel Riti' __license__ = 'MIT' from .request import Request import resources class TraceView(object): """ Provides access to TraceView API resources. :param api_key: The TraceView API access key. """ ...
Add layers object attribute to TraceView.
## Code Before: __title__ = 'traceview' __version__ = '0.1.0' __author__ = 'Daniel Riti' __license__ = 'MIT' from .request import Request import resources class TraceView(object): """ Provides access to TraceView API resources. :param api_key: The TraceView API access key. """ def __init__(self,...
7f62587e099b9ef59731b6387030431b09f663f9
bot_chucky/helpers.py
bot_chucky/helpers.py
""" Helper classes """ import facebook import requests as r class FacebookData: def __init__(self, token): """ :param token: Facebook Page token :param _api: Instance of the GraphAPI object """ self.token = token self._api = facebook.GraphAPI(self.token) def g...
""" Helper classes """ import facebook import requests as r class FacebookData: def __init__(self, token): """ :param token: Facebook Page token :param _api: Instance of the GraphAPI object """ self.token = token self._api = facebook.GraphAPI(self.token) def g...
Add StackOverFlowData, not completed yet
Add StackOverFlowData, not completed yet
Python
mit
MichaelYusko/Bot-Chucky
""" Helper classes """ import facebook import requests as r class FacebookData: def __init__(self, token): """ :param token: Facebook Page token :param _api: Instance of the GraphAPI object """ self.token = token self._api = facebook.Gra...
Add StackOverFlowData, not completed yet
## Code Before: """ Helper classes """ import facebook import requests as r class FacebookData: def __init__(self, token): """ :param token: Facebook Page token :param _api: Instance of the GraphAPI object """ self.token = token self._api = facebook.GraphAPI(self.t...
a45942894ace282883da3afa10f6739d30943764
dewbrick/majesticapi.py
dewbrick/majesticapi.py
import argparse import json import os import requests BASE_URL = "https://api.majestic.com/api/json" BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')} def get(cmd, params): querydict = {'cmd': cmd} querydict.update(BASE_PARAMS) querydict.update(params) response = requests.get(BASE_URL, para...
import argparse import json import os import requests BASE_URL = "https://api.majestic.com/api/json" BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')} def get(cmd, params): querydict = {'cmd': cmd} querydict.update(BASE_PARAMS) querydict.update(params) response = requests.get(BASE_URL, para...
Handle multiple sites in single request.
Handle multiple sites in single request.
Python
apache-2.0
ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick
import argparse import json import os import requests BASE_URL = "https://api.majestic.com/api/json" BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')} def get(cmd, params): querydict = {'cmd': cmd} querydict.update(BASE_PARAMS) querydict.update(params) response...
Handle multiple sites in single request.
## Code Before: import argparse import json import os import requests BASE_URL = "https://api.majestic.com/api/json" BASE_PARAMS = {'app_api_key': os.environ.get('THEAPIKEY')} def get(cmd, params): querydict = {'cmd': cmd} querydict.update(BASE_PARAMS) querydict.update(params) response = requests.ge...
3446db734ce669e98f8cdeedbabf13dac62c777f
edgedb/lang/build.py
edgedb/lang/build.py
import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec ...
import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar.single as edgeql_spec ...
Fix the creation of parser cache directory
setup.py: Fix the creation of parser cache directory
Python
apache-2.0
edgedb/edgedb,edgedb/edgedb,edgedb/edgedb
import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar...
Fix the creation of parser cache directory
## Code Before: import os.path from distutils.command import build class build(build.build): def _compile_parsers(self): import parsing import edgedb import edgedb.server.main edgedb.server.main.init_import_system() import edgedb.lang.edgeql.parser.grammar.single as edg...
3421fe2542a5b71f6b604e30f2c800400b5e40d8
datawire/store/common.py
datawire/store/common.py
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn): data ...
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = JSONEncoder().encode(frame) return self._store(urn, data) def load(self, urn): data = self....
Fix encoding of store serialisation.
Fix encoding of store serialisation.
Python
mit
arc64/datawi.re,arc64/datawi.re,arc64/datawi.re
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') - data = json.dumps(frame, cls=JSONEncoder) + data = JSONEncoder().encode(frame) ...
Fix encoding of store serialisation.
## Code Before: import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn...
9131a9f2349261900f056c1f920307b0fce176ad
icekit/plugins/image/content_plugins.py
icekit/plugins/image/content_plugins.py
from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from . import models @plugin_pool.register class ImagePlugin(ContentPlugin): model = models.ImageItem category = _('Image') render_template = 'icekit/plugins/image/default.html' r...
from django.utils.translation import ugettext_lazy as _ from django.template import loader from fluent_contents.extensions import ContentPlugin, plugin_pool from . import models @plugin_pool.register class ImagePlugin(ContentPlugin): model = models.ImageItem category = _('Image') raw_id_fields = ['image'...
Implement per-app/model template overrides for ImagePlugin.
Implement per-app/model template overrides for ImagePlugin.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from django.utils.translation import ugettext_lazy as _ + from django.template import loader from fluent_contents.extensions import ContentPlugin, plugin_pool from . import models @plugin_pool.register class ImagePlugin(ContentPlugin): model = models.ImageItem category = _('Image') - ...
Implement per-app/model template overrides for ImagePlugin.
## Code Before: from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from . import models @plugin_pool.register class ImagePlugin(ContentPlugin): model = models.ImageItem category = _('Image') render_template = 'icekit/plugins/image/def...
6058bc795563d482ce1672b3eb933e1c409c6ac8
setup.py
setup.py
from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README...
from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_description=open('README...
Add cliff as a requirement
Add cliff as a requirement
Python
apache-2.0
jxaas/cli
from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_...
Add cliff as a requirement
## Code Before: from distutils.core import setup setup( name='Juju XaaS CLI', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jxaas'], url='http://pypi.python.org/pypi/jxaas/', license='LICENSE.txt', description='CLI for Juju XaaS.', long_descript...
31691ca909fe0b1816d89bb4ccf69974eca882a6
allauth/app_settings.py
allauth/app_settings.py
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present = False if ...
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django import template SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ...
Fix for checking the context processors on Django 1.8
Fix for checking the context processors on Django 1.8 If the user has not migrated their settings file to use the new TEMPLATES method in Django 1.8, settings.TEMPLATES is an empty list. Instead, if we check django.templates.engines it will be populated with the automatically migrated data from settings.TEMPLATE*.
Python
mit
cudadog/django-allauth,bitcity/django-allauth,petersanchez/django-allauth,bittner/django-allauth,manran/django-allauth,jscott1989/django-allauth,petersanchez/django-allauth,JshWright/django-allauth,italomaia/django-allauth,yarbelk/django-allauth,pankeshang/django-allauth,sih4sing5hong5/django-allauth,ZachLiuGIS/django-...
import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured + from django import template SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors...
Fix for checking the context processors on Django 1.8
## Code Before: import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS def check_context_processors(): allauth_ctx = 'allauth.socialaccount.context_processors.socialaccount' ctx_present ...
f941989ef9663ebbb3ba33709dd3c723c86bd2cc
action_log/views.py
action_log/views.py
from __future__ import unicode_literals import json from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import ActionRecord @csrf_exempt def get_action_records(request): action = request.GET.get('action', None) limit = int(r...
from __future__ import unicode_literals import json from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import ActionRecord @csrf_exempt def get_action_records(request): action = request.GET.get('action', None) limit = int(r...
Make it DESC order by id.
Make it DESC order by id.
Python
mit
bradojevic/django-action-log
from __future__ import unicode_literals import json from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import ActionRecord @csrf_exempt def get_action_records(request): action = request.GET.get('action...
Make it DESC order by id.
## Code Before: from __future__ import unicode_literals import json from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import ActionRecord @csrf_exempt def get_action_records(request): action = request.GET.get('action', None) ...
21f08d30bf23056ea3e4fc9804715a57a8978c02
gitdir/host/localhost.py
gitdir/host/localhost.py
import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def __str__(self): ...
import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def __str__(self): ...
Add support for branch arg to LocalHost.clone
Add support for branch arg to LocalHost.clone
Python
mit
fenhl/gitdir
import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def...
Add support for branch arg to LocalHost.clone
## Code Before: import gitdir.host class LocalHost(gitdir.host.Host): def __iter__(self): for repo_dir in sorted(self.dir.iterdir()): if repo_dir.is_dir(): yield self.repo(repo_dir.name) def __repr__(self): return 'gitdir.host.localhost.LocalHost()' def __str__...
838895500f8046b06718c184a4e8b12b42add516
wp2hugo.py
wp2hugo.py
import sys from pprint import pprint from lxml import etree import html2text from wp_parser import WordpressXMLParser from hugo_printer import HugoPrinter def main(): wp_xml_parser = WordpressXMLParser(sys.argv[1]) meta = wp_xml_parser.get_meta() cats = wp_xml_parser.get_categories() tags = wp_xml_...
import sys from pprint import pprint from lxml import etree import html2text from wp_parser import WordpressXMLParser from hugo_printer import HugoPrinter def main(): wp_xml_parser = WordpressXMLParser(sys.argv[1]) wp_site_info = { "meta": wp_xml_parser.get_meta(), "cats": wp_xml_parser.get...
Call HugoPrinter to save config file
Call HugoPrinter to save config file
Python
mit
hzmangel/wp2hugo
import sys from pprint import pprint from lxml import etree import html2text from wp_parser import WordpressXMLParser from hugo_printer import HugoPrinter def main(): wp_xml_parser = WordpressXMLParser(sys.argv[1]) + wp_site_info = { - meta = wp_xml_parser.get_meta() + ...
Call HugoPrinter to save config file
## Code Before: import sys from pprint import pprint from lxml import etree import html2text from wp_parser import WordpressXMLParser from hugo_printer import HugoPrinter def main(): wp_xml_parser = WordpressXMLParser(sys.argv[1]) meta = wp_xml_parser.get_meta() cats = wp_xml_parser.get_categories() ...
71fef8b9696d79f7d6fd024320bc23ce1b7425f3
greatbigcrane/preferences/models.py
greatbigcrane/preferences/models.py
from django.db import models class Preference(models.Model): name = models.CharField(max_length=32, unique=True) value = models.CharField(max_length=512)
from django.db import models class PreferenceManager(models.Manager): def get_preference(self, name, default=None): try: value = Preference.objects.get(name="projects_directory").value except Preference.DoesNotExist: return default class Preference(models.Model): name ...
Add a manager to make getting preferences prettier.
Add a manager to make getting preferences prettier.
Python
apache-2.0
pnomolos/greatbigcrane,pnomolos/greatbigcrane
from django.db import models + + class PreferenceManager(models.Manager): + def get_preference(self, name, default=None): + try: + value = Preference.objects.get(name="projects_directory").value + except Preference.DoesNotExist: + return default class Preference(mo...
Add a manager to make getting preferences prettier.
## Code Before: from django.db import models class Preference(models.Model): name = models.CharField(max_length=32, unique=True) value = models.CharField(max_length=512) ## Instruction: Add a manager to make getting preferences prettier. ## Code After: from django.db import models class PreferenceManager(m...
018acc1817cedf8985ffc81e4fe7e98d85a644da
instructions/base.py
instructions/base.py
class InstructionBase(object): BEFORE=None AFTER=None def __init__(self, search_string): self.search_string = search_string @property def search_string(self): return self._search_string @search_string.setter def search_string(self, value): if value.startswith(self....
class InstructionBase(object): BEFORE=None AFTER=None def __init__(self, search_string): self.search_string = search_string @property def search_string(self): return self._search_string @search_string.setter def search_string(self, value): if value.startswith(self....
Add hack to allow specifying newlines in scripts
Add hack to allow specifying newlines in scripts
Python
unlicense
djmattyg007/IdiotScript
class InstructionBase(object): BEFORE=None AFTER=None def __init__(self, search_string): self.search_string = search_string @property def search_string(self): return self._search_string @search_string.setter def search_string(self, value): ...
Add hack to allow specifying newlines in scripts
## Code Before: class InstructionBase(object): BEFORE=None AFTER=None def __init__(self, search_string): self.search_string = search_string @property def search_string(self): return self._search_string @search_string.setter def search_string(self, value): if value....
ed0f115e600a564117ed540e7692e0efccf5826b
server/nso.py
server/nso.py
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i i...
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i i...
Set time back four hours to EST
Set time back four hours to EST
Python
mit
pennlabs/penn-mobile-server,pennlabs/penn-mobile-server
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split...
Set time back four hours to EST
## Code Before: from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") ...
01b03d46d32dd7f9e027220df0681c4f82fe7217
cumulusci/conftest.py
cumulusci/conftest.py
from pytest import fixture from cumulusci.core.github import get_github_api @fixture def gh_api(): return get_github_api("TestOwner", "TestRepo")
import os from pytest import fixture from cumulusci.core.github import get_github_api @fixture def gh_api(): return get_github_api("TestOwner", "TestRepo") @fixture(scope="class", autouse=True) def restore_cwd(): d = os.getcwd() try: yield finally: os.chdir(d)
Add pytest fixture to avoid leakage of cwd changes
Add pytest fixture to avoid leakage of cwd changes
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
+ import os + from pytest import fixture from cumulusci.core.github import get_github_api @fixture def gh_api(): return get_github_api("TestOwner", "TestRepo") + + @fixture(scope="class", autouse=True) + def restore_cwd(): + d = os.getcwd() + try: + yield + finally: + ...
Add pytest fixture to avoid leakage of cwd changes
## Code Before: from pytest import fixture from cumulusci.core.github import get_github_api @fixture def gh_api(): return get_github_api("TestOwner", "TestRepo") ## Instruction: Add pytest fixture to avoid leakage of cwd changes ## Code After: import os from pytest import fixture from cumulusci.core.github impo...
1d55fe7b1f4f3d70da6867ef7465ac44f8d2da38
keyring/tests/backends/test_OS_X.py
keyring/tests/backends/test_OS_X.py
import sys from ..test_backend import BackendBasicTests from ..py30compat import unittest from keyring.backends import OS_X def is_osx_keychain_supported(): return sys.platform in ('mac','darwin') @unittest.skipUnless(is_osx_keychain_supported(), "Need OS X") class OSXKeychainTestCase(Backen...
import sys from ..test_backend import BackendBasicTests from ..py30compat import unittest from keyring.backends import OS_X def is_osx_keychain_supported(): return sys.platform in ('mac','darwin') @unittest.skipUnless(is_osx_keychain_supported(), "Need OS X") class OSXKeychainTestCase(Backen...
Test passes on OS X
Test passes on OS X
Python
mit
jaraco/keyring
import sys from ..test_backend import BackendBasicTests from ..py30compat import unittest from keyring.backends import OS_X def is_osx_keychain_supported(): return sys.platform in ('mac','darwin') @unittest.skipUnless(is_osx_keychain_supported(), "Need OS X") class OS...
Test passes on OS X
## Code Before: import sys from ..test_backend import BackendBasicTests from ..py30compat import unittest from keyring.backends import OS_X def is_osx_keychain_supported(): return sys.platform in ('mac','darwin') @unittest.skipUnless(is_osx_keychain_supported(), "Need OS X") class OSXKeychai...
e55c5b80d67edcde6c6f31665f39ebfb70660bc1
scripts/update_lookup_stats.py
scripts/update_lookup_stats.py
import re from contextlib import closing from acoustid.script import run_script from acoustid.data.stats import update_lookup_stats def main(script, opts, args): db = script.engine.connect() redis = script.redis for key, count in redis.hgetall('lookups').iteritems(): count = int(count) da...
import re import urllib import urllib2 from contextlib import closing from acoustid.script import run_script from acoustid.data.stats import update_lookup_stats def call_internal_api(func, **kwargs): url = script.config.cluster.base_master_url.rstrip('/') + '/v2/internal/' + func data = dict(kwargs) data...
Handle lookup stats update on a slave server
Handle lookup stats update on a slave server
Python
mit
lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server,lalinsky/acoustid-server
import re + import urllib + import urllib2 from contextlib import closing from acoustid.script import run_script from acoustid.data.stats import update_lookup_stats + + + def call_internal_api(func, **kwargs): + url = script.config.cluster.base_master_url.rstrip('/') + '/v2/internal/' + func + data...
Handle lookup stats update on a slave server
## Code Before: import re from contextlib import closing from acoustid.script import run_script from acoustid.data.stats import update_lookup_stats def main(script, opts, args): db = script.engine.connect() redis = script.redis for key, count in redis.hgetall('lookups').iteritems(): count = int(c...
a797f4862ccfdb84ff87f0f64a6abdc405823215
tests/app/na_celery/test_email_tasks.py
tests/app/na_celery/test_email_tasks.py
from app.na_celery.email_tasks import send_emails class WhenProcessingSendEmailsTask: def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email): mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email') send_emails(sample_email.id) assert...
from app.na_celery.email_tasks import send_emails class WhenProcessingSendEmailsTask: def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member): mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email', return_value=200) send_emails(sample_email.id) ...
Update email task test for members
Update email task test for members
Python
mit
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
from app.na_celery.email_tasks import send_emails class WhenProcessingSendEmailsTask: - def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email): + def it_calls_send_email_to_task(self, mocker, db, db_session, sample_email, sample_member): - mock_send_e...
Update email task test for members
## Code Before: from app.na_celery.email_tasks import send_emails class WhenProcessingSendEmailsTask: def it_calls_send_email_to_task(self, mocker, db, db_session, sample_admin_user, sample_email): mock_send_email = mocker.patch('app.na_celery.email_tasks.send_email') send_emails(sample_email.id)...
05fc957280fecbc99c8f58897a06e23dcc4b9453
elections/uk/forms.py
elections/uk/forms.py
from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(forms.Form): q = forms.C...
from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(forms.Form): q = forms.C...
Fix the postcode form so that it's actually validating the input
Fix the postcode form so that it's actually validating the input
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(...
Fix the postcode form so that it's actually validating the input
## Code Before: from __future__ import unicode_literals from django import forms from django.core.exceptions import ValidationError from candidates.mapit import BaseMapItException from popolo.models import Area from compat import text_type from .mapit import get_areas_from_postcode class PostcodeForm(forms.Form):...
5a7b3e024eba2e279ada9aa33352046ab35b28f5
tests/test_io.py
tests/test_io.py
""" Test the virtual IO system. """ from StringIO import StringIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): """ Fixture to load a new VM. """ return System() ...
""" Test the virtual IO system. """ from io import BytesIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): """ Fixture to load a new VM. """ return System() def te...
Remove StringIO in favor of BytesIO.
Remove StringIO in favor of BytesIO.
Python
bsd-3-clause
travcunn/snake-vm
""" Test the virtual IO system. """ - from StringIO import StringIO + from io import BytesIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): ...
Remove StringIO in favor of BytesIO.
## Code Before: """ Test the virtual IO system. """ from StringIO import StringIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): """ Fixture to load a new VM. """ r...
07d2ffe3c14a6c908a7bf138f40ba8d49bf7b2c3
examples/plot_grow.py
examples/plot_grow.py
# Code source: Óscar Nájera # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 2, 100) y = np.exp(x) plt.plot(x, y) plt.xlabel('$x$') plt.ylabel('$exp(x)$') plt.show()
# Code source: Óscar Nájera # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 2, 100) y = np.exp(x) plt.figure() plt.plot(x, y) plt.xlabel('$x$') plt.ylabel('$\exp(x)$') plt.figure() plt.plot(x, -np.exp(-x)) plt.xlabel('$x$') plt.ylabel('$-\exp(-x)$') plt.show()
Update example for image stacking CSS instuction
Update example for image stacking CSS instuction
Python
bsd-3-clause
lesteve/sphinx-gallery,Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery,Titan-C/sphinx-gallery,lesteve/sphinx-gallery,Titan-C/sphinx-gallery,Eric89GXL/sphinx-gallery,sphinx-gallery/sphinx-gallery
# Code source: Óscar Nájera # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 2, 100) y = np.exp(x) + plt.figure() plt.plot(x, y) plt.xlabel('$x$') - plt.ylabel('$exp(x)$') + plt.ylabel('$\exp(x)$') + + plt.figure() + plt.plot(x, -np.exp(-x)) + p...
Update example for image stacking CSS instuction
## Code Before: # Code source: Óscar Nájera # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt x = np.linspace(-1, 2, 100) y = np.exp(x) plt.plot(x, y) plt.xlabel('$x$') plt.ylabel('$exp(x)$') plt.show() ## Instruction: Update example for image stacking CSS instuction ## Code After: # Code...
be517c8df23826d343b187a4a5cc3d1f81a06b53
test/framework/utils.py
test/framework/utils.py
import os, re from os.path import join as jp from .config import flow_graph_root_dir _http_re = re.compile(r'https?://[^/]*/') def replace_host_port(contains_url): return _http_re.sub('http://x.x/', contains_url) def flow_graph_dir(flow_name): """ Put the generated graph in the workspace root if runni...
import os, re from os.path import join as jp from .config import flow_graph_root_dir _http_re = re.compile(r'https?://.*?/job/') def replace_host_port(contains_url): return _http_re.sub('http://x.x/job/', contains_url) def flow_graph_dir(flow_name): """ Put the generated graph in the workspace root if...
Test framework fix - url replacing handles jenkins url with 'prefix'
Test framework fix - url replacing handles jenkins url with 'prefix'
Python
bsd-3-clause
lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lhupfeldt/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow,lechat/jenkinsflow
import os, re from os.path import join as jp from .config import flow_graph_root_dir - _http_re = re.compile(r'https?://[^/]*/') + _http_re = re.compile(r'https?://.*?/job/') def replace_host_port(contains_url): - return _http_re.sub('http://x.x/', contains_url) + return _http_re.sub('http:/...
Test framework fix - url replacing handles jenkins url with 'prefix'
## Code Before: import os, re from os.path import join as jp from .config import flow_graph_root_dir _http_re = re.compile(r'https?://[^/]*/') def replace_host_port(contains_url): return _http_re.sub('http://x.x/', contains_url) def flow_graph_dir(flow_name): """ Put the generated graph in the workspa...
7418079606a6e24cb0dccfa148b47c3f736e985f
zou/app/blueprints/persons/resources.py
zou/app/blueprints/persons/resources.py
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissio...
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check_admin_permissio...
Allow to set role while creating a person
Allow to set role while creating a person
Python
agpl-3.0
cgwire/zou
from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permiss...
Allow to set role while creating a person
## Code Before: from flask import abort from flask_restful import Resource, reqparse from flask_jwt_extended import jwt_required from zou.app.services import persons_service from zou.app.utils import auth, permissions class NewPersonResource(Resource): @jwt_required def post(self): permissions.check...
a95b1b2b5331e4248fe1d80244c763df4d3aca41
taiga/urls.py
taiga/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r...
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.urls)), url(r...
Set prefix to static url patterm call
Set prefix to static url patterm call
Python
agpl-3.0
jeffdwyatt/taiga-back,bdang2012/taiga-back-casting,WALR/taiga-back,seanchen/taiga-back,gam-phon/taiga-back,EvgeneOskin/taiga-back,CoolCloud/taiga-back,WALR/taiga-back,Rademade/taiga-back,seanchen/taiga-back,taigaio/taiga-back,astronaut1712/taiga-back,astronaut1712/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back...
from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', includ...
Set prefix to static url patterm call
## Code Before: from django.conf import settings from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from .routers import router admin.autodiscover() urlpatterns = patterns('', url(r'^api/v1/', include(router.u...
31af4bf93b8177e8ac03ef96bec926551b40fdcb
cogs/common/types.py
cogs/common/types.py
from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
from aiohttp.web import Application # aiohttp web server application from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
Add aiohttp.web.Application into type aliases
Add aiohttp.web.Application into type aliases
Python
agpl-3.0
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
+ from aiohttp.web import Application # aiohttp web server application from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker
Add aiohttp.web.Application into type aliases
## Code Before: from multidict import MultiDictProxy as Cookies # Type of aiohttp.web.BaseRequest.cookies from sqlalchemy.orm import Session as DBSession # Return from sqlalchemy.orm.sessionmaker ## Instruction: Add aiohttp.web.Application into type aliases ## Code After: from aiohttp.web import Application ...
d495d9500377bad5c7ccfd15037fb4d03fd7bff3
videolog/user.py
videolog/user.py
from datetime import datetime import time import json from videolog.core import Videolog class User(Videolog): def find_videos(self, user): content = self._make_request('GET', '/usuario/%s/videos.json' % user) usuario = json.loads(content) response = [] for video in usuario['usuar...
from datetime import datetime import time import json from videolog.core import Videolog class User(Videolog): def find_videos(self, user, privacy=None): path = '/usuario/%s/videos.json' % user if privacy is not None: path = "%s?privacidade=%s" % (path, privacy) content = self...
Add privacy parameter to User.find_videos
Add privacy parameter to User.find_videos
Python
mit
rcmachado/pyvideolog
from datetime import datetime import time import json from videolog.core import Videolog class User(Videolog): - def find_videos(self, user): + def find_videos(self, user, privacy=None): - content = self._make_request('GET', '/usuario/%s/videos.json' % user) + path = '/usuario/%s...
Add privacy parameter to User.find_videos
## Code Before: from datetime import datetime import time import json from videolog.core import Videolog class User(Videolog): def find_videos(self, user): content = self._make_request('GET', '/usuario/%s/videos.json' % user) usuario = json.loads(content) response = [] for video i...
9d1a53fea17dfc8d48324e510273259615fbee01
pivoteer/writer/hosts.py
pivoteer/writer/hosts.py
import dateutil.parser from pivoteer.writer.core import CsvWriter from core.lookups import geolocate_ip class HostCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record) """ def __init__(self, writer): """ Create a new ...
import dateutil.parser from pivoteer.writer.core import CsvWriter from core.lookups import geolocate_ip class HostCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record) """ def __init__(self, writer): """ Create a new ...
Update historical export with latest data model changes
Update historical export with latest data model changes
Python
mit
LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID
import dateutil.parser from pivoteer.writer.core import CsvWriter from core.lookups import geolocate_ip class HostCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record) """ def __init__(self, writer): "...
Update historical export with latest data model changes
## Code Before: import dateutil.parser from pivoteer.writer.core import CsvWriter from core.lookups import geolocate_ip class HostCsvWriter(CsvWriter): """ A CsvWriter implementation for IndicatorRecord objects with a record type of "HR" (Host Record) """ def __init__(self, writer): """ ...
06eabe9986edfb3c26b2faebb9e07ede72e4781d
wush/utils.py
wush/utils.py
import rq import redis import django from django.conf import settings REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0) class CustomJob(rq.job.Job): def _unpickle_data(self): django.setup() super(CustomJob, self)._unpickle_data() class CustomQueue(rq.Queue): def _...
import rq import redis import django from django.conf import settings REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0) class CustomJob(rq.job.Job): def _unpickle_data(self): django.setup() super(CustomJob, self)._unpickle_data() class CustomQueue(rq.Queue): job_c...
Use the existing class property job_class.
Use the existing class property job_class.
Python
mit
theju/wush
import rq import redis import django from django.conf import settings REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0) class CustomJob(rq.job.Job): def _unpickle_data(self): django.setup() super(CustomJob, self)._unpickle_data() clas...
Use the existing class property job_class.
## Code Before: import rq import redis import django from django.conf import settings REDIS_CLIENT = redis.Redis(settings.REDIS_HOST, settings.REDIS_PORT, db=0) class CustomJob(rq.job.Job): def _unpickle_data(self): django.setup() super(CustomJob, self)._unpickle_data() class CustomQueue(rq.Q...
5c3900e12216164712c9e7fe7ea064e70fae8d1b
enumfields/enums.py
enumfields/enums.py
import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not None and inspect.iscla...
import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not None and inspect.iscla...
Fix 'Labels' class in Python 3.
Fix 'Labels' class in Python 3. In Python 3, the attrs dict will already be an _EnumDict, which has a separate list of member names (in Python 2, it is still a plain dict at this point).
Python
mit
suutari-ai/django-enumfields,jackyyf/django-enumfields,bxm156/django-enumfields,jessamynsmith/django-enumfields
import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not ...
Fix 'Labels' class in Python 3.
## Code Before: import inspect from django.utils.encoding import force_bytes, python_2_unicode_compatible from enum import Enum as BaseEnum, EnumMeta as BaseEnumMeta import six class EnumMeta(BaseEnumMeta): def __new__(cls, name, bases, attrs): Labels = attrs.get('Labels') if Labels is not None a...
e0d811f5146ba2c97af3da4ac904db4d16b5d9bb
python/ctci_big_o.py
python/ctci_big_o.py
p = int(input().strip()) for a0 in range(p): n = int(input().strip())
from collections import deque class Sieve(object): def __init__(self, upper_bound): self.upper_bound = upper_bound + 1 self.primes = [] self.populate_primes() # print("Primes " + str(self.primes)) def is_prime(self, potential_prime): return potential_prime in self.pri...
Solve all test cases but 2
Solve all test cases but 2
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
+ from collections import deque - p = int(input().strip()) - for a0 in range(p): - n = int(input().strip()) + + class Sieve(object): + + def __init__(self, upper_bound): + self.upper_bound = upper_bound + 1 + self.primes = [] + self.populate_primes() + # print("Primes " + st...
Solve all test cases but 2
## Code Before: p = int(input().strip()) for a0 in range(p): n = int(input().strip()) ## Instruction: Solve all test cases but 2 ## Code After: from collections import deque class Sieve(object): def __init__(self, upper_bound): self.upper_bound = upper_bound + 1 self.primes = [] self...
ed92a324cceddce96f2cff51a103c6ca15f62d8e
asterix/test.py
asterix/test.py
""" Utility functions to help testing. """ from unittest.mock import Mock class dummy(object): def __init__(self): self.components = {} def get(self, name, default): if name not in self.components: self.components[name] = Mock() return self.components[name] class dummy...
""" Utility functions to help testing. """ from unittest.mock import Mock class dummy(object): def __init__(self): self.components = {} def get(self, name, default=None): if name not in self.components: self.components[name] = Mock() return self.components[name] class ...
Add facade to mocked components
Add facade to mocked components
Python
mit
hkupty/asterix
""" Utility functions to help testing. """ from unittest.mock import Mock class dummy(object): def __init__(self): self.components = {} - def get(self, name, default): + def get(self, name, default=None): if name not in self.components: self.components[n...
Add facade to mocked components
## Code Before: """ Utility functions to help testing. """ from unittest.mock import Mock class dummy(object): def __init__(self): self.components = {} def get(self, name, default): if name not in self.components: self.components[name] = Mock() return self.components[nam...
adc92c01ef72cd937de7448da515caf6c2704cc3
app/task.py
app/task.py
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. """ class Task(Document): ...
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. """ class Task(Document): ...
Remove closed_at field from Task model
Remove closed_at field from Task model
Python
mit
Zillolo/lazy-todo
from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. "...
Remove closed_at field from Task model
## Code Before: from mongoengine import Document, DateTimeField, EmailField, IntField, \ ReferenceField, StringField import datetime, enum class Priority(enum.IntEnum): LOW = 0, MIDDLE = 1, HIGH = 2 """ This defines the basic model for a Task as we want it to be stored in the MongoDB. """ class T...
435d5d21c2bd2b14998fd206035cc93fd897f6c8
tests/testclasses.py
tests/testclasses.py
from datetime import datetime import unittest from normalize import ( JsonCollectionProperty, JsonProperty, JsonRecord, Record, RecordList, ) class MockChildRecord(JsonRecord): name = JsonProperty() class MockDelegateJsonRecord(JsonRecord): other = JsonProperty() class MockJsonRecord(...
from datetime import datetime import unittest from normalize import ( JsonCollectionProperty, JsonProperty, JsonRecord, Record, RecordList, ) class MockChildRecord(JsonRecord): name = JsonProperty() class MockDelegateJsonRecord(JsonRecord): other = JsonProperty() class MockJsonRecord(...
Remove some traces of this module's predecessor
Remove some traces of this module's predecessor
Python
mit
samv/normalize,tomo-otsuka/normalize,hearsaycorp/normalize
from datetime import datetime import unittest from normalize import ( JsonCollectionProperty, JsonProperty, JsonRecord, Record, RecordList, ) class MockChildRecord(JsonRecord): name = JsonProperty() class MockDelegateJsonRecord(JsonRecord): other = Js...
Remove some traces of this module's predecessor
## Code Before: from datetime import datetime import unittest from normalize import ( JsonCollectionProperty, JsonProperty, JsonRecord, Record, RecordList, ) class MockChildRecord(JsonRecord): name = JsonProperty() class MockDelegateJsonRecord(JsonRecord): other = JsonProperty() class...
e53c572af6f9ee2808ef682cfcfc842fe650ab4b
gribapi/__init__.py
gribapi/__init__.py
from .gribapi import * # noqa from .gribapi import __version__ from .gribapi import bindings_version
from .gribapi import * # noqa from .gribapi import __version__ from .gribapi import bindings_version # The minimum required version for the ecCodes package min_reqd_version_str = '2.14.0' min_reqd_version_int = 21400 if lib.grib_get_api_version() < min_reqd_version_int: raise RuntimeError('ecCodes ...
Check minimum required version of ecCodes engine
Check minimum required version of ecCodes engine
Python
apache-2.0
ecmwf/eccodes-python,ecmwf/eccodes-python
from .gribapi import * # noqa from .gribapi import __version__ from .gribapi import bindings_version + # The minimum required version for the ecCodes package + min_reqd_version_str = '2.14.0' + min_reqd_version_int = 21400 + + if lib.grib_get_api_version() < min_reqd_version_int: + raise Ru...
Check minimum required version of ecCodes engine
## Code Before: from .gribapi import * # noqa from .gribapi import __version__ from .gribapi import bindings_version ## Instruction: Check minimum required version of ecCodes engine ## Code After: from .gribapi import * # noqa from .gribapi import __version__ from .gribapi import bindings...
da5479f4db905ea632009728864793812d56be81
test/test_bill_history.py
test/test_bill_history.py
import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(history['house_passage_res...
import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(history['house_passage_res...
Fix failing test since switching to use bare dates and not full timestamps when appropriate
Fix failing test since switching to use bare dates and not full timestamps when appropriate
Python
cc0-1.0
boblannon/congress,Nolawee/congress,Nolawee/congress,chriscondon/billtext,sunlightlabs/congress-opencongress,boblannon/congress,chriscondon/billtext,unitedstates/congress,sunlightlabs/congress-opencongress,unitedstates/congress
import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(...
Fix failing test since switching to use bare dates and not full timestamps when appropriate
## Code Before: import unittest import bill_info import fixtures import datetime class BillHistory(unittest.TestCase): def test_normal_enacted_bill(self): history = fixtures.bill("hr3590-111")['history'] self.assertEqual(history['house_passage_result'], 'pass') self.assertEqual(self.to_date(history['h...
61a4743b62914559fea18a945f7a780e1394da2f
test/test_export_flow.py
test/test_export_flow.py
import netlib.tutils from libmproxy import flow_export from . import tutils req_get = netlib.tutils.treq( method='GET', headers=None, content=None, ) req_post = netlib.tutils.treq( method='POST', headers=None, ) def test_request_simple(): flow = tutils.tflow(req=req_get) assert flow_expo...
import netlib.tutils from libmproxy import flow_export from . import tutils req_get = netlib.tutils.treq( method='GET', content=None, ) req_post = netlib.tutils.treq( method='POST', headers=None, ) req_patch = netlib.tutils.treq( method='PATCH', path=b"/path?query=param", ) def test_curl_co...
Test exact return value of flow_export.curl_command
Test exact return value of flow_export.curl_command
Python
mit
jvillacorta/mitmproxy,tdickers/mitmproxy,ddworken/mitmproxy,StevenVanAcker/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,tdickers/mitmproxy,mosajjal/mitmproxy,mosajjal/mitmproxy,fimad/mitmproxy,fimad/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,dwfreed/mitmproxy,ParthGanatra/mitmproxy,xaxa89/mitmproxy,mhils/mitmpro...
import netlib.tutils from libmproxy import flow_export from . import tutils req_get = netlib.tutils.treq( method='GET', - headers=None, content=None, ) req_post = netlib.tutils.treq( method='POST', headers=None, ) + req_patch = netlib.tutils.treq( + method='PATCH',...
Test exact return value of flow_export.curl_command
## Code Before: import netlib.tutils from libmproxy import flow_export from . import tutils req_get = netlib.tutils.treq( method='GET', headers=None, content=None, ) req_post = netlib.tutils.treq( method='POST', headers=None, ) def test_request_simple(): flow = tutils.tflow(req=req_get) ...
37cb987503f336362d629619f6f39165f4d8e212
utils/snippets.py
utils/snippets.py
import sys import os import datetime snippet_map = { 'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '), 'time' : datetime.datetime.now().strftime('%I:%M%p '), } keys = '\n'.join(snippet_map.keys()) result = os.popen('printf "%s" | rofi -dmenu ' % keys) selected_key = result.read().strip() os.sy...
import sys import os import datetime snippet_map = { 'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '), 'time' : datetime.datetime.now().strftime('%I:%M%p '), 'sign' : 'Best,\nSameer', } keys = '\n'.join(snippet_map.keys()) result = os.popen('printf "%s" | rofi -dmenu ' % keys) selected_key...
Update snippet script to work with newlines.
Update snippet script to work with newlines.
Python
mit
sam33r/dotfiles,sam33r/dotfiles,sam33r/dotfiles,sam33r/dotfiles
import sys import os import datetime snippet_map = { 'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '), 'time' : datetime.datetime.now().strftime('%I:%M%p '), + 'sign' : 'Best,\nSameer', } keys = '\n'.join(snippet_map.keys()) result = os.popen('printf "%s" | rofi -dme...
Update snippet script to work with newlines.
## Code Before: import sys import os import datetime snippet_map = { 'date' : datetime.datetime.now().strftime('%b %d %G %I:%M%p '), 'time' : datetime.datetime.now().strftime('%I:%M%p '), } keys = '\n'.join(snippet_map.keys()) result = os.popen('printf "%s" | rofi -dmenu ' % keys) selected_key = result.read...
95a6f1fa9e5153d337a3590cea8c7918c88c63e0
openedx/core/djangoapps/embargo/admin.py
openedx/core/djangoapps/embargo/admin.py
import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blacklisting/whitelisting sp...
import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blacklisting/whitelisting sp...
Allow searching restricted courses by key
Allow searching restricted courses by key
Python
agpl-3.0
a-parhom/edx-platform,a-parhom/edx-platform,a-parhom/edx-platform,edx/edx-platform,msegado/edx-platform,philanthropy-u/edx-platform,edx-solutions/edx-platform,cpennington/edx-platform,eduNEXT/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,arbrandes/edx-platform,jolyonb/edx-platform,EDUlib/edx-platform,mitoc...
import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blackl...
Allow searching restricted courses by key
## Code Before: import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blacklisting...
8b6d285f60caa77677aaf3076642a47c525a3b24
parsers/nmapingest.py
parsers/nmapingest.py
import pandas as pd import logging, os import IPy as IP log = logging.getLogger(__name__) df3 = pd.read_csv('nmap.tsv', delimiter='\t') df3.columns = ['host_and_fingerprint', 'port'] df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip('')) df3['port'] = df3['port'].map(l...
import pandas as pd import logging, os import IPy as IP log = logging.getLogger(__name__) df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t') df3.columns = ['host_and_fingerprint', 'port'] df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip('')) df3['port'] = df3['port...
Fix problem lines in nmap parsing.
Fix problem lines in nmap parsing.
Python
apache-2.0
jzadeh/chiron-elk
import pandas as pd import logging, os import IPy as IP - log = logging.getLogger(__name__) - - df3 = pd.read_csv('nmap.tsv', delimiter='\t') + df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t') df3.columns = ['host_and_fingerprint', 'port'] df3['host_and_fingerprint'] = df3['host_and_fingerpri...
Fix problem lines in nmap parsing.
## Code Before: import pandas as pd import logging, os import IPy as IP log = logging.getLogger(__name__) df3 = pd.read_csv('nmap.tsv', delimiter='\t') df3.columns = ['host_and_fingerprint', 'port'] df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip('')) df3['port'] = d...
4ddce41a126395141738f4cd02b2c0589f0f1577
test/utils.py
test/utils.py
from contextlib import contextmanager import sys try: from StringIO import StringIO except ImportError: from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err ...
from contextlib import contextmanager import sys from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stder...
Remove conditional import for py2 support
Remove conditional import for py2 support
Python
mit
bertrandvidal/parse_this
from contextlib import contextmanager import sys - try: - from StringIO import StringIO - except ImportError: - from io import StringIO + from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, ne...
Remove conditional import for py2 support
## Code Before: from contextlib import contextmanager import sys try: from StringIO import StringIO except ImportError: from io import StringIO @contextmanager def captured_output(): """Allows to safely capture stdout and stderr in a context manager.""" new_out, new_err = StringIO(), StringIO() o...
6be3a40010b7256cb5b8fadfe4ef40b6c5691a06
jungle/session.py
jungle/session.py
import boto3 def create_session(profile_name): if not profile_name: return boto3 else: return boto3.Session(profile_name=profile_name)
import sys import boto3 import botocore import click def create_session(profile_name): if profile_name is None: return boto3 else: try: session = boto3.Session(profile_name=profile_name) return session except botocore.exceptions.ProfileNotFound as e: ...
Add error message when wrong AWS Profile Name is given
Add error message when wrong AWS Profile Name is given
Python
mit
achiku/jungle
+ import sys + import boto3 + import botocore + import click def create_session(profile_name): - if not profile_name: + if profile_name is None: return boto3 else: + try: - return boto3.Session(profile_name=profile_name) + session = boto3.Session(profile_na...
Add error message when wrong AWS Profile Name is given
## Code Before: import boto3 def create_session(profile_name): if not profile_name: return boto3 else: return boto3.Session(profile_name=profile_name) ## Instruction: Add error message when wrong AWS Profile Name is given ## Code After: import sys import boto3 import botocore import click ...
a71c6c03b02a15674fac0995d120f5c2180e8767
plugin/floo/sublime.py
plugin/floo/sublime.py
from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): then = time.time() + timeout TIMEOUTS[then].append(lambda: func(*args, **kwargs)) def call_timeouts(): now = time.time() to_re...
from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): then = time.time() + (timeout / 1000.0) TIMEOUTS[then].append(lambda: func(*args, **kwargs)) def call_timeouts(): now = time.time(...
Fix off by 1000 error
Fix off by 1000 error
Python
apache-2.0
Floobits/floobits-neovim,Floobits/floobits-neovim-old,Floobits/floobits-vim
from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): - then = time.time() + timeout + then = time.time() + (timeout / 1000.0) TIMEOUTS[then].append(lambda: fun...
Fix off by 1000 error
## Code Before: from collections import defaultdict import time TIMEOUTS = defaultdict(list) def windows(*args, **kwargs): return [] def set_timeout(func, timeout, *args, **kwargs): then = time.time() + timeout TIMEOUTS[then].append(lambda: func(*args, **kwargs)) def call_timeouts(): now = time....
d0e7c8ec73e36d6391ec57802e6186608196901a
aldryn_apphooks_config/templatetags/namespace_extras.py
aldryn_apphooks_config/templatetags/namespace_extras.py
from django import template from django.core import urlresolvers from ..utils import get_app_instance register = template.Library() @register.simple_tag(takes_context=True) def namespace_url(context, view_name, *args, **kwargs): """ Returns an absolute URL matching given view with its parameters. """ ...
from django import template from django.core import urlresolvers from ..utils import get_app_instance register = template.Library() @register.simple_tag(takes_context=True) def namespace_url(context, view_name, *args, **kwargs): """ Returns an absolute URL matching given view with its parameters. """ ...
Use string.format for performance reasons
Use string.format for performance reasons
Python
bsd-3-clause
aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config
from django import template from django.core import urlresolvers from ..utils import get_app_instance register = template.Library() @register.simple_tag(takes_context=True) def namespace_url(context, view_name, *args, **kwargs): """ Returns an absolute URL matching given view w...
Use string.format for performance reasons
## Code Before: from django import template from django.core import urlresolvers from ..utils import get_app_instance register = template.Library() @register.simple_tag(takes_context=True) def namespace_url(context, view_name, *args, **kwargs): """ Returns an absolute URL matching given view with its para...
d68bdfe0b89137efc6b0c167663a0edf7decb4cd
nashvegas/management/commands/syncdb.py
nashvegas/management/commands/syncdb.py
from django.core.management import call_command from django.core.management.commands.syncdb import Command as SyncDBCommand class Command(SyncDBCommand): def handle_noargs(self, **options): # Run migrations first if options.get('database'): databases = [options.get('database')] ...
from django.core.management import call_command from django.core.management.commands.syncdb import Command as SyncDBCommand class Command(SyncDBCommand): def handle_noargs(self, **options): # Run migrations first if options.get("database"): databases = [options.get("database")] ...
Update style to be consistent with project
Update style to be consistent with project
Python
mit
dcramer/nashvegas,iivvoo/nashvegas,paltman/nashvegas,paltman-archive/nashvegas,jonathanchu/nashvegas
from django.core.management import call_command from django.core.management.commands.syncdb import Command as SyncDBCommand class Command(SyncDBCommand): def handle_noargs(self, **options): # Run migrations first - if options.get('database'): + if options.get("database"): - ...
Update style to be consistent with project
## Code Before: from django.core.management import call_command from django.core.management.commands.syncdb import Command as SyncDBCommand class Command(SyncDBCommand): def handle_noargs(self, **options): # Run migrations first if options.get('database'): databases = [options.get('dat...
6c98f48acd3cc91faeee2d6e24784275eedbd1ea
saw-remote-api/python/tests/saw/test_basic_java.py
saw-remote-api/python/tests/saw/test_basic_java.py
import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int,...
import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fresh_var(java_int,...
Test assumption, composition for RPC Java proofs
Test assumption, composition for RPC Java proofs
Python
bsd-3-clause
GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script
import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") ...
Test assumption, composition for RPC Java proofs
## Code Before: import unittest from pathlib import Path import saw_client as saw from saw_client.jvm import Contract, java_int, cryptol class Add(Contract): def __init__(self) -> None: super().__init__() def specification(self) -> None: x = self.fresh_var(java_int, "x") y = self.fre...
1541af9052d9c12fb3d23832838fce69fcc02761
pywal/export_colors.py
pywal/export_colors.py
import os import pathlib from pywal.settings import CACHE_DIR, TEMPLATE_DIR from pywal import util def template(colors, input_file): """Read template file, substitute markers and save the file elsewhere.""" template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file) export_file = pathlib.Path...
import os import pathlib from pywal.settings import CACHE_DIR, TEMPLATE_DIR from pywal import util def template(colors, input_file): """Read template file, substitute markers and save the file elsewhere.""" template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file) export_file = pathlib.Path...
Convert colors to rgb for putty.
colors: Convert colors to rgb for putty.
Python
mit
dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal
import os import pathlib from pywal.settings import CACHE_DIR, TEMPLATE_DIR from pywal import util def template(colors, input_file): """Read template file, substitute markers and save the file elsewhere.""" template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file) ex...
Convert colors to rgb for putty.
## Code Before: import os import pathlib from pywal.settings import CACHE_DIR, TEMPLATE_DIR from pywal import util def template(colors, input_file): """Read template file, substitute markers and save the file elsewhere.""" template_file = pathlib.Path(TEMPLATE_DIR).joinpath(input_file) export_fil...
6fa924d73df148ad3cfe41b01e277d944071e4dd
equajson.py
equajson.py
from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "parameters" in eqn_dict: ...
from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "parameters" in eqn_dict: ...
Add a line between outputs.
Add a line between outputs.
Python
mit
nbeaver/equajson
from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "par...
Add a line between outputs.
## Code Before: from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "parameters"...
8fb15f3a072d516e477449c2b751226494ee14c5
perfkitbenchmarker/benchmarks/__init__.py
perfkitbenchmarker/benchmarks/__init__.py
"""Contains all benchmark imports and a list of benchmarks.""" import pkgutil def _LoadModules(): result = [] for importer, modname, ispkg in pkgutil.iter_modules(__path__): result.append(importer.find_module(modname).load_module(modname)) return result BENCHMARKS = _LoadModules()
import importlib import pkgutil def _LoadModulesForPath(path, package_prefix=None): """Load all modules on 'path', with prefix 'package_prefix'. Example usage: _LoadModulesForPath(__path__, __name__) Args: path: Path containing python modules. package_prefix: prefix (e.g., package name) to prefix...
Fix a bug in dynamic benchmark loading.
Fix a bug in dynamic benchmark loading. perfkitbenchmarker/benchmarks/__init__.py used ImpImporter.load_module to import benchmarks, which caused an error when they were later imported directly by an import statement. Switched to 'importlib' to resolve.
Python
apache-2.0
GoogleCloudPlatform/PerfKitBenchmarker,lleszczu/PerfKitBenchmarker,GoogleCloudPlatform/PerfKitBenchmarker,msurovcak/PerfKitBenchmarker,tvansteenburgh/PerfKitBenchmarker,ksasi/PerfKitBenchmarker,juju-solutions/PerfKitBenchmarker,gablg1/PerfKitBenchmarker,juju-solutions/PerfKitBenchmarker,msurovcak/PerfKitBenchmarker,sye...
- """Contains all benchmark imports and a list of benchmarks.""" + import importlib import pkgutil - def _LoadModules(): - result = [] - for importer, modname, ispkg in pkgutil.iter_modules(__path__): - result.append(importer.find_module(modname).load_module(modname)) - return result + def _LoadMod...
Fix a bug in dynamic benchmark loading.
## Code Before: """Contains all benchmark imports and a list of benchmarks.""" import pkgutil def _LoadModules(): result = [] for importer, modname, ispkg in pkgutil.iter_modules(__path__): result.append(importer.find_module(modname).load_module(modname)) return result BENCHMARKS = _LoadModules() ## Ins...
167ca3f2a91cd20f38b32ab204855a1e86785c67
st2common/st2common/constants/meta.py
st2common/st2common/constants/meta.py
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. def yaml...
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster. # # Safe...
Add a comment to custom yaml_safe_load() method.
Add a comment to custom yaml_safe_load() method.
Python
apache-2.0
StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2
from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extens...
Add a comment to custom yaml_safe_load() method.
## Code Before: from __future__ import absolute_import import yaml try: from yaml import CSafeLoader as YamlSafeLoader except ImportError: from yaml import SafeLoader as YamlSafeLoader __all__ = ["ALLOWED_EXTS", "PARSER_FUNCS"] # NOTE: We utilize CSafeLoader if available since it uses C extensions and is ...
7a281be50ba1fc59281a76470776fa9c8efdfd54
pijobs/scrolljob.py
pijobs/scrolljob.py
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness...
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness...
Add back rotatation for scroll job.
Add back rotatation for scroll job.
Python
mit
ollej/piapi,ollej/piapi
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): ...
Add back rotatation for scroll job.
## Code Before: import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): sel...
592ffbcd7fbbc29bfd377b5abadb39aa29f1c88d
foyer/tests/conftest.py
foyer/tests/conftest.py
import pytest @pytest.fixture(scope="session") def initdir(tmpdir): tmpdir.chdir()
import pytest @pytest.fixture(autouse=True) def initdir(tmpdir): tmpdir.chdir()
Switch from scope="session" to autouse=True
Switch from scope="session" to autouse=True
Python
mit
iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer
import pytest - @pytest.fixture(scope="session") + @pytest.fixture(autouse=True) def initdir(tmpdir): tmpdir.chdir()
Switch from scope="session" to autouse=True
## Code Before: import pytest @pytest.fixture(scope="session") def initdir(tmpdir): tmpdir.chdir() ## Instruction: Switch from scope="session" to autouse=True ## Code After: import pytest @pytest.fixture(autouse=True) def initdir(tmpdir): tmpdir.chdir()
693dc9d8448740e1a1c4543cc3a91e3769fa7a3e
pySPM/utils/plot.py
pySPM/utils/plot.py
import numpy as np import matplotlib.pyplot as plt def plotMask(ax, mask, color, **kargs): import copy m = np.ma.masked_array(mask, ~mask) palette = copy.copy(plt.cm.gray) palette.set_over(color, 1.0) ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs) def Xdist(ax,left, right, y, color='r',...
import numpy as np import matplotlib.pyplot as plt def plotMask(ax, mask, color, **kargs): import copy m = np.ma.masked_array(mask, ~mask) palette = copy.copy(plt.cm.gray) palette.set_over(color, 1.0) ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs) def Xdist(ax,left, right, y, color='r',...
Add helper function to create a DualPlot
Add helper function to create a DualPlot
Python
apache-2.0
scholi/pySPM
import numpy as np import matplotlib.pyplot as plt def plotMask(ax, mask, color, **kargs): import copy m = np.ma.masked_array(mask, ~mask) palette = copy.copy(plt.cm.gray) palette.set_over(color, 1.0) ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs) def Xdist(ax,left...
Add helper function to create a DualPlot
## Code Before: import numpy as np import matplotlib.pyplot as plt def plotMask(ax, mask, color, **kargs): import copy m = np.ma.masked_array(mask, ~mask) palette = copy.copy(plt.cm.gray) palette.set_over(color, 1.0) ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs) def Xdist(ax,left, righ...
2bd551d7fa8da9d7641998a5515fba634d65bc56
comics/feedback/views.py
comics/feedback/views.py
from django.conf import settings from django.core.mail import mail_admins from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from comics.feedback.forms import FeedbackForm def feedback(request): """Mail feedback to ADMINS""" if reques...
from django.conf import settings from django.core.mail import mail_admins from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from comics.feedback.forms import FeedbackForm def feedback(request): """Mail feedback to ADMINS""" if reques...
Add user information to feedback emails
Add user information to feedback emails
Python
agpl-3.0
jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics
from django.conf import settings from django.core.mail import mail_admins from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from comics.feedback.forms import FeedbackForm def feedback(request): """Mail feedback to ADMI...
Add user information to feedback emails
## Code Before: from django.conf import settings from django.core.mail import mail_admins from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from comics.feedback.forms import FeedbackForm def feedback(request): """Mail feedback to ADMINS""...
c7ab4bc8e0b3dbdd305a7a156ef58dddaa37296c
pystorm/__init__.py
pystorm/__init__.py
from .component import Component, Tuple from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt from .spout import Spout __all__ = [ 'BatchingBolt', 'Bolt', 'Component', 'Spout', 'TicklessBatchingBolt', 'Tuple', ]
''' pystorm is a production-tested Storm multi-lang implementation for Python It is mostly intended to be used by other libraries (e.g., streamparse). ''' from .component import Component, Tuple from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt from .spout import Spout from .version import __version__, VERSI...
Add VERSION and __version__ directly to pystorm namespace
Add VERSION and __version__ directly to pystorm namespace
Python
apache-2.0
pystorm/pystorm
+ ''' + pystorm is a production-tested Storm multi-lang implementation for Python + + It is mostly intended to be used by other libraries (e.g., streamparse). + ''' + from .component import Component, Tuple from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt from .spout import Spout + from .version impor...
Add VERSION and __version__ directly to pystorm namespace
## Code Before: from .component import Component, Tuple from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt from .spout import Spout __all__ = [ 'BatchingBolt', 'Bolt', 'Component', 'Spout', 'TicklessBatchingBolt', 'Tuple', ] ## Instruction: Add VERSION and __version__ directly to pysto...
eb0aeda225cc7c0aef85559857de4cca35b77efd
ratemyflight/urls.py
ratemyflight/urls.py
from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template urlpatterns = patterns("ratemyflight.views", url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$", "airports_for_boundary", name="airports_for_boundary"), url("^api/flight/l...
from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template urlpatterns = patterns("ratemyflight.views", url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$", "airports_for_boundary", name="airports_for_boundary"), url("^api/flig...
Clean up URLS for API and point final URLS to views.
Clean up URLS for API and point final URLS to views.
Python
bsd-2-clause
stephenmcd/ratemyflight,stephenmcd/ratemyflight
from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template urlpatterns = patterns("ratemyflight.views", - url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$", + url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*...
Clean up URLS for API and point final URLS to views.
## Code Before: from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template urlpatterns = patterns("ratemyflight.views", url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$", "airports_for_boundary", name="airports_for_boundary"), url...
1775782f100f9db9ad101a19887ba95fbc36a6e9
backend/project_name/celerybeat_schedule.py
backend/project_name/celerybeat_schedule.py
from celery.schedules import crontab CELERYBEAT_SCHEDULE = { # Internal tasks "clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"}, }
from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module CELERYBEAT_SCHEDULE = { # Internal tasks "clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"}, }
Disable prospector on celery.schedules import
Disable prospector on celery.schedules import
Python
mit
vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate
- from celery.schedules import crontab + from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module CELERYBEAT_SCHEDULE = { # Internal tasks "clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"}, }
Disable prospector on celery.schedules import
## Code Before: from celery.schedules import crontab CELERYBEAT_SCHEDULE = { # Internal tasks "clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"}, } ## Instruction: Disable prospector on celery.schedules import ## Code After: from celery.schedules import crontab # p...
691e3581f1602714fba33f6dcb139f32e0507d23
packages/syft/src/syft/core/node/common/node_table/setup.py
packages/syft/src/syft/core/node/common/node_table/setup.py
from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class SetupConfig(Base): __tablename__ = "setup" id = Column(Integer(), primary_key=True, autoincrement=True) domain_name = Column(String(255), default="") node_id = Column(String...
from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import Boolean # relative from . import Base class SetupConfig(Base): __tablename__ = "setup" id = Column(Integer(), primary_key=True, autoincrement=True) domain_name = Column(String(255), default=...
ADD description / contact / daa fields
ADD description / contact / daa fields
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String + from sqlalchemy import Boolean # relative from . import Base class SetupConfig(Base): __tablename__ = "setup" id = Column(Integer(), primary_key=True, autoincrement=True) domain_name = ...
ADD description / contact / daa fields
## Code Before: from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class SetupConfig(Base): __tablename__ = "setup" id = Column(Integer(), primary_key=True, autoincrement=True) domain_name = Column(String(255), default="") node_id...
b5e368437a600d78e22a53abe53c0103b20daa24
_python/main/migrations/0003_auto_20191029_2015.py
_python/main/migrations/0003_auto_20191029_2015.py
from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20191007_1639'), ] operations = [ migrations.AlterField( model_name='contentnode', name='headnote', field=main.mode...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20191007_1639'), ] operations = [ migrations.AlterField( model_name='default', name='url', field=models.URLField(max_length=1024), ...
Repair migration, which was a no-op in SQL and was 'faked' anyway.
Repair migration, which was a no-op in SQL and was 'faked' anyway.
Python
agpl-3.0
harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o
from django.db import migrations, models - import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20191007_1639'), ] operations = [ migrations.AlterField( - model_name='contentnode', - name='headnote...
Repair migration, which was a no-op in SQL and was 'faked' anyway.
## Code Before: from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20191007_1639'), ] operations = [ migrations.AlterField( model_name='contentnode', name='headnote', ...
1dc2856368e5e6852b526d86a0c78c5fe10b1550
myhronet/models.py
myhronet/models.py
import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, ...
import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, ...
Fix hashcode generation for existing URLs
Fix hashcode generation for existing URLs
Python
mit
myhro/myhronet,myhro/myhronet
import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, ...
Fix hashcode generation for existing URLs
## Code Before: import string from django.db import models class Blacklist(models.Model): domain = models.CharField(max_length=255, unique=True, null=True) def __unicode__(self): return self.domain class URL(models.Model): hashcode = models.CharField(max_length=10, unique=True, ...
1cad9ab61148173b0f61971805b3e6203da3050d
faker/providers/en_CA/ssn.py
faker/providers/en_CA/ssn.py
from __future__ import unicode_literals from ..ssn import Provider as SsnProvider class Provider(SsnProvider): ssn_formats = ("### ### ###",) @classmethod def ssn(cls): return cls.bothify(cls.random_element(cls.ssn_formats))
from __future__ import unicode_literals from ..ssn import Provider as SsnProvider import random class Provider(SsnProvider): #in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum #this function essentially reverses the checksum steps to create a...
Update Canada SSN/SIN provider to create a valid number
Update Canada SSN/SIN provider to create a valid number The first revision generated a random number in the correct format. This commit creates a SIN number that passes the checksum as described here http://http://en.wikipedia.org/wiki/Social_Insurance_Number
Python
mit
jaredculp/faker,trtd/faker,xfxf/faker-python,HAYASAKA-Ryosuke/faker,johnraz/faker,joke2k/faker,joke2k/faker,venmo/faker,ericchaves/faker,xfxf/faker-1,GLMeece/faker,danhuss/faker,beetleman/faker,thedrow/faker,meganlkm/faker,yiliaofan/faker,MaryanMorel/faker
from __future__ import unicode_literals from ..ssn import Provider as SsnProvider + import random class Provider(SsnProvider): - ssn_formats = ("### ### ###",) + #in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum + #this functio...
Update Canada SSN/SIN provider to create a valid number
## Code Before: from __future__ import unicode_literals from ..ssn import Provider as SsnProvider class Provider(SsnProvider): ssn_formats = ("### ### ###",) @classmethod def ssn(cls): return cls.bothify(cls.random_element(cls.ssn_formats)) ## Instruction: Update Canada SSN/SIN provider to cre...
dd1ed907532526a4a70694c46918136ca6d93277
nqueens/nqueens.py
nqueens/nqueens.py
from nqueens.chessboard import Chessboard from nqueens.printer import Printer from nqueens.solver import Solver board = Chessboard.create(8) solver = Solver.create(board) solution = solver.solve() if solution is not None: printer = Printer.create(solution) printer.printBoard()
import os import sys import getopt sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from nqueens.chessboard import Chessboard from nqueens.printer import Printer from nqueens.solver import Solver def main(): try: n = parse_command_line() except ValueError as e: ...
Add ability to run problems from command line
Add ability to run problems from command line
Python
mit
stevecshanks/nqueens
+ import os + import sys + import getopt + sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from nqueens.chessboard import Chessboard from nqueens.printer import Printer from nqueens.solver import Solver + def main(): + try: + n = parse_command_line() + exce...
Add ability to run problems from command line
## Code Before: from nqueens.chessboard import Chessboard from nqueens.printer import Printer from nqueens.solver import Solver board = Chessboard.create(8) solver = Solver.create(board) solution = solver.solve() if solution is not None: printer = Printer.create(solution) printer.printBoard() ## Instruction:...
c9cc5585e030951a09687c6a61a489ec51f83446
cr2/plotter/__init__.py
cr2/plotter/__init__.py
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot import AttrConf def register_forwarding_arg(arg_name): """Allows the user to register args to be forwarded to matplotlib """ if arg_name not in AttrConf.ARGS_TO_FORWARD: AttrConf.ARGS_TO_FORWARD.appen...
Enable user specified arg forwarding to matplotlib
plotter: Enable user specified arg forwarding to matplotlib This change allows the user to register args for forwarding to matplotlib and also unregister the same. Change-Id: If53dab43dd4a2f530b3d1faf35582206ac925740 Signed-off-by: Kapileshwar Singh <d373e2b6407ea84be359ce4a11e8631121819e79@arm.com>
Python
apache-2.0
JaviMerino/trappy,joelagnel/trappy,bjackman/trappy,derkling/trappy,ARM-software/trappy,sinkap/trappy,JaviMerino/trappy,joelagnel/trappy,ARM-software/trappy,derkling/trappy,bjackman/trappy,sinkap/trappy,ARM-software/trappy,ARM-software/trappy,bjackman/trappy,sinkap/trappy,joelagnel/trappy,sinkap/trappy,JaviMerino/trappy...
"""Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot + import AttrConf + + def register_forwarding_arg(arg_name): + """Allows the user to register args to + be forwarded to matplotlib + """ + if arg_name not in AttrConf.ARGS_TO_FORWARD: + At...
Enable user specified arg forwarding to matplotlib
## Code Before: """Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot ## Instruction: Enable user specified arg forwarding to matplotlib ## Code After: """Init Module for the Plotter Code""" import pandas as pd from LinePlot import LinePlot import AttrConf def register_forwardi...